Python- 整数输入,输入字母时的错误提示

-1 投票
2 回答
14144 浏览
提问于 2025-04-17 18:21
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

我已经添加了一个错误提示,告诉用户输入的数字如果低于或高于规定的范围就会出错。不过,如果可以的话,我还想在用户输入字母或者什么都不输入的时候,给他们显示一个错误提示。

2 个回答

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
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")

撰写回答