Today we're going to write a simple login program in Python. This lab will step you through the process and tell you what lines you need to add to the VS Code IDE. You are free to either transcribe the code or copy-and-paste it. If you copy-and-paste it be sure to remove the line numbers after you paste it because they aren't part of the program and VS Code will number the lines for you.
Open VS Code.
In the Explorer panel (Ctrl + Shift + E) find the "Lab 2" folder. Inside the folder is a file named Login.py. Select that file to open it in the Editor panel.
Review the Login.py file in the Editor panel (Ctrl + 1). There's not much here. It's just two comment lines that say this is going to be a login program and you're going to fill it in.
Let's get started filling in this program. The number and | before each line tells you what line number the code goes in your program. Add the following lines to your program:
4 | # Password "database".
5 | password_db = {"Bill" : "Clawhammer",
6 | "Jesse" : "Mitsu",
7 | "Steven" : "Muddy",
8 | "Ashley" : "Shadow"}
Explanation: Lines 4 through 8 add a password dictionary to our program. Line 4 is a comment to help us remember what this is in the future. Line 5 introduces variable called password_db. This variable stores a data structure that Python calls a dictionary. A dictionary is a look up table with key and value pairs that is structured like this:
{ key : value,
key : value,
key : value }
This dictionary is going to function as a password database for our program. The usernames are the keys and the values are the user's passwords. In a more sophisticated program this information would be stored in an actual database or a protected file. We're just going to use a dictionary to simplify things today.
When you're coping the password dictionary to your program be sure to pay close attention to all of the special characters like { " : " , } and where they are used. They are important so that Python can understanding your program.
Now we're going to start gathering information from the user. Add the following lines to your program:
9 |
10 | # Collect login information.
11 | print("\n\n=========Login Page===========")
12 | username = input("Username: ")
13 | password = input("Password: ")
Explanation: Lines 9 through 13 collect the username and password from the user - which is important information for a login program. Line 9 is an empty line. Line 10 is a comment to remind us what the next few lines do.
Line 11 is a print command (like we used yesterday). The \n\n characters create two new lines so there will always be two blank lines above the login in the terminal when we run the program.
Line 12 introduces a variable called username and uses the input command to store a name the user enters in it.
Line 13 introduces a variable called password and uses the input command to store a password the user enters in it.
Now let's run our program to make sure it works. It's good practice to run your program often so you can catch mistakes as you go and correct them. If you wait until the end it can be difficult to debug the entire program at once. It's much easier to code a little and then test a little to make sure everything is working.
Press the "Run Python File" button in the upper-right corner of the IDE or use the Ctrl + F5 shortcut to run the program then check the Terminal panel (Ctrl + `) to make sure we see the expected output.
In the terminal panel you should see the following output:
=========Login Page===========
Username:
If you don't you might see an error message instead. Try and figure out what's wrong with your program. If can't figure it out then ask for help debugging it.
If you do see the Username: prompt in your terminal window enter a user name and press the Enter key. (If you're using a mouse you might have to click the terminal panel first.)
After you press Enter you should see a Password: prompt appear. Go ahead and enter something for a password and press the Enter key. Right now it doesn't really matter what you enter because our program doesn't do anything with the input yet.
If you were able to enter both a username and a password that is a success! So far, so good. Next we'll do something with the input.
Now that we're collecting a user name and password from the user we need to compare it the password dictionary to see if the password is correct. Add the following lines to your program:
14 |
15 | # Get correct password from database that matches username.
16 | correct_password = password_db.get(username)
17 |
18 | if correct_password == None:
19 | # If correct_password is None that means user was not found.
20 | print("User Not Found!")
21 | elif correct_password != password:
22 | # If passwords do not match then password is wrong.
23 | print("Invalid Password")
24 | else:
25 | print("Congratulations, you are logged in.")
Explanation: This code compares the password the user entered to the ones saved in the password dictionary. We'll step through it line-by-line. Line 14 is a blank line and line 15 is a comment (those two are easy).
Line 16 tries to look up the user's password in our password dictionary. The line starts by introducing a new variable called correct_password that we'll store the correct password in. We get the correct password by looking it up in our password_db dictionary. To look it up we take the username variable, which is currently storing the name the user entered, and passing that to the password_db dictionary's get function. If the dictionary has an entry for that user it will store the correct password in the correct_password variable. If it doesn't have an entry it will store nothing in the variable.
The next few lines are a decision structure sometimes called an "if block". This is a common structure programs use to make decisions by evaluating the contents of their variables.
Line 18 uses a Python command called an if statement. If statements check a condition and will only run the indented lines if that condition is true. In this case, the if statement checks to see if the value of the correct_password variable is equal to None. If correct_password is equal to None that means we weren't able to find the username the user entered in our password dictionary. On lines 19 and 20 we print a message telling the user the bad news: "User Not Found!"
Line 21 uses a Python command called elif which stands for "else if". This is a special command that checks an additional conduction if the first condition is false. In this case, if there is a password stored in the correct_password variable the if statement on line 18 will be false (because it is not equal to None). Then the program will check the elif statement on line 21.
If we look at the condition on line 21 we see it says correct_password != password. The != characters means "not equal" in Python. Remember that we're storing the password that the user entered in a variable called password. So this line checks to see if the password the user entered is not equal to the one saved in our password dictionary. If it is not, then lines 22 and 23 print out a message telling the user the password they entered is an "Invalid Password".
Lastly, on line 24 we have a Python command called else. If the conditions aren't satisfied on line 18 or line 21 then line 24 will be executed. This is a catch-all to make sure something is executed in this if statement block. In this case, if the user is found in the password dictionary, and the password matches, then they have successfully logged in. So line 15 prints out a message telling the user they are logged in.
Ok, now that we've added to our program it is time to run again to make sure we haven't introduced any errors.
Press the "Run Python File" button in the upper-right corner of the IDE or use the Ctrl + F5 shortcut to run the program then check the Terminal panel (Ctrl + `) to make sure we see the expected output.
In the terminal panel you should once again see the following output:
=========Login Page===========
Username:
Go ahead and enter a username and password into the program. Depending on what you enter you should see one of the following three lines:
User Not Found!
Invalid Password
Congratulations, you are logged in.
In fact, you should run your program multiple times to make sure you can get it to produce all three outputs. This is called testing your code. If you have three expected results you want to make sure you can reach all three results. You can look at the username and password pairs in the password_db variable at the top of the program if you need a reminder of what the valid users and passwords are.
If you aren't able to produce all three of the expected outputs it time to figure out what's wrong. If you can't figure it out ask for help.
If you were able to make your program produce the expected messages for user not found, invalid password, and successful login then congratulations. You technically have a functioning login program. Although, it's a bit simple isn't it?
One of the issues is that you only get once chance to enter your username and password. If you get it wrong you have to run the program again. The last thing we're going to do today is fix that by adding a loop to our program so you get multiple tries to enter a correct username and password.
To add the loop we only need to add a few lines to our program, but since these lines will be spread throughout the program the following is a listing of the complete program. We'll identify the new lines you need to add after the listing.
1 | # GenCyber Login Program
2 | # You've got to fill in the rest.
3 |
4 | # Password "database".
5 | password_db = {"Bill" : "Clawhammer",
6 | "Jesse" : "Mitsu",
7 | "Steven" : "Muddy",
8 | "Ashley" : "Shadow"}
9 |
10 | # Keep track of if we should keep looping.
11 | loop_again = True
12 |
13 | while loop_again:
14 | # Collect login information.
15 | print("\n\n=========Login Page===========")
16 | username = input("Username: ")
17 | password = input("Password: ")
18 |
19 | # Get correct password from database that matches username.
20 | correct_password = password_db.get(username)
21 |
22 | if correct_password == None:
23 | # If correct_password is None that means user was not found.
24 | print("User Not Found!")
25 | elif correct_password != password:
26 | # If passwords do not match then password is wrong.
27 | print("Invalid Password")
28 | elif correct_password == password:
29 | # If the password match stop looping and log in user.
30 | loop_again = False
31 |
32 | print("Congratulations, you are logged in.")
Line 10 and line 11 are new. You'll need to insert them into your program at the appropriate place. Line 10 is a comment and line 11 introduces a new variable called loop_again. As long as the value of loop_again is True your program will keep looping and asking for usernames and passwords.
Line 12 and 13 are also new. You'll need to also insert them into your program at the appropriate place. Line 12 is a blank and line 13 introduces a Python command called a while loop. The statement tells the program to keep looping until a condition is not true. On line 13 you can see the condition is stored in the variable loop_again which we set to true on line 11 so the program will keep looping until something sets the loop_again variable to false.
Do you remember with if statements that the program would run the indented lines only if the condition was true? It works the same way with while loops. You'll notice that you already have lines 14 through 27 in your program, but now they have been indented to be put "in the loop". You can either intent the lines one-by-one or you can select all of the lines you want to indent in VS Code and then hit the Tab key to do a group indent. (You can also group un-indent by selecting multiple lines and using the Shift + Tab shortcut.)
Lines 28 through 32 are also new. Line 28 gets rid of the else statement on your if block and replaces it with another elif statement. The new elif checks to see if correct_password is equal to the password the user entered. If it is, then the program executes lines 29 and 30. Line 30 sets the loop_again variable to false so the loop will stop and the program can execute line 32.
Copy the new lines to your program and make sure the entire program matches the 32 lines given above.
Ok, since we've added to our program we need to run again it to make sure we haven't introduced any errors.
Press the "Run Python File" button in the upper-right corner of the IDE or use the Ctrl + F5 shortcut to run the program then check the Terminal panel (Ctrl + `) to make sure we see the expected output.
In the terminal panel you should once again see the following output:
=========Login Page===========
Username:
Enter a username and password.
If you enter a user that doesn't exist or the wrong password you should see one of the following responses.
User Not Found!
Invalid Password
And more importantly, after it shows you one of those lines, it should show you the prompt to enter a username again. You should be able to continue to try and log in until you enter a valid username and password pair.
Once you enter a correct username and password you should see the following line and the program will end.
Congratulations, you are logged in.
Once again, you should run your program multiple times to make sure you can get it to produce all the expected outputs. If you aren't able to produce all three of the expected outputs it time to figure out what's wrong. Doublecheck that your code matches the listing provided in Part 7. If you can't figure it out ask for help.
This is a simple program, but it accomplishes some important things. First off, it works and does something. Lots of programs and websites have to provide very similar login functionality to this program.
Secondly it includes some powerful programming concepts. If statements and loops are fundamental coding building blocks that are used often in programming.
Are there other things we'd want a log in program to do? That's something to think about because tomorrow we're going to continue to add to this program. What else do you think a login program should be able to do?