错误捕获字符串和整数

时间:2016-12-29 09:18:24

标签: python

我正在尝试使用try-except catch创建一个错误陷阱,以防止用户输入字符串,但是当我运行代码时,它不会捕获错误。

info=False
count=input("How many orders would you like to place? ")
while info == False:
    try:
        count*1
        break
    except TypeError:
        print("Please enter a number next time.")
        quit()
#code continues        

4 个答案:

答案 0 :(得分:0)

input返回的值为string

你可以尝试这样的事情:

try:
    val = int(userInput)
except ValueError:
    print("That's not an int!")

答案 1 :(得分:0)

strìnt在python中完美运行:'a'*3 = 'aaa'。您的try区块中不会出现任何例外情况。

如果您想从int中解除str

try:
    int(count)
except ValueError:
    do_something_else()

注意:它是ValueError而不是TypeError

答案 2 :(得分:0)

更好的方法是使用try除块

while True:
    try:
        count=int(input("How many orders would you like to place? "))
        break
    except:
        print("This is not a valid input. Try again\n")

print(count)

答案 3 :(得分:0)

您可以通过以下方式使用TypeError

while True:
    try:
        count=input("How many orders would you like to place? ")
        count += 1
    except TypeError:
        print("Please enter a number next time.")
        break

注意,字符串可以在python中乘以整数,所以我使用了加法运算,因为我们不能在python中将整数添加到字符串。

相关问题