提问人:MoRayhxn 提问时间:11/10/2022 更新时间:11/10/2022 访问量:40
Python 而 True 定位混乱
Python while True positioning confusion
问:
我刚刚开始制作一个石头剪刀布程序,但我发现我尝试放置一段时间的 2 个位置 True: 命令具有完全相反的效果。我无法理解它背后的逻辑/推理,希望有人能够用简单的术语解释它。
代码的第一个副本是与第 3 行的 while True: 一起正常工作的代码副本。
代码的第二个版本是我首先用 while True 完成的:在第 6 行。
第二个版本导致游戏被无休止地打印,例如“你赢了”一百万次,而当 while True: 在第 3 行时,它按预期运行,赢/输或平局消息只打印一次。
有人可以解释为什么这样我理解以供将来参考。
import random
moves = "rock", "paper", "scissors"
while True:
computer = moves[random.randint(0,2)]
player = input("Choose rock, paper or scissors... Or 'end' to end the game: ")
if player == "end":
print("Game over!")
break
elif player == "rock" and computer == "scissors" or player == "scissors" and computer == "paper" or player == "paper" and computer == "rock":
print("You win", player, "beats", computer)
elif player == computer:
print("Tie!")
else:
print("You lose!", computer, "beats", player)
import random
moves = "rock", "paper", "scissors"
computer = moves[random.randint(0,2)]
player = input("Choose rock, paper or scissors... Or 'end' to end the game: ")
while True:
if player == "end":
print("Game over!")
break
elif player == "rock" and computer == "scissors" or player == "scissors" and computer == "paper" or player == "paper" and computer == "rock":
print("You win", player, "beats", computer)
elif player == computer:
print("Tie!")
else:
print("You lose!", computer, "beats", player)
答: 暂无答案
上一个:修改 Pandas 数据帧
下一个:Python 的布尔函数优化器包
评论
input
computer = moves[random.randint(0,2)]
moves
moves
computer = random.choice(moves)
randint