print("this program will calculate the area")
input("[Press any key to start]")
width = int(input("enter width"))
while width < 0 or width > 1000:
print ("please chose a number between 0-1000")
width = int(input("enter width"))
height = int(input("Enter Height"))
while height < 0 or height > 1000:
print("please chose a number between 0-1000")
widht = int(input("Enter Height"))
area = width*height
print("The area is:",area
我添加了一条错误消息,用于输入低于或高于所述数字的数字,但是如果可能的话,我想向用户显示错误消息,如果他们输入一封信或什么都没有。
答案 0 :(得分:4)
尝试在try中包装行输入行,但不包括:
try:
width = int(input("enter width"))
except:
width = int(input("enter width as integer"))
或更好:将其包装在函数中:
def size_input(message):
try:
ret = int(input(message))
return ret
except:
return size_input("enter a number")
width = size_input("enter width")
答案 1 :(得分:2)
您可以使用try-except
,int()
如果传递给它的参数无效,则会引发异常:
def valid_input(inp):
try:
ret=int(inp)
if not 0<ret<1000:
print ("Invalid range!! Try Again")
return None
return ret
except:
print ("Invalid input!! Try Again")
return None
while True:
rep=valid_input(input("please chose a number between 0-1000: "))
if rep:break
print(rep)
<强>输出:强>
please chose a number between 0-1000: abc
Invalid input!! Try Again
please chose a number between 0-1000: 1200
Invalid range!! Try Again
please chose a number between 0-1000: 123abc
Invalid input!! Try Again
please chose a number between 0-1000: 500
500