2012-12-17 106 views
1

我剛剛開始學習編程以下http://learnpythonthehardway.org。 瞭解循環和if語句後,我想嘗試做一個簡單的猜謎遊戲。python中的猜測遊戲

的問題是:

如果做出不正確的猜出它卡住,只是不斷重複,無論是「過高」或「太低」,直到你擊中CRTL C.

我看了一下,而循環和閱讀其他人的代碼,但我只是不想複製代碼。

print ''' This is the guessing game! 
A random number will be selected from 1 to 10. 
It is your objective to guess the number!''' 

import random 

random_number = random.randrange(1, 10) 
guess = input("What could it be? > ") 
correct = False 

while not correct: 
    if guess == random_number: 
     print "CONGRATS YOU GOT IT" 
     correct = True 
    elif guess > random_number: 
     print "TOO HIGH" 
    elif guess < random_number: 
     print "TOO LOW" 
    else: 
     print "Try something else" 
+0

是LPTHW真教人使用'輸入()'在Python 2的伎倆? – geoffspear

+0

您需要在'while not correct:'循環中再次提示用戶; Eumiro的方法是最好的:)。另外,我認爲'random.randrange(1,10)'會得到一個從1到9的隨機範圍,因爲最後一個數字可能是唯一的。我不確定是否是這樣;在正常的對象類型中,範圍(1,10)僅爲1到9;它排除了第二個參數。 –

+0

@ F3AR3DLEGEND是正確的:random.randrange(start,stop [,step])在start <= number furins

回答

8

您必須再次詢問用戶。

末加入這一行(由四個空格縮進,以保持它的while塊內):

guess = input("What could it be? > ") 

這僅僅是一個快速的黑客。否則我會遵循@furins提出的改進。

3

移動while循環中請求確實:)

print ''' This is the guessing game! 
A random number will be selected from 1 to 10. 
It is your objective to guess the number!''' 

import random 

random_number = random.randrange(1, 10) 
correct = False 

while not correct: 
    guess = input("What could it be? > ") # ask as long as answer is not correct 
    if guess == random_number: 
     print "CONGRATS YOU GOT IT" 
     correct = True 
    elif guess > random_number: 
     print "TO HIGH" 
    elif guess < random_number: 
     print "TO LOW" 
    else: 
     print "Try something else" 
+0

ops,它幾乎與@eumiro的答案是一樣的......但是,在while循環的開始處提出這個問題可以讓你不重複自己。對不起,重複 – furins

+0

,這是一個更好的答案。 – eumiro