我的下一個任務是修改當前代碼。在之前的練習中,我寫了一個涵蓋數字猜測遊戲的基本應用程序。代碼如下: -Modfying當前代碼
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
我的任務是改變這一點,以便有一個數量有限的失敗消息是考慮到用戶之前的那張。到目前爲止,該章已經涵蓋了「if,elif,else,for,loops,避免無限循環」。因此,我只想限制我對這些概念的迴應。 For循環將在下一章介紹。
我試過了什麼?
到目前爲止,我已經嘗試在另一個while循環中修改該塊,使用5 go和try變量,但似乎不起作用。
# guessing loop
while tries < 6:
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
tries += 1
input("You didn't do it in time!")
input("\n\nPress the enter key to exit.")
任何指針或突出顯示我已經錯過了什麼,將不勝感激加爲我已經錯過了任何解釋。教我自己去編程思考也是非常棘手的。
什麼不起作用 當我運行它時,循環條件似乎不起作用。我空閒的反饋如下。
這意味着我的問題可以概括爲 我的循環邏輯在哪裏壞了?
>>> ================================ RESTART ================================
>>>
Welcome to 'Guess My Number'!
I'm thinking of a number between 1 and 100.
Try to guess it in as few attempts as possible.
Take a guess: 2
Take a guess: 5
Higher...
You didn't do it in time!
Press the enter key to exit.
您需要定義「似乎不起作用」*表示*。它會給出錯誤嗎?你的輸出是否與你的期望不符?請*包括*那些期望和你得到的輸出是什麼。 – 2013-03-01 16:08:05
不是真正的問題(有什麼問題?)/離題(代碼評論在codereviews.stackexchange.com上) – rds 2013-03-01 16:09:44
順便說一句,你可以通過使用'for'循環代替'while '循環,並擺脫'try'變量。只要將範圍(6):'中的'嘗試<6:'行更改爲''即可。 – 2013-03-01 16:11:06