Creating a Login System for the OCR NEA
Introduction
To create a login system we are going to have to break the problem down into the following categories:
- Sign In
- Sign Up
- Content you want to access
Sign In
We want the user to be able to sign in if they already have an account
Sign Up
We want users to be able to create a new account
Content you want to access
You want some content that the user can sign in or sign up so that they can access. When you login to facebook it displays your own profile. For this example we can just make it login and say "Welcome to your profile"
Click a topic on the left to begin
Setting up our Login System
For this chapter you will have to know about: Variables, Arrays, 2d Arrays
To create our login system we are first going to have to initiate a variable to store our users.
1 | arrayOfUsers = [] |
This is an array of empty users
Lets add in a new user, for this we are going to have to add an array into another array. This makes 2d array.
We are going to say that the first entry into the array is their username and the second entry their password.
This means the array will look like this for every user:
["name", "password"] |
Or using an example
["coolestguy", "abc123"] |
Lets add in a new user to our array like so:
1 | arrayOfUsers = [["Fred", "password1"]] |
Now we have 1 user in our program who can sign in.
Lets print out our array using the print function
1 | arrayOfUsers = [["Fred", "password1"]] |
2 | print(arrayOfUsers) |
Add in two more users to your array, remember to use a comma to separate each array
Show Answer1 | arrayOfUsers = [["Fred", "password1"],["Selena", "starWars"],["Ellie", "RedMAn"]] |
2 | print(arrayOfUsers) |
Setting up our Login System
For this chapter you will have to know about: Variables, Arrays, 2d Arrays, Dictionaries
To create our login system we are first going to have to initiate a variable to store our users.
1 | arrayOfUsers = [] |
This is an array of empty users
Lets add in a new user, we are going to add a dictionary into it, this makes it a kind of 2d array.
We are going to store the username under the key "username" and password under the key "password"
This means the dictionary will look like this for every user:
{"username":"name","password":"password123"} |
Or using an example
{"username":"coolestguy","password":"abc123"} |
Using a dictionary makes it clearer to whoever is reading the program what value we are using. E.g user["username"] is clearer than user[0]
Lets add in a new user to our array like so:
1 | arrayOfUsers = [{"username":"Fred", "password":"password1"}] |
Now we have 1 user in our program who can sign in.
Lets print out our array using the print function
1 | arrayOfUsers = [{"username":"Fred", "password":"password1"}] |
2 | print(arrayOfUsers) |
Add in two more users to your array, remember to use a comma to separate each dictionary
Show Answer1 | arrayOfUsers = [{"username":"Fred", "password":"password1"},{"username":"Selena", "password":"starWars"},{"username":"Ellie", "password":"RedMAn"}] |
2 | print(arrayOfUsers) |
Creating a user specific message
For this chapter you will need to know about: variables, inputs, arrays, functions
We are going to create a very simple message to display when the user logs in
We are going to put everything into functions so that it is broken up and easier to read
Copy down the code below:
3 | def logIntoSystem(user): |
4 | print("Welcome to the login system " + user[0]) |
This bit of code takes in an array called "user". It print the first value stored in the array, which is their name, along with a welcome message
To display this message we need to write the following line of code:
3 | def logIntoSystem(user): |
4 | print("Welcome to the login system " + user[0]) |
5 | |
6 | logIntoSystem(arrayOfUsers[0]) |
user[0] gets the first value in the array
Now print the 3rd user in the list
Show Answer6 | logIntoSystem(user[2]) |
Remember that to get the 3rd element we need to minus one, because arrays start at 0
Now we have something that a user can login to or a profile page, later on we could change this to be the main program
Remove line 6 as we only want this to print when the user signs up or logins in successfully
Creating a user specific message
For this chapter you will need to know about: Variables, Inputs, Arrays, Functions
We are going to create a very simple message to display when the user logs in
We are going to put everything into functions so that it is broken up and easier to read
Copy down the code below:
3 | def logIntoSystem(user): |
4 | print("Welcome to the login system " + user["username"]) |
This bit of code takes in an array called "user". It print the username value stored in the dictionary, which is their name, along with a welcome message
To display this message we need to write the following line of code:
3 | def logIntoSystem(user): |
4 | print("Welcome to the login system " + user["username"]) |
5 | |
6 | logIntoSystem(arrayOfUsers[0]) |
Now print the 3rd user in the list
Show Answer6 | logIntoSystem(arrayOfUsers[2]) |
Remember that to get the 3rd element we need to minus one, because arrays start at 0
Now we have something that a user can login to or a profile page, later on we could change this to be the main program
Remove line 6 as we only want this to print when the user signs up or logins in successfully
Creating Sign Up
For this chapter you will need to know about: Input, Variables, Arrays
We are going to allow new users to sign up, we are going to do this by adding to our array
To make a sign up it is really simple, we have to ask the user for a username and password
Create a function for this event, it is important to break down our code into functions so they can be called in multiple places and makes code easier to read
Create a function that asks the user for their password and username and add the user to arrayOfUsers
Show Answer6 | def signUp(): |
7 | name = input("Enter your username") |
8 | password = input("Enter your password") |
9 | user = [name, password] |
10 | arrayOfUsers.append(user) #this adds the user to the storage space |
10 | logIntoSystem(user) #this runs the program with the new user |
Make it print out the array after you add a user to it, this helps to show that it works correctly
Creating Sign Up
For this chapter you will need to know about: Input, Variables, Arrays
We are going to allow new users to sign up, we are going to do this by adding to our array
Create a function for this event, it is important to break down our code into functions so they can be called in multiple places and makes code easier to read
Create a function that does the following
- Asks the user for a username
- Makes sure that the username is not already taken
- If it is then ask them to enter a new username
6 | def signUp(): |
7 | userInput = "" #The variable should be defined outside of a while loop because when the while loop ends all variables in that while loop are deleted unless they are saved outside like here |
8 | |
9 | while True: #keep repeating until the user enters a correct name |
10 | usernameInput = input("Choose a username: ") |
11 | usernameTaken = False |
12 | for user in arrayOfUsers: |
13 | if(usernameInput == user["username"]): |
14 | print("This username is already taken. Please pick a new username") |
15 | usernameTaken = True |
16 | break #break out of the for loop, we don't need to keep checking if we have already found it |
17 | if(not usernameTaken): |
18 | break #break out of the while loop, a username has been chosen |
Before we ask the user for a password we want to create a new function to allow us to check if the password is valid
This means when the user enters a password the following is true:
Check to make sure the password:
- Is greater than 8 characters long
- Has at least 1 capital letter
- Has at least 1 number in it
- Has at least 1 symbol in it
Have a go at creating a function that takes in a password and returns a message with an error saying why it isn't valid or if it is valid it returns True
Hint: For the last two cases I created a new function to check if any characters from a string were in the password e.g. are any characters from "1234567890" in my password
Show Answer20 | def verifyPassword(password): |
21 | if(len(password) < 8): |
22 | return "Your password needs to be at least 8 characters long" |
23 | if(password == password.lower()): #If the lower case version of the password is the same as the normal one then there are no capital letter |
24 | return "You must have capitals in your password" |
25 | if(not checkIfSymbolsInPassword("1234567890", password)): |
26 | return "You must have numbers in your password" |
27 | if(not checkIfSymbolsInPassword("!\"£$%^&*()_-+=`¬[]{};'#:@~<>?,./\|", password)): |
28 | return "You must have symbols in your password" |
29 | return True |
30 | |
31 | def checkIfSymbolsInPassword(symbols, password): |
32 | for char in password: |
33 | if(char in symbols): |
34 | return True |
35 | return False |
Once you have completed the task above, think about asking the user for a password.
The rest of the function should:
- Ask the user for a password
- Check the password is valid using the criteria above
- If it isn't it should ask for the password again
- Add the new user that has been created into a dictionary
- Return the new user
Make it print out the array after you add a user to it, this helps to show that it works correctly
Show Answer20 | passwordInput = "" |
21 | while True: |
22 | passwordInput = input("Choose a password: ") |
23 | verifyPasswordOutput = verifyPassword(passwordInput) |
24 | if(verifyPasswordOutput == True): |
25 | break |
26 | else: |
27 | print(verifyPasswordOutput) |
28 | print("Please choose a new password") |
29 | |
30 | newUser = {"username": usernameInput, "password": encryptPassword(passwordInput)} |
31 | return newUser |
Creating Sign In
For this chapter you will need to know about:
Now we need to allow users to sign in after they have an account. Currently users are only saved until you end the program and when you start it again then it starts with the default user list. Take this into account when testing this function.
Now we have to think about how we want our program to work. Below is a flow diagram for how this function should work

