Liz*_*zie 2 python loops nested 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.")
Run Code Online (Sandbox Code Playgroud)
因此,这部分工作。但是,我如何退出此循环,因为在输入正确的输入后,它会一直询问“请输入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
Run Code Online (Sandbox Code Playgroud)
这与嵌套循环有关吗?
您的代码要点:
':'
在之后if,elif
和之后都没有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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5589 次 |
最近记录: |