在Python中,如果输入有效,如何使条件if循环不执行?

时间:2016-06-29 02:27:49

标签: python validation loops input

#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user invalid guess and do not count that as an attempt

我的问题是,即使用户猜到0到100之间的数字,它仍会打印出“无效猜测。再试一次”。如果可以接受输入(1-100),如何控制循环跳过print语句并重复问题?提前谢谢!

favoriteNumber = 7
attempts = 0

guess = raw_input("Guess a number between 0 and 100: ")

if (guess  < 0) or (guess > 100):
    print "Invalid guess. Try again"
    guess = raw_input("Guess a number between 0 and 100: ")

attempts1 = str(attempts)
print "it took " + attempts1 + "attempts."

3 个答案:

答案 0 :(得分:0)

在Python 2.7.10中,似乎如果不将字符串转换为整数,它会接受它,但适用于数字的所有规则都返回false。 这是一个有效的例子:

favoriteNumber = 7
attempts = 0

guess = raw_input("Guess a number between 0 and 100: ")

if (int(guess)  < 0) or (int(guess) > 100):
    print "Invalid guess. Try again"
    guess = raw_input("Guess a number between 0 and 100: ")

attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."

在Python 3.4中,原始代码会产生错误,它会告诉您它是字符串而不是整数。但是,就像保罗所说,你可以将raw_input放在int()命令中。

答案 1 :(得分:0)

你raw_input返回一个字符串,该字符串始终为> 100.将其转换为int(raw_input())

的数字

答案 2 :(得分:0)

使用输入而不是raw_input,因此您获得整数而不是字符串

favoriteNumber = 7
attempts = 0


while True:
    guess = input("Guess a number between 0 and 100: ")
    if (guess  < 0) or (guess > 100):

        attempts=attempts+1
        print "Invalid guess. Try again"
    else:
        attempts=attempts+1
        break

attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."