2014-12-23 102 views
0

如何讓循環工作,以便它會在你正確的時候結束並且如果你弄錯了再問這個問題? 當我猜錯兩次或更多次時,無論發生什麼事,總會說錯。雖然循環不打印正確的猜字遊戲

import random; 
import sys; 
x = random.randint(1, 100); 
print(x); 
guess = int(input("Guess a number 1 to 100")); 
if guess == x: 
     print("correct"); 
     sys.exit() 
while guess != x: 
    print("wrong"); 
    int(input("Guess a number 1 to 100")); 
    print(x); 
    if guess == x: 
     print("Correct"); 
     sys.exit() 

另外什麼函數記錄它循環的次數。例如,如果我猜錯了10次,然後我要打印,我打進了10

+0

我真的建議在行尾加分號 - 這是不必要的,更糟糕​​的是,一旦你習慣於閱讀Python代碼,這會讓人感到困惑(你開始期待它是一個冒號,你經常看到它在一行的末尾) – zehnpaard

回答

2

你忘了周圍的分配,第二次在該guess變量

while guess != x: 
    print("wrong"); 
    guess = int(input("Guess a number 1 to 100")); #look here 
    print(x); 
    if guess == x: 
     print("Correct"); 
     sys.exit() 
2

失蹤「的猜測=」循環中的輸入行。要記錄次數,只需在循環中增加一個變量即可。

[附錄]

import random; 
import sys; 
x = random.randint(1, 100); 
print(x); 
count = 1 
guess = int(input("Guess a number 1 to 100: ")); 
while guess != x: 
    count += 1 
    guess = int(input("Wrong\nGuess a number 1 to 100: ")); 
print("Correct - score = "+str(100./count)+"%"); 
sys.exit(0) 
+0

你可以更具體的增量變量部分? – user3370908

+0

進口隨機; import sys; x = random.randint(1,100); print(x); count = 1 guess = int(input(「猜數字1至100:」)); while guess!= x: count + = 1 guess = int(input(「Wrong \ nGuess a number 1 to 100:」)); print(「Correct - score =」+ str(100./count)+「%」); sys.exit(0) – dwn

0

其實你應該改變你的代碼:

import random 
x=random.randint(1,100) 
score=0 
while True: 
    guess=int(input("Guess a number 1 to 100: ")) 
    if guess==x: 
     print ("Correct!") 
     break 
    else: 
     print ("Not correct!") 
     score+=1 
print ("your answers was wrong {} times.".format(score)) 

更好的語句,少的代碼。乾杯!

+0

也是什麼函數記錄它循環的次數。例如,如果我猜錯了10次,那麼我想打印出我得分爲10. – user3370908

+0

定義一個等於零的變量並在錯誤答案後升級此變量的值,然後在_while_循環之外打印該變量 – GLHF

+0

如果此答案已解決你的問題,請檢查它作爲答案。 – GLHF