2017-01-30 32 views
-3

我做了一個簡單的猜謎遊戲的練習。該程序運行時沒有錯誤,但給出的輸出是錯誤的值。錯誤的計數在輸出

下面是代碼:

import random 

welcome_phrase = "Hi there. What's your name?" 
print("{:s}".format(welcome_phrase)) 

user_name = input("Name: ") 
print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1 and 20. Can you guess the number?".format(user_name)) 

attempts = 5 
secret_num = random.randint(1,20) 

for attempt in range (attempts): 
    guess = int(input("Guess the number: ")) 
    if guess > secret_num: 
     print("Your guess is higher than the number. Try again") 
    elif guess < secret_num: 
     print("Your guess is lower than the number. Try again.") 
    else: 
     print("Well done! {:d} is the right number.".format(guess)) 
     print("It took you {:d} attempts.".format(attempt)) 
     break 

if guess != secret_num: 
    print("Sorry, you have used up all your chances.") 
    print("The number was {:d}".format(secret_num)) 

這裏是輸出:

This is what the console prints back.

,你可以在上圖中看到,儘管很顯然,3次嘗試了爲了猜測正確的數字,Python只計算了2次嘗試。有誰會請讓我知道如何解決這個問題?

+1

複製並粘貼到控制檯輸出在這裏請。另請注意,Python是一種** 0-索引**語言,因此嘗試0,1和2共有3次嘗試 –

+3

'範圍'從0開始。 – Matthias

+0

在這種情況下使用while循環和break語句會更好 –

回答

0

您可以更改

for attempt in range (attempts): 

for attempt in range (1,attempts+1): 

來解決這個問題,因爲範圍從0

+0

感謝您的幫助。該程序現在工作正常。 –

0

while循環開始於一個break條款是許多猜測更清潔因爲它更可靠。

for循環開始,除非指定在另一點開始在0開始計數,所以即使是在代碼運行3次計數器輸出會說其僅2((0,1,2))

這是我爲創建一個數字猜測遊戲的基本版本,但其他功能(如額外的級別和提示)可以輕鬆完成,我很樂意提供幫助,如果您不瞭解下面的任何代碼,請告訴我。

例:

import random 

welcome_phrase = "Hi there. What's your name?" 
print("{:s}".format(welcome_phrase)) 

user_name = input("Name: ") 
print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1 and 20. Can you guess the number?".format(user_name)) 

totalAttempts = 5 
secret_num = random.randint(1,20) 
usedAttempts=0 

while usedAttempts!=totalAttempts: #will run until they run out of attempts 
    guess=input("What is your guess? ") 
    if guess > secret_num: 
     print("Your guess is higher than the number. Try again") 
    elif guess < secret_num: 
     print("Your guess is lower than the number. Try again.") 
    elif guess==secret_num: #checks if they are right 
     print("Well done, You have guessed my number!") 
     print("It took you {:s} attempts".format(usedAttempts)) 
     wonGame=True 
     break #exits while loop 
    else: 
     print("Sorry that is not my number, you have lost a life. :(") 
     usedAttempts+=1 #adds 1 to the value of the used attempts 


if wonGame==True: 
    print("Sorry, you have used up all your chances.") 
    print("The number was {:d}".format(secret_num)) 
+0

感謝您的幫助。不幸的是,上面的代碼將不起作用,因爲第14行有一個錯誤:'guess = input(「你猜怎麼着?」)' 相反,它應該是:'guess = int(input(「你猜的是什麼? 「) –

+0

同樣,第21行也會產生錯誤,因爲usedAttempts有一個整數值,而不是字符串,因此第21行應該是:'print(」它花了你{:d}次嘗試「.format(usedAttempts)) ' –

+0

如果你做int(輸入(「你猜的是什麼?」))它會崩潰,所以你必須稍後將它轉換爲數字 – WhatsThePoint