簡體   English   中英

我如何詢問用戶是否想再次播放並重復 while 循環?

[英]How do I ask the user if they want to play again and repeat the while loop?

在 Python 上運行,這是我的代碼示例:

import random 

comp = random.choice([1,2,3])

while True:
     user = input("Please enter 1, 2, or 3: ")
     if user == comp
             print("Tie game!")
     elif (user == "1") and (comp == "2")
             print("You lose!")
             break
     else:
             print("Your choice is not valid.")

所以這部分有效。 但是,我如何退出這個循環,因為在輸入正確的輸入后,它不斷詢問“請輸入 1,2,3”。

我也想問一下玩家想不想再玩:

偽代碼:

     play_again = input("If you'd like to play again, please type 'yes'")
     if play_again == "yes"
         start loop again
     else:
         exit program

這是否與嵌套循環有關?

您的代碼要點:

  1. 您粘貼的代碼在if,elifelse.之后沒有':' else.
  2. 無論您想要什么,都可以使用諸如continue and break類的控制流語句來實現。 請在此處查看更多詳細信息
  3. 您需要從“YOU LOSE”中刪除 break,因為您想詢問用戶他是否想玩。
  4. 由於您將字符串與整數進行比較,因此您編寫的代碼永遠不會遇到“平局游戲”。 保存在變量中的用戶輸入將是字符串,而隨機輸出的comp將是整數。 您已將用戶輸入轉換為整數作為int(user)
  5. 檢查用戶輸入是否有效可以簡單地使用in操作符進行檢查。

代碼:

import random

while True:
     comp = random.choice([1,2,3])
     user = raw_input("Please enter 1, 2, or 3: ")
     if int(user) in [1,2,3]:
         if int(user) == comp:
            print("Tie game!")
         else:
            print("You lose!")
     else:
            print("Your choice is not valid.")

     play_again = raw_input("If you'd like to play again, please type 'yes'")
     if play_again == "yes":
        continue
     else:
         break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM