2016-03-02 542 views
1

如果用户的猜测大于或小于随机生成的值,Python循环不想循环回来。它要么退出循环,要么创建一个无限循环。我哪里错了?对不起,如果我的格式糟糕,第一次海报。Python 3.4:while循环不循环

import random 

correct = random.randint(1, 100) 
tries = 1 
inputcheck = True 
print("Hey there! I am thinking of a numer between 1 and 100!") 
while inputcheck: 
    guess = input("Try to guess the number! ") 
    #here is where we need to make the try statement 
    try: 
     guess = int(guess) 
    except ValueError: 
     print("That isn't a number!") 
     continue 
    if 0 <= guess <= 100: 
     inputcheck = False 
    else: 
     print("Choose a number in the range!") 
     continue 
    if guess == correct: 
     print("You got it!") 
     print("It took you {} tries!".format(tries)) 
     inputcheck = False 
    if guess > correct: 
     print("You guessed too high!") 
     tries = tries + 1 
    if guess < correct: 
     print("You guessed too low!") 
     tries = tries + 1 

    if tries >= 7: 
     print("Sorry, you only have 7 guesses...") 
     keepGoing = False 
+2

你的循环是'inputcheck',您在设置为'FALSE' '如果0 <=猜测<= 100'块。如果你这样做,你为什么期望它继续运行? – Blckknght

回答

2

问题是与这一行:

if 0 <= guess <= 100: 
    inputcheck = False 

这将终止每当用户输入0和100之间的数字环路可以改写该部分为:

if not 0 <= guess <= 100: 
    print("Choose a number in the range!") 
    continue 
+1

非常感谢,这帮助了一大堆。我不敢相信我忽略了这一点! – cparks10

1

正确的代码如下:

import random 

correct = random.randint(1, 100) 
tries = 1 
inputcheck = True 
print("Hey there! I am thinking of a numer between 1 and 100!") 
while inputcheck: 
    guess = input("Try to guess the number! ") 
    #here is where we need to make the try statement 
    try: 
     guess = int(guess) 
    except ValueError: 
     print("That isn't a number!") 
     continue 
    if 0 > guess or guess > 100: 
     print("Choose a number in the range!") 
     continue 
    if guess == correct: 
     print("You got it!") 
     print("It took you {} tries!".format(tries)) 
     inputcheck = False 
    if guess > correct: 
     print("You guessed too high!") 
     tries = tries + 1 
    if guess < correct: 
     print("You guessed too low!") 
     tries = tries + 1 
    if tries > 7: 
     print("Sorry, you only have 7 guesses...") 
     inputcheck = False 

这里的问题是,当guess的值介于0和100之间时,您将inputcheck设置为False。将此值更改为False,并且循环已退出,因为此时不再是True

此外,你应该改变而循环的最后if情况,因为现在这个修复无限期运行的情况下:

if tries > 7: 
    print("Sorry, you only have 7 guesses...") 
    inputcheck = False 
+0

对于downvoter:请指出答案的错误 –