2014-10-26 60 views
-1

這款遊戲讓用戶猜測一個4位數的數字,並在用戶猜測顯示'Y'後給出反饋,如果用戶獲得正確的數字,並顯示'H',如果猜測最多比數字高3倍,顯然與在數字以下至多3位顯示「L」相反。但這是我的問題,我不能讓它顯示'H'和'L'在3以上或以下!任何幫助表示讚賞..代碼是低於我已經嘗試過的地方。小於或超過一定數量

from random import randint 
guessesTaken = 0 
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums 
while guessesTaken < 10: 
    guesses = list(input("Guess Number: ")) # create list of four digits 
    check = "".join(["Y" if a==b else "H" if int(a)< 3 int(b) else "L" for a, b in zip(guesses,randomNumber)]) 
    if check == guesses: # if check has four Y's we have a correct guess 
     print("Congratulations, you are correct, it took you", guessesTaken, "guesses.") 
     break 
    else: 
     guessesTaken += 1 # else increment guess count and ask again 
     print(check) 
    if guessesTaken == 10: 
     print("You lose") 
+0

而不是在一行中做'check',爲什麼不嘗試寫出多行代碼,'a,b in zip(...):'等等。然後我想你會發現更多的錯誤容易。 – darthbith 2014-10-26 16:13:29

+0

我做到了,但我是新來的蟒蛇,並沒有看到我出錯的地方。我不能讓它做到3或以下 – paxyshack 2014-10-26 16:23:16

回答

0

修復了這一點,請參閱評論。

from random import randint 
guessesTaken = 1 # repaired that. you cannot guess correctly on "0 guesses". 
randomNumber = [str(randint(1, 9)) for _ in range(4)] 
while guessesTaken < 10: 
     guesses = list(input("Guess Number: ")) 
     #repaired check cases 
     check = "".join(["Y" if a == b else "L" if int(a) < int(b) and int(a)+3 >= int(b) else "H" if int(a) > int(b) and int(a)-3 <= int(b) else '?' for a, b in zip(guesses,randomNumber)]) 
     if check == "YYYY": # repaired this check 
      print("Congratulations, you are correct, it took you", guessesTaken, "guesses.") 
      break 
     else: 
      guessesTaken += 1 
      print(check) 
else: # loop is exhausted 
    print("You lose") 


Guess Number: 4444 
?HLH 
Guess Number: 2262 
?LYL 
Guess Number: 7363 
LYYY 
Guess Number: 8363 
LYYY 
Guess Number: 9363 
Congratulations, you are correct, it took you 5 guesses. 

雖然它的工作,這樣一個長長的列表理解是一個PITA來編寫和維護。 更好地保持你的語句簡短並重構常見的東西。

相關問題