We are going to need one loop that we do not know how long it will go on for (until the user enters a correct username and password)
We are also going to need to do some kind for loop to check if the user exists
Have a go at creating the signin function using the flow diagram as a guide
Maybe have a print statement to tell the user there was no match and they have to type in their username and password again
Show Answer13 | def signIn(): |
14 | while True: #this happens infinitely until the user enters a correct username and password |
15 | usernameInput = input("Enter your username: ") |
16 | passwordInput = input("Enter your password: ") |
17 | for user in arrayOfUsers: #this cycles through all the users in the array |
18 | if(usernameInput == user[0] and passwordInput == user[1]): |
19 | logIntoSystem(user) #this logs the user into the system |
20 | return |
21 | print("Your username and password did not match. Please try again.") |
For this chapter you will need to know about:
Now we need to allow users to sign in after they have an account. Currently users are only saved until you end the program and when you start it again then it starts with the default user list. Take this into account when testing this function.
Now we have to think about how we want our program to work. Below is a flow diagram for how this function should work

You could make this using a for loop or a while loop, for this example I will make it using a while loop
Have a go at creating the signin function using the flow diagram as a guide
Maybe have a print statement to tell the user there was no match and they have to type in their username and password again
If the user exists then return it to end the function, if the user reaches 4 attempts then exit the program
Show Answer51 | def signIn(): |
52 | attempts = 0 |
53 | while True: |
54 | if(attempts > 3): |
55 | print("You have attempted to login too many times") |
56 | exit() |
57 | usernameInput = input("Enter your username: ") |
58 | passwordInput = input("Enter your password: ") |
59 | for user in retrieveUsers(): |
60 | if(usernameInput == user["username"] and passwordInput == user["password"]): |
61 | return user |
62 | attempts += 1 |
63 | print("Your username and password did not match. Please try again.") |
Creating a Menu
For this chapter you will need to know about: inputs
Lets create a menu for the user to choose from when they start the program
The menu should look something like this:

