我做了一個簡單的猜謎遊戲的練習。該程序運行時沒有錯誤,但給出的輸出是錯誤的值。錯誤的計數在輸出
下面是代碼:
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))
這裏是輸出:
,你可以在上圖中看到,儘管很顯然,3次嘗試了爲了猜測正確的數字,Python只計算了2次嘗試。有誰會請讓我知道如何解決這個問題?
複製並粘貼到控制檯輸出在這裏請。另請注意,Python是一種** 0-索引**語言,因此嘗試0,1和2共有3次嘗試 –
'範圍'從0開始。 – Matthias
在這種情況下使用while循環和break語句會更好 –