“ if”语句不适用于输入变量

时间:2019-01-12 23:54:58

标签: python python-3.x

好吧,我是一个初学者,我的变量(guess)输入不适用于if语句:

当我输入从09的输入数字时,我希望它打印出Right number!,否则它打印出另一条消息:

guess = input("Choose a number between 0-9: ")
if guess <=9 and guess >=0:
    print("Right number!")
else:
    print("The number you entered is out of range try again!")

1 个答案:

答案 0 :(得分:0)

input()函数返回字符串,而不是 number (例如"127",而不是127)。您必须将其转换为数字,例如。 G。借助int()函数。

所以不是

guess = input("Choose a number between 0-9: ")

使用

guess = int(input("Choose a number between 0-9: "))

guest变量而不是字符串中获取整数
或者,您可以通过2条语句来达到目的-第一条可以是原始语句,第二条可以是转换语句:

guess = input("Choose a number between 0-9: ")
guess = int(guess)

注意:

代替

if guess <=9 and guess >=0:

你可以写

if 0 <= guess <= 9:           # don't try it in other programming languages

if guess in range(10):        # 0 inclusive to 10 exclusive