Skip to main content
 首页 » 编程设计

python之如何在语句为假时重复代码 [Python]

2025年05月04日12dflying

我真的很想了解如何在 Python 中的语句为 false 时重复我的代码。我只是想知道,如果错误,我该如何让 Python 再次询问用户名和密码?这是我的代码:

print("Enter username") 
username = input() 
print("Enter password") 
pword = input() 
if username=="Shadow" and pword=="ItzShadow": 
   print("Access granted to Shadow!") 
else: 
   print("Wrong username and / or password") 

我的意思是,如果其中一个是假的,我如何让 Python 再次询问用户名和密码?

请您参考如下方法:

您需要将您的代码包含在一个循环中。像这样:

def get_user_pass(): 
   print("Enter username") 
   username = input() 
   print("Enter password") 
   pword = input() 
   return username, pword 
 
username, pword = get_user_pass() 
while not(username=="Shadow" and pword=="ItzShadow"): 
   print("Wrong username and / or password") 
   username, pword = get_user_pass() 
 
print("Access granted to Shadow!")