在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
这是否与嵌套循环有关?
答案 0 :(得分:5)
您的代码要点:
':'
和if,elif
else.
continue and break
之类的控制流语句来实现。 Please check here for more detail。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