2015-09-02 91 views
0

我有一個問題,我簡單的猜測在python中的數字遊戲。代碼如下給出。該程序從來沒有給我一個正確的猜測,它不斷詢問數字。問題與簡單猜數字遊戲中的蟒蛇

import random 
import time 

time1 = time.time() 

number = random.randint(1,1000) 

print ("welcome to the guessing game") 
name = input("what is your name? ") 
print("well, " + name + " iam thinking of the number between 1 and 1000") 

while True: 
guess = int(input("guess: ")) 
if guess > number: 
    print("too high!") 
    if guess < number: 
     print("too low!") 
     if guess == number: 
      break 
     print("yahoo,you guessed the number!") 
     input() 
     time2 = time.time() 

是在Python 3

+4

問題在於縮進。 Python使用縮進來分隔代碼塊 –

+0

以代碼塊「if guess == number:」開頭並取消縮進。現在,當猜測值太低時,程序只能到達那條線,這意味着當猜測不能等於數字時,它只能到達那裏。取消縮進,它應該可以正常工作。 – WDS

回答

0
import random 
import time 

time1 = time.time() 
number = random.randint(1,1000) 

print ("welcome to the guessing game") 
name = input("what is your name? ") 
print("well, " + name + " i am thinking of the number between 1 and 1000") 

while True: 
    guess = int(input("guess: ")) 
    if guess > number: 
     print("too high!") 
    if guess < number: 
     print("too low!") 
    if guess == number: 
     print("yahoo,you guessed the number!") 
     time2 = time.time() 
     break 

猜謎遊戲數量不改變太多,這裏是一個工作的代碼。

1

您需要正確縮進代碼,您還應該使用if/elif's,因爲猜測在任何時候都只能是較高,較低或相等的一種。您還需要打印您在成功的猜測打破前:

while True: 
    guess = int(input("guess: ")) 
    if guess > number: 
     print("too high!") 
    elif guess < number: 
     print("too low!") 
    elif guess == number: 
     print("yahoo,you guessed the number!") 
     time2 = time.time() 
     break 

沒有辦法,你的循環可以打破作爲你如果的嵌套外if guess > number:內,如果猜>號碼,然後if guess < number:評估,但對於明顯的原因不可能是真的,所以你無限循環。