【发布时间】:2019-12-26 01:47:44
【问题描述】:
import random
def rock_paper_scissors(choice):
computer_choice = random.choice(['rock', 'paper', 'scissors'])
while True:
if choice == computer_choice:
print("Tie! Play again.")
choice
elif choice.lower() == 'quit':
break
elif choice.lower() == 'rock' and computer_choice.lower() == 'paper':
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
choice
elif choice.lower() == 'rock' and computer_choice.lower() == 'scissors':
print("YOU WON!", choice.lower(), "beats", computer_choice.lower())
choice
elif choice.lower() == 'paper' and computer_choice.lower() == 'scissors':
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
choice
elif choice.lower() == 'paper' and computer_choice.lower() == 'rock':
print("YOU WON!", choice.lower(), "beats", computer_choice.lower())
choice
elif choice.lower() == 'scissors' and computer_choice.lower() == "rock":
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
choice
elif choice.lower() == 'scissors' and computer_choice.lower() == "paper":
print("YOU WON!", choice.lower(), 'beats', computer_choice.lower())
choice
else:
print("Sorry, invalid.")
choice
print(rock_paper_scissors(input("Rock paper or scissors (enter 'q' to quit): ")))
运行此代码时,elif 中打印的任何内容都会在运行框中一遍又一遍地重复。我不知道是否应该修复 while 语句或在 elif 语句中添加其他代码。输入工作正常,但我不知道在 while 循环中添加什么。 (我是一个初学 Python 程序员)
【问题讨论】:
-
while True:根据定义会一遍又一遍地重复,除非你有办法跳出循环。我想你只是想删除while声明。 -
您必须请求用户输入,而不是输入
choice语句(没有效果)。提示:在所有ifs 检查后,您只能请求用户输入一次 -
@dcg 你为什么写在评论里?这正是答案......即使是stackoverflow也不愿意在评论中给出答案,并且仅将其用于添加信息。
标签: python while-loop infinite