In this tutorial, you will learn How to create a Password protected python file with only 8 lines of code! This program will ask user for username and password. And if those credentials are incorrect, it will exit the program. There are 4 steps in this article.
{tocify}
Step 1: Store default username and password
We are going to store username and password in a variable. Here I'm using mrperfect
as username and perfectbro
as password.
username = 'mrperfect'
password = 'perfectbro'{codeBox}
Step 2: Ask user for username and password
To ask or get input from user, we use input()
function. This is a built-in python function. And we also have to store it in a variable.
inputuser = input('[*] Enter username: ')
inputpass = input('[*] Enter password: '){codeBox}
Step 3: Match those credentials
We can use IF-ELSE statement to match those and do action if not matched. Since we want to exit the script if not matched, so we will use only IF statement. and since there is 2 conditions and 1 Logical operator, we will put conditions in a bracket.
if not (username==inputuser and password==inputpass):here
print('Incorrect username or password!\nPlease try again.')
exit(){codeBox}
exit()
is a python built-in function. This function exit's the program.Step 4: Put your main code after that
Since this is a tutorial so my main function is printing a text.
print('This is main function'){codeBox}
Full Code
username = 'mrperfect'
password = 'perfectbro'
inputuser = input('[*] Enter username: ')
inputpass = input('[*] Enter password: ')
if not (username==inputuser and password==inputpass):
print('Incorrect username or password!\nPlease try again.')
exit()
print('This is main function'){codeBox}