如何在语句为false时重复代码[Python]

时间:2018-05-31 16:05:45

标签: python

我真的想学习如何在Python中声明错误时重复我的代码。我只是想知道,如果错误的话,如何让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再次询问用户名和密码?

3 个答案:

答案 0 :(得分:4)

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

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!")

答案 1 :(得分:2)

使用while循环:

while True:
    print("Enter username")
    username = input()
    print("Enter password")
    pword = input()
    if username=="Shadow" and pword=="ItzShadow":
        print("Access granted to Shadow!")
        break # Exit the loop
    else:
        print("Wrong username and / or password") # Will repeat

stuff() # Only executed when authenticated

答案 2 :(得分:0)

每次用户和密码不相同时,我们在循环中使用输入函数get_input的数据。

def get_input():
# enter your declarations here
return [user_name,password]

user,pwd=get_input()
while (user!='your desired user' and pwd!='the password'):
    print('Not authorized')
    user,pwd=get_input()
print('Your success message')