-1
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

我添加了一条错误消息,用于输入低于或高于所述数字的数字,但是如果可能的话,如果用户输入字母或根本没有输入,我想向用户显示一条错误消息。

4

2 回答 2

4

尝试在尝试中换行输入行,除了:

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")
于 2013-03-08T00:40:05.100 回答
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
于 2013-03-08T00:42:08.267 回答