简体   繁体   English

为什么即使输入是整数,我也会不断收到 TypeError?

[英]Why do I keep getting TypeError even though input is an interger?

I'm coding something for a school project which asks the user for a number between 0-10 and I have no idea why I keep getting a TypeError even though the input is converted to integer using a list.我正在为一个学校项目编写一些代码,该项目要求用户输入一个介于 0-10 之间的数字,我不知道为什么即使使用列表将输入转换为 integer,我仍然会收到 TypeError。 Any help please?请问有什么帮助吗? I'm doing this on Wing IDE 101.我在 Wing IDE 101 上执行此操作。

numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
while True:
    num = ''
    while num == '':
        try:
            num = input("Please enter a number: ")
            num = int(num)
        except ValueError:
            if num in numbers:
                num = numbers.index(num)
                num = int(num)
            else:
                print('Invalid input, please enter valid input')
    if num == 0:
        print("Thank you for using this program")
        break
    elif num < 0 or num > 10:
        print("This is an invalid number, please enter a valid number.")
        print()
        continue

I think this the reason:我觉得是这个原因:

When your input is not a valid input like "asdf" .当您的输入不是像"asdf"这样的有效输入时。 It will jump out the inner while loop.它会跳出内部的while循环。 Because you inner while loop condition is num == '' while num is "asdf" now.因为你内部的 while 循环条件是num == ''num现在是"asdf"

You should just put num = "" under print('Invalid input, please enter valid input') and your code will work and not raise TypeError anymore.您只需将num = ""放在print('Invalid input, please enter valid input')下,您的代码就可以正常工作并且不再引发 TypeError。

Complete code below:完整代码如下:

numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
while True:
    num = ''
    while num == '':
        try:
            num = input("Please enter a number: ")
            num = int(num)
        except ValueError:
            if num in numbers:
                num = numbers.index(num)
                num = int(num)
            else:
                print('Invalid input, please enter valid input')
                num = ""
    if num == 0:
        print("Thank you for using this program")
        break
    elif num < 0 or num > 10:
        print("This is an invalid number, please enter a valid number.")
        print()
        continue

In fact your code could be simpfy to one loop:实际上,您的代码可以简化为一个循环:

numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
while True:
    num = input("Please enter a number: ")
    if num in numbers:
        num = numbers.index(num)
    else:
        try:
            num = int(num)
        except ValueError:
            print("Invalid input, please enter valid input")
            continue
    if num == 0:
        print("Thank you for using this program")
        break
    elif num < 0 or num > 10:
        print("This is an invalid number, please enter a valid number.")

What happens to you can happen a lot in dynamic language since the types are resolved on runtime rather on design time, so sometimes it is hard to figure.发生在你身上的事情在动态语言中可能会发生很多,因为类型是在运行时而不是在设计时解析的,所以有时很难确定。

First, separate the user_input from the number ( num ) you are evaluating, into 2 different parameters (one for user input string and one for integer) - I know it does not matter on Python, but it is a good practice.首先,将user_input与您正在评估的数字 ( num ) 分离为 2 个不同的参数(一个用于用户输入字符串,一个用于整数) - 我知道在 Python 上并不重要,但这是一个很好的做法。

Now your num value will only be assigned on a successful parsing.现在,您的num值只会在成功解析时分配。 No need for continue at the end of the loop as well在循环结束时也不需要continue

Code Snippet代码片段

numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
while True:
    user_input = ''
    num = None  # default invalid value
    while num is None:
        try:
            user_input = input("Please enter a number: ")
            num = int(user_input)
        except ValueError:
            if user_input in numbers:
                num = numbers.index(user_input)
            else:
                print('Invalid input, please enter valid input')
                print()
    if num == 0:
        print("Thank you for using this program")
        break
    elif num < 0 or num > 10:
        print("This is an invalid number, please enter a valid number.")
        print()

Debug Output调试Output

Please enter a number: 1
Please enter a number: one
Please enter a number: 11
This is an invalid number, please enter a valid number.

Please enter a number: -1
This is an invalid number, please enter a valid number.

Please enter a number: no numbder
Invalid input, please enter valid input

Please enter a number: 0
Thank you for using this program

Process finished with exit code 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这样,即使我将其放置在一个类中,也始终收到未定义Driver Sponsor的错误? - Why is it so that I keep getting the error that Driver sponsor is not defined, even though I placed it within a class? 为什么我一直收到此错误:TypeError:&#39;bool&#39;对象不可迭代? - Why do I keep getting this error: TypeError: 'bool' object is not iterable? 即使元素确实存在,我仍然在 selenium 中收到 NoSuchElementException - I keep getting a NoSuchElementException in selenium even though the element DOES exist 即使我安装了它,也无法找到 selenium - Keep getting selenium cant be found even though i installed it 为什么我会不断尝试输入6次而不是3次? - Why do I keep getting 6 input attempts instead of 3? 为什么我得到:TypeError: unsupported operand type(s) for -: 'str' and 'str' 即使 dtypes 显示所有 float64 - Why am I getting: TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ even though dtypes is showing all float64 即使我使用 np.random.choice(),我是否有理由一遍又一遍地获得相同的输入? - Is there a reason why I am getting the same input over and over even though I am using np.random.choice()? 为什么 TypeError 即使需要 2 个 arguments - Why TypeError even though it takes 2 arguments 为什么我在页面上找到了StaleElementReferenceException,但仍然找到了该元素? - Why am I getting a StaleElementReferenceException even though it found the element on the page? 为什么我在 pygame 中调用“屏幕”时总是收到“TypeError: 'module' object is not callable”? - why do I keep getting “TypeError: 'module' object is not callable” when calling 'screen' in pygame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM