我如何让我的代码继续循环?

  • 本文关键字:继续 循环 代码 python
  • 更新时间 :
  • 英文 :


我试图使代码重复行"播放器名称无效"并重复请求输入,直到输入为"玩家1"。我该怎么做?

correct_n="player 1"
while True:
Name1 = input ("Enter Your Name: ")
if Name1 == correct_n:
cp = 'password'
while True:
password= input("enter the password ")
if password == cp:
print ("yes you are in")
break
print("please try again")
else:
print("Player name not valid")
break
print("player name invalid")

代码只是打印&;player name invalidate &;然后继续执行剩下的代码。我不希望在用户输入正确的名称和密码之前输出其余的代码。

因为您有两个while循环,所以不可能使用break来退出它们。相反,您应该将循环分开,以便名称循环运行直到名称正确,然后密码循环运行直到密码匹配。

correct_n="player 1"
while True:
Name1 = input("Enter Your Name: ")
if Name1 == correct_n:
break
else:
print("Player name not valid")
cp = 'password'
while True:
password= input("enter the password ")
if password == cp:
print ("yes you are in")
break
else:
print("please try again")

解决方案:

while input('Enter your name: ') != 'player 1': print('Player name invalid')

最新更新