Learning Outcomes
• variables, constants, and Boolean and arithmetic operators;
• input, output and assignment statements;
• one-dimensional array structures.
There are a range of different data-types we can use to deal with different pieces of information.
String: This is used to represent text, including numbers, letters and symbols.
This can be used for variables such as...
Note we put quotes around strings and characters
name="Fred"
postcode="BT82 9PS"
productNumber="AC1278372"
mobileNumber="07826761829"
accountNumber=0129827
Why have I set mobileNumber and accountNumber as strings?
Character: This is used to represent a single letter,number or symbol.
This can be used for variables such as...
initial="G"
gender="F"
Integer: This is used to represent whole numbers, we can perform mathematical functions on integers.
This can be used for variables such as...
age=17
weightKG=93
Note we do not put quotes around integers.
Real(Float): This is used to represent decimal numbers, again we can perform mathematical functions on reals.
pi=3.14
payRate=9.45
Boolean: This has two possible states True or False.
These are often used like switches to control the flow around a program. Note the use of a capital letter at the start of True/False and the lack of quotes.
validUser=False
accountLocked=True
Note that all data input by users by default will be of String data-type.
In programs we often need to collect data from a user, to achieve this we create a variable with an appropriate name to describe the data and use the keyword input. This process is shown below...
name=input("Please enter your name:")
We created a variable with the identifier name. It will be used to hold the data input by the user. Each variable must use a unique identifier.
height=input("Please enter your height in cm:")
weight=input("Please enter your weight in kg:)
The = sign is used to assign a value to a variable.
The input statements above can also be writen as....
print("Please enter your name:")
name=input("")
Both of these methods will achieve the same thing.
To output a piece of data to the screen we use the print() function.
print("Hello and Welcome to my App")
We can also output variables.
print(username)
We sometimes need to combine strings to form sentences we can do this by using concatenation. This is simply when we use the + sign to join them.
print("Hello "+name +" welcome to my App")
In programs we often need to change the datatype of a vaiable. Casting is the term used to describe the changing of a variable from one data type to another.
In the above example the data input by the user is stored as a string. If we wanted to use this data in a calculation, let's say to calculate someone's BMI, we would need to convert it to an integer/float. This can be done using the int() function as shown in the example below.
height=int(input("Please enter your height in cm:"))
weight=int(input("Please enter your weight in kg:))
Sequence is when a set of instructions are carried out in order one after another. This example below shows how we might use sequence to calcualte the area of a rectangle.
length=input("Please enter the length in cm:)
width=input("Please enter the width in cm:)
area=length*width
print("The area of the rectangle is "+str(area))
The lines above will be executed one after the other.
Selection is when the computer is going to evaluate a condition to determine what it should do next. This is used when there are two or more possibilities.
if area<20:
print("This is a small rectangle")
elif area <40:
print("This is a medium sized rectangle")
else:
print ("This is a large sized rectangle")
We can use as many elif as we need but every if statement should have one if and one else at the start and end.
It can also be used to check an answer to determine whether it is correct or incorrect.
correctAnswer="Paris"
userAnswer=input("What is the capital of France called?")
if correctAnswer==userAnswer:
print ("Correct")
else:
print ("That is incorrect, Paris is the capital of France")
The code below performs the same task but in a slightly different way.
userAnswer=input("What is the capital of France called?")
if (userAnswer=="Paris") or (userAnswer=="paris") or (userAnswer=="PARIS)
print ("Correct")
else:
print ("That is incorrect, Paris is the capital of France")
In this example we haven't created a variable to hold the answer we simply check it in the IF Else, note this will have 3 possible correct answers.
Iteration is used when we want to repeat certain pieces of code. For example in a login system if the person puts inthe wrong details we would want them to be allowed to try again. There are two main methods used for iteration.
1:For Loops
These are used when we want the code to be repeated for a certain amount of times.
For i in range (0,5):
print ("apple")
The above code will print out the word apple 5 times. The variable i starts off with the value 0 and increments (increases by 1) until it reaches the value 5 when it stops.
For x in range (10,20):
print("banana")
This code will print out the word banana 10 times. The variable x starts off with the value 10 and increments until it reaches the value 20 when it stops.
2:While Loops
These can be used went we want a condition to control the loop.
validuser=False
while validuser==False:
username=("Please enter your username":)
password=input("Please enter your password")
if (username=="Jim") and (password=="Lisnaskea456"):
validuser=True
print("Welcome to the program")
In the code above the user will be prompted to enter a username and password, when they type in the correct details validuser is turned to True which will mean the loop is exited and the welcome message is printed. When the incorrect details are entered the user is kept in the loop.
The following operators can be used to perform a randge of functions. The arithmetic operators are used mostly when doing calculations using integers and floats. The conditional operators and used mostly in IF Statements.
Arrays
Often a programmer wishes to group together a collection of related data items. Most programming languages - Python included - provide a variety of different methods to achieve this. One widely used method uses arrays.
Array “[An array] is a set of data items of the same type grouped together using a single identifier. Each of the data items is is addressed by the variable name and a subscript.” BCS Glossary of Computing, 13th edition, p 326.
In order to use use an array in Python it is first necessary to import the array module from the Python Standard Library. As you gain experience in the use of Python you will learn that many useful features are available via the Standard Library. Fortunately, it is very straightforward to import a module - requiring only a single line of Python code. In this case, all that is needed is the following line of code, which may be used in interactive mode or included in a script.
The following code, for example, creates an array, called my_array, containing the integers 1, 2 and 3.
The value ‘i’ means that the array is only allowed to contain integers.
my_array = array(‘i’, [1,2,3])
>>> We can use a print statement to display the array.
print(my_array) array(‘i’, [1, 2, 3])
We can display individual items contained in an array. Each one is referred to by its index (within square brackets). The index of an item is simply its position within the array and, of course, we start counting at 0 rather than 1.
print(my_array[0]) 1
print(my_array[2]) 3
We can add an item to the end of an array using the append method.
my_array.append(4)
print(my_array) array(‘i’, [1, 2, 3, 4])
We can insert an item into an array at a specified location using the insert method.
my_array.insert(0,0)
print(my_array) array(‘i’, [0, 1, 2, 3, 4])
We can remove a specified item from an array.
my_array.remove(2)
print(my_array) array(‘i’, [0, 1, 3, 4])
The array module provides more methods but these are some of the most important ones .
Python arrays are a little restrictive in the data types that they may contain. Fortunately Python provides other ways of grouping related data together. One of the most commonly used is the Python list.
Lists
In Python, lists are similar to arrays except that they may contain a wider range of data types - indeed a single list may contain data items of different types. The following code, for example, creates a list, called my_list, containing the values 1, ‘two’ and 3.0. You will notice that the first value is an int, the second is a string, while the third is a floating point number. It is not possible to mix data types in this way in an array.
my_list=[1,’two’,3.0]
print(my_list)
[1, ‘two’, 3.0]
You can see below that accessing a data item in a list is similar to the corresponding operation in an array.
(my_list[0])
1
print(my_list[2])
3.0
Similarly, the append, insert and remove methods work in the same way for lists as for arrays.
my_list.append(‘FOUR’)
print(my_list)
[1, ‘two’, 3.0, ‘FOUR’]
my_list.insert(0,’ZeRo’)
print(my_list)
[‘ZeRo’, 1, ‘two’, 3.0, ‘FOUR’]
my_list.remove(‘two’)
print(my_list)
[‘ZeRo’, 1, 3.0, ‘FOUR’]
Because of their flexibility lists are more frequently used than arrays in Python. Arrays and lists may also be used in the programming languages Java and C#.
We can create really powerful programs when we combine loops and lists. In the example below you will see some of the different ways we can create reports on a set of data held in lists. Usually in this type of program we would hold the data in an external file and import it into the program. This is explained below. Read the writing in green which expalins each section of the code.
If we want to hold the data in a program for long term we must store it in a file. It is good practice to use a file to keep the data and read the data into lists each time you open the program. Before the program is closed we need to make sure the data in our lists is writen back to the file. This will log any changes that have been made to the files during the session.
nameFile=open("names.txt","r")
The code above will open a text file called names. This should be stored in the same folder as our program. In thebrackets the "r" stands for read mode, this means we can get the data but not update it. To change the data we would need to open it in write mode by changing "r" to "w".
nameFile=open("names.txt","w)
This code would open the file in write mode, so we can change the data.
We then create a container to hold the data within the program.
nameData=nameFile.read()
The next step is to split the data in the file into a list, this is done below. The "\n" means that each item on each line will be added into the list one at a time. We can also separate using commas or any other way. Most people would consider new lines or commas as best practice.
The text file using the new line approach would look like this...
Jim
Mary
Sue
The text file using the comma approach would look like this...
Jim, Mary, Sue
We can use notepad to create the text files.
nameList=nameData.split("\n")
To close the file we use the following code...
nameFile.close()
To write the data from the list back into the file we use this code...
with open("names.txt","w") as filehandle:
for listitem in nameList:
filehandle.write("%s\n"% listitem)
You can choose to write the data to the file after it is input or you could write all of the data to the file at the end of each users session.
We can also use CSV files to hold information. These work in much the same way as text files although the code is different. It doesn't matter which method we use as long as we get it working.
String Splitting
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
The above code will split the variable txt and add each piece of text between the hashtags as an item into a list x. X would look like ["apple","banana","cherry","orange"]. We can split a string on any character or group of characters.
Concatenation
firstName="Jim"
lastName="Brown"
print("Hello "+firstName+ " "+lastName)
The above code takes the two variables firstName and lastName and adds them to the world hello. Concatenation is the use of the + symbol to join strings together.
Character searching
string = "freeCodeCamp"
print(string[0:5])
output "freeC"
The above code gives is the first 5 characters from the string.
string = "freeCodeCamp"
print(string[2:6])
output "eeCo"
The above code starts at position 2 and returns up to but not including position 6.
string = "freeCodeCamp"
print(string[-1])
output "p"
This code returns the last character
string = "freeCodeCamp"
print(string[-5:])
output "ecamp"
This code returns the last 5 characters
string = "freeCodeCamp"
print(string[1:-4])
output "reeCode"
This code removes the first character and the last 4.