The user will have the option to input option 1 or option 2
If they put in something else it should just ask for the input again
Try and code this menu, the options should call the functions you have already created
Show Answer21 | menuOption(): |
22 | print("Welcome to this login menu\nDo you want to:\n1)Sign Up\n2)Sign in") |
23 | while True: |
24 | userResponse = input("") |
25 | if(userResponse == "1"): |
26 | signUp() #this will run the sign up menu |
27 | elif(userResponse == "2"): |
28 | signIn() #this will run the sign in menu |
29 | else: |
30 | print("That was not a correct response, please try again") |
31 | |
32 | menuOption() #this will run the function |
We now have a login system that works!
For this chapter you will need to know about: inputs
Lets create a menu for the user to choose from when they start the program
The menu should look something like this:

The user will have the option to input option 1 or option 2
If they put in something else it should just ask for the input again
Both the signin and signout functions return the user if its successful so use this to run the login function
Try and code this menu, the options should call the functions you have already created
Show Answer65 | def menuOption(): |
66 | print("Welcome to this login menu\nDo you want to:\n1)Sign Up\n2)Sign in") |
67 | signInUser = False |
68 | while True: |
69 | userResponse = input("") |
70 | if(userResponse == "1"): |
71 | startLoginSystem(signUp()) |
72 | break |
73 | elif(userResponse == "2"): |
74 | startLoginSystem(signIn()) |
75 | break |
76 | else: |
77 | print("That was not a correct response, please try again") |
We now have a login system that works!
Reading the users from a file
For this chapter you will need to know about: inputs
The problem at the moment is that our login system can only store users if the program is running
We need to be able to save the usernames and passwords to a file so we can save and load them in the future
Instead of an array of users, we want to create a new array from the file each time we want to search it
First of all create a users.txt file in the same directory as your python script, this makes it easier to find
We want our users to be stored in the same way each time and we want to be able to know when information for one user finishes and the next one starts
Below is what we should use for this example
Fred, password | |
Selena, 12345 |
Each line represents data for a new user and the comma seperates the username and password, so when we read the file we want to split the data on the comma and save the left side as a username and the right side as a password
Have a go at writing a function called retrieve users to load an array of users from a file
34 | def retrieveUsers(): |
35 | userDataFile = open("./users.txt", "r") |
36 | lines = userDataFile.readlines() #Reads all the lines and puts them into an array of lines |
37 | userDataFile.close() #We have finished reading the file so we close it |
38 | listOfUsers = [] #Creates an empty list of users to fill |
39 | for line in lines: |
40 | line = line.strip() #Remove any white space (this means spaces or new lines) |
41 | splitUsers = line.split(",") #Split the string on the "," so that we have two seperate parts |
42 | listOfUsers.append([splitUsers[0],splitUsers[1]]) #Adds the user to the array |
43 | return listOfUsers #This will return an array of users like the one we stored at the top before |
Because this returns an array which will be the same as the one we created in the earlier chapters:
1 | arrayOfUsers = [["Fred", password1],["Selena", starWars],["Ellie", RedMAn]] |
We can replace any mention of arrayOfUsers with our function retrieveUsers()
That means we can replace our mention of it on line 17:
17 | for user in arrayOfUsers: |
With:
17 | for user in retrieveUsers(): |
79 | filePath = "./users.txt" #create a variable so that we only need to change it in one place |
80 | def retrieveUsers(): |
81 | userDataFile = open(filePath, "r") |
82 | lines = userDataFile.readlines() |
83 | userDataFile.close() |
84 | listOfUsers = [] |
85 | for line in lines: |
86 | line = line.strip() |
87 | splitUsers = line.split(",") |
88 | listOfUsers.append({"username": splitUsers[0], "password": splitUsers[1]}) |
89 | return listOfUsers |
Because this returns an array which will be the same as the one we created in the earlier chapters:
1 | arrayOfUsers = [{"username":"Fred","password":"password1"},{"username":"Selena", "password":"starWars"],{"username":"Ellie", "password":"RedMAn"}] |
We can replace any mention of arrayOfUsers with our function retrieveUsers() as they will give the same information
That means we can replace our mention of it on line 16:
12 | for user in arrayOfUsers: |
With:
12 | for user in retrieveUsers(): |
Do the same with any other mention of arrayOfUsers
Now we can load data from a file, test it out by writing some new users in the file using a comma to seperate their username and password and a new line to represent a new user
Then try and login with one of those created users
Saving to a file
For this chapter you will need to know about: Writing to a file
We have almost finished our login system, the only feature left to implement is saving new users into a text file
So we need to open up our users.txt file and add a new user separating their username and password using a comma like below:
Fred, password | |
Selena, 12345 |
Create a function which takes in 1 parameter "user". User is an array of user information, use this information to add their details to the end of the users.txt file
91 | def addUser(user): |
92 | userDataFile = open("./users.txt", "a") |
93 | userDataFile.write(user[0] + "," + user[1] + "\n") |
94 | userDataFile.close() |
Think about where we need to call this function and what parameters we need to pass it
9 | user = [name, password] |
10 | addUser(user) |
11 | logIntoSystem(user) |
We now have a fully working login system, if you want to try out the advanced login system then swap this tutorial to advanced at the top right
30 | newUser = {"username": usernameInput, "password": encryptPassword(passwordInput)} |
31 | addUser(user) |
32 | return newUser |
We now have a fully working login system!
For this next section we are going to encrypt our password so if you look at the txt file you can't work out what the password is
For this we need to use a hash function. A hash function takes a value, which could be anything, and converts it to a random set of characters. What is important about a hash function is that:
- If you put in the same key you always get the same output
- Its very hard to start at the output and go back to the input. This can be done using the % function
Have a go at making your own hash function. Think about converting characters to their ascii alternatives and combining all these numbers together
Show Answer95 | def encryptPassword(password): |
96 | passwordValue = 1 |
97 | for character in password: |
98 | passwordValue = (passwordValue * ord(character)) + (4 * passwordValue) |
99 | passwordValue = (passwordValue % 12345) * (passwordValue % 12345) * 4 |
100 | return str(passwordValue) |
Think about where we need to put this function, we only need to use it when comparing the user input password to the stored password
Show Answer30 | newUser = {"username": usernameInput, "password": encryptPassword(passwordInput)} |
60 | if(usernameInput == user["username"] and encryptPassword(passwordInput) == user["password"]): |
Variables
Variables is the memory of a program, when you want the computer to remember a value you create a variable to store it in
x = 0 | |
age = 16 | |
year = 2018 |
We use one equal sign, this means that the variable name on the left is equal to the value given on the right
variableName = Value |
The variable name can be whatever we want but can't include spaces and shouldn't start with a capital letter
We can then manipulate the variables by changing it later. When we store a number in a variable it is called an integer
x = 0 #x now equals 0 | |
x = 2 #x now equals 2 and the 0 is replaced | |
x = x + 2 # x = 4 | |
x = x * 2 # x = 8 | |
y = 2 | |
x = x + y # x = 10 |
When you want to store sentences or words we store them in strings like below:
name = "Oliver" | |
Country = "England" |
Make sure you have the speech marks surrounding the strings otherwise it will treat it as a variable
You can manipulate strings and add them together
name = "Oliver" + " " + "Smith" # name = "Oliver Smith" | |
greeting = "Hello" | |
greetingTwo = "Friend" | |
welcomeMessage = greeting + " " + greetingTwo #welcomeMessage = "Hello Friend" |
Have a go yourself
Question 1
x = 2 | |
y = 3 | |
x = 5 |
What is the value of x by the end of the program?
Question 2
x = 2 | |
x = x + 3 | |
y = 3 | |
x = x * 2 |
What is the value of x by the end of the program?
Question 3
x = 2 | |
y = 6 | |
x = y | |
x = x + 2 |
What is the value of x by the end of the program?
Question 4
name = "Donald Jones" | |
country = "Germany" | |
message = "Welcome " + name |
What is the value of message by the end of the program?
Question 5
name = "Donald Jones" | |
country = "Germany" | |
message = country + "," + name |
What is the value of message by the end of the program?
Question 6
What symbol should you have at the start and end of a string?
Functions
A function is a section of code that you can call in multiple places, it can take in parameters that can change the output but the process will be the same
As an example you could have a function that adds two numbers, the process will be the same every time but the outcome will depend on the two numbers entered
def addNumbers(a,b): | |
return a + b |
You can then call the function:
addNumbers(2,3) #returns 5 |
Make sure to indent all the code you want to be inside the function, non indented code will not be run when the function is called
def function(): | |
print(1) #Will be run when the function is called | |
print(2) #Will be run when the function is called | |
print(3) #Isn't related to the function |
Sometimes you want to return something when a function finishes, this means the function generates a variable and returns it. When you want to do the equation 2 + 4 * 5 you want the multiply to be returned first so the equation becomes 2 + 10. Similarly in programming the function should return something so that the rest of the program can continue
def returnHello(): | |
return "Hello" | |
msg = returnHello() + " Bob" # This variable stores "Hello Bob" |
You can have as many parameters as you want
def returnHello(): | |
return "Hello" | |
msg = returnHello() + " Bob" # This variable stores "Hello Bob" |
Have a go yourself
Question 1
def returnNumber(a): | |
return 2 |
What is the value of x by the end of the program?
Inputs
Inputs is a function that requests a value from the user. It looks something like this:
input("What is your name") |
You put your question between the () such as "What is your name?", "What country are you from?", "Enter your date of birth"
This function returns a string so we can store it in a variable
name = input("What is your name") | |
print(name) #this will output whatever the user input |
As it always returns a string then if we want them to input an integer we have to convert it
In the example below, it takes an input from the user, converts this to an integer and stores it in a variable
name = int(input("How old are you?")) #if you enter 3 it will be the string "3" so you need to convert it |
Have a go yourself
Question 1
date = ______("Please enter the date") |
Fill in the blank
Question 2
input("What is your favourite subject?") |
What question will the program ask the user?
Question 3
subject = input("What is your favourite subject?") |
What is the name of the element highlighted in bold?
Question 4
What is the variable type returned by the input function?
The print statement prints the variable or collection of variables that you pass as a parameter
print("What is your name") # "What is your name" | |
x = 3 | |
print(3) # 3 | |
print(x) # 3 | |
print(x + 3) # 6 | |
print(input("Password:")) # Prints what the user inserted |
When you use the print statement with a string it prints out the speech marks to show that it is a string
Have a go yourself
Question 1
x = 6 | |
print(7) |
What gets printed out?
Question 2
x = 6 | |
print(x + 4) |
What gets printed out?
Question 3
msg = "Hello" | |
print(msg) |
What gets printed out?
Arrays
Arrays are lists of information stored in one variable, this makes it easier to access
[1,2,3,4,5,6,7,8,9] |
Above is an array of numbers from 1 to 9, but they could be any type of variable:
["London", "Paris", "Beijing", "Cairo", "Berlin"] |
We can access any element in a list by putting square brackets after the array name like below:
1 | cities = ["London", "Paris", "Beijing", "Cairo", "Berlin"] |
2 | print(cities[0]) #prints out London |
2 | print(cities[2]) #prints out Beijing |
3 | print(cities[4]) #prints out Berlin |
Note that arrays start at the 0th element
You can also use negative numbers in arrays to get the last elements in a list
1 | cities = ["London", "Paris", "Beijing", "Cairo", "Berlin"] |
2 | print(cities[-1]) #prints out Berlin |
2 | print(cities[-2]) #prints out Cairo |
You can add to an array using the following command:
1 | cities = ["London", "Paris"] |
2 | cities.append("Barcelona") |
3 | print(cities) #prints out ["London", "Paris", "Barcelona"] |
Append always adds to the end of an array
You can remove an item from the array using the following command:
1 | cities = ["London", "Paris", "Barcelona"] |
2 | cities.pop(1) #1 refers to the index of the item |
3 | print(cities) #prints out ["London", "Barcelona"] |
Have a go yourself
Question 1
1 | names = ["John","Julie","Oliver","Sebastian","Jackie","Mike"] |
2 | print(names[2]) |
What gets printed out?
Question 2
1 | names = ["John","Julie","Oliver","Sebastian","Jackie","Mike"] |
2 | print(names[0]) |
What gets printed out?
Question 3
1 | names = ["John","Julie","Oliver"] |
2 | names.append("Jackie") |
3 | names.pop(1) |
4 | print("1") |
What gets printed out?
Question 4
1 | names = ["John","Julie","Oliver","Sebastian","Jackie","Mike"] |
2 | print(names[-1]) |
What gets printed out?
2D Arrays
2D arrays are arrays within arrays, this makes them display like a table
[["Mark", 24, "HA2 3HW"],["Jeremy", 18, "FD2 4FD"],["Niamh", 21, "JF4 3WW"]] |
We can access information within an array using two square brackets like below:
1 | information = [["Mark", 24, "HA2 3HW"],["Jeremy", 18, "FD2 4FD"],["Niamh", 21, "JF4 3WW"]] |
2 | print(information[0]) #prints ["Mark", 24, "HA2 3HW"] |
3 | print(information[0][1]) #prints 24 |
4 | print(information[1][2]) #prints "FD2 4FD" |
5 | print(information[2][0]) #prints "Niamh" |
If it helps, imagine it like a table of information where the first value is which column you want and the 2nd value is what row you want
[0][ ] | [1][ ] | [2][ ] | |
[ ][0] | "Mark" | "Jeremy" | "Niamh" |
[ ][1] | 24 | 18 | 21 |
[ ][2] | "HA2 3HW" | "FD2 4FD" | "JF4 3WW" |
2D arrays are used to store multidimensional data such as user information, if you wanted the age of all your users you could loop through each list and look at the same array position each time
Have a go yourself
Question 1
1 | names = ["John","Julie","Oliver","Sebastian","Jackie","Mike"] |
2 | print(names[2]) |
What gets printed out?
Question 1
1 | numbers = [[1,2,3],[4,5,6],[7,8,9]] |
2 | print(numbers[2]) |
What gets printed out?
Question 2
1 | numbers = [[1,2,3],[4,5,6],[7,8,9]] |
2 | print(numbers[0]) |
What gets printed out?
Question 3
1 | numbers = [[1,2,3],[4,5,6],[7,8,9]] |
2 | print(numbers[0][2]) |
What gets printed out?
Question 4
1 | numbers = [[1,2,3],[4,5,6],[7,8,9]] |
2 | print(numbers[2][1]) |
What gets printed out?
Reading a file
Python can read and write to text files (txt). This can be useful for saving information that can be accessed later
This command opens a file:
1 | open("./users.txt", "r") |
There are 2 other commands you can replace r with which we will cover in writing to a file
"r" in this situation means read only so you cannot edit the file
1 | userDataFile = open("./users.txt", "r") #Make sure you change the name to open the file you want |
2 | lines = userDataFile.readlines() #Stores all the lines in this variable as an array of strings |
3 | userDataFile.close() #This shows we have finished with the file and can allow other programs to use the file |
Now our file information is stored in a variable we can use a for loop to go through the list like below
6 | for line in lines: |
7 | print(line) |
Have a go yourself
Question 1
What letter is passed as a parameter when opening a file in read only mode?
Question 2
1 | d = open("./example.txt", "r") |
2 | x = d.readlines() |
3 | d.close() |
Which variable has all the lines from the file stored in it
Writing to a file
Writing to a file is a lot easier than reading to a file
userDataFile = open("./users.txt", "w") |
Instead of writing r for read only we write either:
- "w" = Write and replace
- "a" = Append to the end of the file
If you want to read in all the data, edit it and then save it you would want to use "w" and if you wanted to add some extra data to a file you would use "a"
To write to a file you use the following command
userDataFile.write("some new content" + "\n") |
The \n tells the program to add a new line
Once you have finished writing then you need to close the file like before
userDataFile.close() #This allows other programs to access this file |
Have a go yourself
Question 1
What letter is passed as a parameter when opening a file in append mode?
Question 2
What letter is passed as a parameter when opening a file in write mode?
Question 3
If you want to write something on the next line what do you have to type?
Dictionaries
A dictionary is very similar to an array but you save information with "keys" which are generally words so that it is easier to find the correct bit of information later
info = {"name":"Benji", "age":25, "job": "Police Man"} | |
print(info["name"]) #This will return "Benji" | |
print(info["job"]) #This will return "Police Man" |
We can add to a dictionary by simply doing the following:
info = {"name":"Benji", "age":25, "job": "Police Man"} | |
info["gender"] = "Male" | |
print(info) #This prints {"name":"Benji", "age":25, "job": "Police Man", "gender": Male} |
Dictionaries make it a lot easier for someone reading the code to understand what value you are getting from a list
Have a go yourself
Question 1
favourites = {"city":"Berlin", "food":"pasta", "number": 9} | |
print(favourites["city"]) |
What value is printed out?
Question 2
favourites = {"city":"Berlin", "food":"pasta", "number": 9} | |
print(favourites["number"]) |
What value is printed out?
Question 3
favourites = {"city":"Berlin", "food":"pasta", "number": 9} | |
favourties["city"] = "London" | |
print(favourties["city"]) |
What value is printed out?