gpt4 book ai didi

python - 如何避免 ValueError 并在 python2 中仅获取整数输入?

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:20 26 4
gpt4 key购买 nike

python valueerror

#!/usr/bin/env python

# getting user input
height = int(raw_input("height: "))

while (height < 0 or height > 23):
height = int(raw_input("height: "))

# building the "pyramid"
spaceCount = height
hashCount = 1

for i in range(height):
assert height != 0
hashCount += 1
spaceCount -= 1
print " " * spaceCount,
print "#" * hashCount

如果输入不是整数,代码应不断提示用户。但如何呢?

最佳答案

您需要捕获异常。

 height = 24
while (height < 0 or height > 23):
try:
height = int(raw_input("heightL "))
except ValueError:
print "Height needs to be an integer. Try again."

关于python - 如何避免 ValueError 并在 python2 中仅获取整数输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com