2016-03-02 168 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:請指出答案的錯誤 –