提问人:LucidKoder 提问时间:9/9/2023 最后编辑:MarkLucidKoder 更新时间:9/9/2023 访问量:94
如何在 Python 中的 while 循环中添加 while 循环?
How to add a while loop within a while loop in Python?
问:
我一直在研究一个非常简单的 Python 代码,它基本上是旧的石头剪刀布游戏。
目前,当用户输入选项之外的任何内容(石头、纸、剪刀)时,提示将继续要求用户在 while 循环中输入,直到他们选择其中一个选项。(石头、纸或剪刀)。
现在,当我要求他们提供另一个输入时,我想实现同样的想法,当我问(你想再玩一次吗?是/否)。
如果答案是 Y,我希望代码继续。 我希望当答案为 N 时打印代码(感谢您的播放)。 但是我希望在 while 循环中连续询问输入,如果答案不是 Y 或 N(例如拼写错误)。
例:
用户输入 = Y 代码 = 继续询问第一个输入(您的选择是什么?(石头、纸、剪刀?
用户输入 = N 代码 = 打印 (感谢您的播放!) 并且循环被转义
用户输入 = H(Y 或 N 以外的任何值) code = prints(请输入有效的响应)并再次询问提示(是否要再次播放?是/否?:
这是到目前为止的代码(来自 YouTube 上的 Bro Code)
options = ("rock", "paper", "scissors")
running = True
while running:
player = None
computer = random.choice(options)
while player not in options:
player = input("Enter a choice (rock, paper, scissors): ")
print(f"Player: {player}")
print(f"Computer: {computer}")
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
print("You win!")
elif player == "paper" and computer == "rock":
print("You win!")
elif player == "scissors" and computer == "paper":
print("You win!")
else:
print("You lose!")
if not input("Play again? (y/n): ").lower() == "y":
running = False
print("Thanks for playing!")
我尝试创建一个 True False 变量并创建另一个 while 循环,但由于我是初学者,我遇到了大量的缩进错误,代码不起作用。
答:
嵌套循环不是一个很好的做法,因为随着代码变大,循环变得越来越难以调试。不过,在这样的小程序中,这并不重要。while
您可以复制并粘贴下面的代码,它应该可以工作。我所做的只是添加另一个循环,其结构与检查您是否输入“石头、纸、剪刀”的循环完全相同。while
关于缩进:大多数代码编辑器都允许您选择许多行代码。如果随后按 Tab 键,则应以相同的量缩进所有行。希望这对您有所帮助!
-测验器515SY
import random
options = ["rock", "paper", "scissors"]
computer = random.choice(options)
running = True
while running:
player = None
while player not in options:
player = input("Enter a choice (rock, paper, scissors): ")
print(f"Player: {player}")
print(f"Computer: {computer}")
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
print("You win!")
elif player == "paper" and computer == "rock":
print("You win!")
elif player == "scissors" and computer == "paper":
print("You win!")
else:
print("You lose!")
i = None
while i not in ["y", "n"]:
i = input("Play again? (y/n): ").lower()
if not i == "y":
print("Thanks for playing!")
running = False
评论
你可以嵌套循环,但任何超过两个深度的东西都会让我感到困惑。在那之后,编写一个输入函数。while
import random
mapping = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'}
options = list(mapping.keys())
while True:
player = None
computer = random.choice(options)
while player not in options:
player = input("enter a choice (rock, paper, scissors): ")
print(f"player: {player}")
print(f"computer: {computer}")
if computer == player: print("it's a tie!")
elif computer == mapping[player]: print("computer win!")
else: print("you win!")
# walrus operator sets variable then tests condition, Python 3.8+ only
while not (retry := input("Play again? (y/n): ").lower()) in ('y', 'n'):
continue # ask again until we get y/n
if retry == 'n':
print("thanks for playing!")
break
下面是将输入验证移动到函数中的示例:
import random
options = ("rock", "paper", "scissors")
def get_input( prompt, valid ):
while True:
value = input(prompt).lower()
if value in valid:
return value
print("Invalid reponse. Choose from", valid)
while True:
computer = random.choice(options)
player = get_input("Enter a choice (rock, paper, scissors): ", options)
print(f"Player: {player}")
print(f"Computer: {computer}")
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
print("You win!")
elif player == "paper" and computer == "rock":
print("You win!")
elif player == "scissors" and computer == "paper":
print("You win!")
else:
print("You lose!")
if get_input("Play again? (y/n): ", ('y','n')) != 'y':
break
print("Thanks for playing!")
现在,该函数可以在其他模块中重用。您甚至可以通过将 yes/no 设置为默认值来简化它:
def get_input( prompt, valid='yn' ):
while True:
...
if get_input("Play again? (y/n): ") != 'y':
评论