2014-10-30 61 views
0

試圖在python中做一個簡單的猜謎遊戲程序,但我在java中更舒服。 當輸入正確的數字時,表示它太高,不會退出while循環。 有什麼建議嗎?基本python編碼

import random 
comp_num = random.randint(1,101) 
print comp_num 
players_guess = raw_input("Guess a number between 1 and 100: ") 
while players_guess != comp_num: 
    if players_guess > comp_num: 
     print "Your guess is too high!" 
    elif players_guess < comp_num: 
     print "Your guess is too low!" 
    players_guess = raw_input("Guess another number between 1 and 100: ") 
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!" 
+0

使用'elif'第二'if'。 .. – 2014-10-30 00:14:54

+0

仍然只是輸出太高... – 2014-10-30 00:18:32

+4

這不是一個好主意,不斷更新您的問題以反映答案(即使答案是a重新正確)。它使答案看起來不相關,並消除了從錯誤中學習其他方面的機會。 – 2014-10-30 00:25:52

回答

7

我想這是因爲你比較stringint。無論是從raw_input捕獲捕獲爲string,並在Python:

print "1" > 100 # Will print true 

對於它的工作,轉換:

players_guess = raw_input("Guess a number between 1 and 100: ") 

players_guess = int(raw_input("Guess a number between 1 and 100: ")) 
+0

謝謝,夥計們!但它仍然不會退出while循環,一旦我輸入正確的數字.. – 2014-10-30 00:23:40

+0

它確實退出了我...... – maksimov 2014-10-30 00:25:13

+1

或者你忘了將第二個'raw_input'投射到'int' ......就像你的更新問題表明。你不應該用答案更新你的問題,因爲你只是混淆了事情。 – maksimov 2014-10-30 00:27:08

5

你是一個比較字符串一個int。這就是爲什麼你會得到奇怪的結果。

試試這個:

players_guess = int(raw_input("Guess a number between 1 and 100: ")) 
0
import random 
comp_num = random.randint(1,101) 
print comp_num 
players_guess = int(raw_input("Guess a number between 1 and 100: ")) 
while players_guess != comp_num: 
    if players_guess > comp_num: 
     print "Your guess is too high!" 
    elif players_guess < comp_num: 
     print "Your guess is too low!" 
    players_guess = int(raw_input("Guess another number between 1 and 100: ")) 
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!" 

需要強制輸入到int

+0

爲什麼對工作計劃投票? – Hackaholic 2014-10-30 00:28:43

+0

你錯過了第二次raw_input調用的int。 – 2014-10-30 00:30:17

+0

是的,這是一個打字錯誤,下來投票不是一個soln – Hackaholic 2014-10-30 00:32:28

0

試試這個代碼:

import random 
comp_num = random.randint(1,101) 
print comp_num 
players_guess = int(raw_input("Guess a number between 1 and 100: ")) 
while players_guess != comp_num: 
    if players_guess > comp_num: 
     print "Your guess is too high!" 
    elif players_guess < comp_num: 
     print "Your guess is too low!" 
    players_guess = int(raw_input("Guess another number between 1 and 100: ")) 
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!" 
+0

您可以通過添加簡短的解釋來改善您的答案。 – dakab 2015-08-30 15:35:16