[英]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
這是否與嵌套循環有關?
您的代碼要點:
if,elif
和else.
之后沒有':'
else.
continue and break
類的控制流語句來實現。 請在此處查看更多詳細信息。comp
將是整數。 您已將用戶輸入轉換為整數作為int(user)
。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.