python 中断条件

yquaqz18  于 2022-10-30  发布在  Python
关注(0)|答案(6)|浏览(160)

假设用户输入1到10之间的数字,并且假设代码检查3个条件:如果输入不是数字,则要求再次输入;如果输入不在1-10范围内,则要求再次输入;如果数字在1-10范围内,则中断循环并将值存储在变量中。前两个检查运行正常,但最后一个检查不起作用,这个循环没有中断,它像其他条件一样说输入无效。2问题是什么?

while True:
        num_guess = input("How many times you want to guess [1-10]: ") # Asking for number of guess
        if num_guess != int: # Checking for non number input
            print("Invalid input")
        elif int(num_guess) < 1 or int(num_guess) > 10: # Checking for out of range input
            print("Invalid input")
        elif 1 <= int(num_guess) <= 10: # if input is in the range just break the loop and store the answer
            break
gcuhipw9

gcuhipw91#

默认情况下,input()方法接受您的输入并将其转换为字符串输入。因此,即使您输入数字12,输入也会转换为“12”并存储在num_guess中。因此,检查输入是否为数字的最佳方法是使用isdigit()方法。
因此,代码的第3行应编写为

if not num_guess.isdigit():
hrysbysz

hrysbysz2#

使用if not num_guess.isnumeric()检查字符串的所有字符是否都是数字字符。num_guess始终是字符串,因此检查类型的答案建议是错误的。

8hhllhi2

8hhllhi23#

if num_guess != int应为:

try:
    num_guess = int(num_guess)
except ValueError:
    print("Not a number!")
    continue

参考:How to check if string input is a number?

lqfhib0f

lqfhib0f4#

if num_guess != int替换为if type(num_guess) != int。这是因为您需要检查数字是什么数据类型,将相等运算符与int一起使用将尝试检查对象是否为classint
在python中,一切都是对象(或数据类型),甚至是对象的构造函数。

kqqjbcuj

kqqjbcuj5#

如果你想检查输入是否是一个数字,你必须使用type(YOUR_VARIABLE)来获取变量的类型,这样python就会检查它的类型,返回如下的值:“int”,“string”,“float”,顺便说一下,你可以检查变量是否是整型!
或者干脆不读它,偷取下面代码:

while True:
        num_guess = input("How many times you want to guess [1-10]: ") # Asking for number of guess
        if type(num_guess) != int: # Checking for non number input
            print("Invalid input")
        elif int(num_guess) < 1 or int(num_guess) > 10: # Checking for out of range input
            print("Invalid input")
        elif 1 <= int(num_guess) <= 10: # if input is in the range just break the loop and store the answer
            break

但我仍然不是100%肯定,所以你可以检查它,并纠正我,如果我做错了什么

91zkwejq

91zkwejq6#

它一直显示“无效输入”的原因是因为num_guess始终是字符串。
你可以试试这样,我希望这对你有帮助。


# store input result

result: int

while True:
    num_guess = input(">> How many times you want to guess [1-10]: ") # Asking for number of guess

    try:
        int(num_guess) # raise ValueError if num_guess is NaN

        if int(num_guess) < 1 or int(num_guess) > 10: # Checking for out of range input
            print(">> Interger from 1 to 10 required.")
        elif 1 <= int(num_guess) <= 10: # if input is in the range just break the loop and store the answer
            # store the value in the result variable
            result = int(num_guess)
            print(">> Saving...")
            break
    except ValueError:
        print(">> Interger 1 ... 10 required.")

相关问题