首页 > 解决方案 > 如何在 Python 中创建一个密码来结束被拒绝的代码的以下部分?

问题描述

我有我的密码和所有密码,但如果您没有正确的密码,我希望有以下部分代码,您无法访问。我怎么做?

attempts=0
while attempts<3:
username=input('Username?')
password=input('Password?')
birhdate=input("Birthdate?")
pin=input("Enter your four digit pin.")
if username=='l.urban'and password=='lucasur2'and birhdate=='857585'and 
pin=='1973':
    print('you are in!')
else:
    attempts+=1
    print('incorrect!')
    if attempts==3:
        print('too many attempts')
          end code

 else:
    attempts+=1
    print('incorrect!')
    if attempts==3:
        print('too many attempts')
          end code

Python 3.6.1(默认,2015 年 12 月,13:05:11)Linux 上的 [GCC 4.8.2] 文件“main.py”,第 14 行`在此处输入代码结束代码 ^``IndentationError:意外缩进 </p >

标签: python

解决方案


确保正确缩进你的代码,否则 Python 将无法解析它,你会得到IndentationError.

修复缩进后,您的代码应该可以工作,但如果您想学习,这里有一个简化版本:

def check_user(username: str, password: str) -> bool:
    return username == 'admin' and password == 'password'


def main():
    tries = 1
    while True:
        if tries > 3:
            print('Too many attempts')
            return

        username = input('username?')
        password = input('password?')

        if check_user(username, password):
            break
        else:
            print('Invalid credentials')
            tries += 1
            continue
    print("You're in")
    # do some work


if __name__ == '__main__':
    main()


推荐阅读