输入字符串字符

时间:2019-06-21 19:46:13

标签: python exception

`我正在尝试触发此异常,以便在输入字符串而不是int时可以看到python是否可以处理。

我尝试将ValueError语句更改为其他类型的异常,例如TypeError而不是Value Error。我还检查了语法问题。

try:
    u_list.append(userInput)
    if userInput % 2 == 0:
        list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
    # a string character instead of an int. Why is this 
    #not being invoked
    #when I put a str character in?!?!
    print("da fuq!?!. That ain't no int!")

我试图让程序打印我输入(k)之类的字符串字符时显示的最后一行,相反,它会抛出错误消息。

这是有人要求的完整代码:

    u_list = []
    list_sum = 0
    for i in range(10):
        userInput = int(input("Gimme a number: "))
        try:
                u_list.append(userInput)
                if userInput % 2 == 0:
                    list_sum += userInput
        except ValueError: #this is supposed to be thrown when I put
                            # a string character instead of an int. Why is this not being invoked
                            #when I put a str character in?!?!
                print("da fuq!?!. That ain't no int!")

    print("u_list: {}".format(u_list))
    print("The sum of tha even numbers in u_list is: {}.".format(list_sum))

2 个答案:

答案 0 :(得分:0)

未能将字符串转换为int时将抛出

ValueErrorinput()(或Python 2中的raw_input())将始终返回一个字符串,即使该字符串包含数字,并且尝试将其视为整数也不会为您隐式转换。尝试这样的事情:

try:
    userInput = int(userInput)
except ValueError:
    ...
else:
    # Runs if there's no ValueError
    u_list.append(userInput)
    ...

答案 1 :(得分:0)

在try-except块中添加userInput,并检查其是否为ValueError。如果它是整数,则将其附加到列表中。

这是代码:

u_list = []
list_sum = 0
for i in range(10):
    try:
        userInput = int(input("Gimme a number: "))
    except ValueError:
            print("da fuq!?!. That ain't no int!")

    u_list.append(userInput)
    if userInput % 2 == 0:
        list_sum += userInput

print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))

希望对您有帮助!