2015-12-08 89 views
-1
import random 


print("Hey there, player! Welcome to Emily's number-guessing game! ") 
name=input("What's your name, player? ") 

random_integer=random.randint(1,25) 

tries=0 
tries_remaining=10 

while tries < 10: 
    guess = input("Try to guess what random integer I'm thinking of, {}! ".format(name)) 
    tries += 1 
    tries_remaining -= 1 

# The next two small blocks of code are the problem. 

    try: 
    guess_num = int(guess) 
    except: 
    print("That's not a whole number! ") 
    tries-=1 
    tries_remaining+=1 


    if not guess_num > 0 or not guess_num < 26: 
    print("Sorry, try again! That is not an integer between 1 and 25! ") 
    break 



    elif guess_num == random_integer: 
    print("Nice job, you guessed the right number in {} tries! ".format(tries)) 
    break 


    elif guess_num < random_integer: 
    if tries_remaining > 0: 
     print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining. ".format(int(tries_remaining))) 
     continue 
    else: 
     print("Sorry, but the integer I was thinking of was {}! ".format(random_integer)) 
     print("Oh no, looks like you've run out of tries! ") 



    elif guess_num > random_integer: 
    if tries_remaining > 0: 
     print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining. ".format(int(tries_remaining))) 
     continue 
    else: 
     print("Sorry, but the integer I was thinking of was {}! ".format(random_integer)) 
     print("Oh no, looks like you've run out of tries! ") 

我會盡量解釋這一點以及我可以...我試圖讓問題區域允許輸入猜測後再次用戶輸入除1和25之間的整數以外的任何東西,但我無法弄清楚如何去做。我該如何做到這一點,以便用戶可以選擇在他們贏得或失敗後重新啓動程序?不知道我在做什麼錯,Python猜數遊戲

編輯:請不要在問題中沒有別的聲明,因爲沒有相反的輸出。

回答

0

這將解決錯誤的間隔

if not guess_num > 0 or not guess_num < 26: 
    print("Sorry, try again! That is not an integer between 1 and 25! ") 
    continue 

對於剩下的,你可以做這樣的事情

創建一個方法,並堅持在你的遊戲數據

def game(): 
    ... 
    return True if the user wants to play again (you have to ask him) 
    return False otherwise 

play = True 
while play: 
    play = game() 
+0

謝謝哈哈,我甚至沒有意識到我忘記了那個 – Nightingale

1

使用函數將所有內容放入函數中,如果用戶想再次嘗試,則再次調用該函數! 這將重新開始整個過程​​!如果用戶想重新啓動,也可以完成此操作。 再次調用該方法是一個很好的計劃。在方法/函數中放入完整的東西。