<<

An introduction to Python

supported by

An introduction to Python

Abstract

This guide provides a simple introduction to Python with examples and exercises to assist learning. Python is a high level object-oriented programming language. Data and functions are contained within an object (or storage container) which can then be used at a later stage in a program. Python is readable and simple to and hence is a great starting language for programming. Python has been around for over 20 years resulting in lots of available resources and many user created libraries to assist you or simplify tasks. Currently Python 3 is available with new features but Python 2 is still most commonly used and most libraries were built to work with this version. Hence we will learn the appropriate syntax for Python 2, however most code remains consistent if you wish to move to Python 3.

An introduction to Python

Contents

1 Getting started with Python 1

2 Data Types 7

3 Numbers, Booleans and Math 8

4 Strings 10

5 Variables 16

6 Output - The print function 19

7 User input 22

8 Operators 24

9 Defining Functions 29

10 Conditional Logic 33

11 Lists 38

12 Loops 48

13 Additional Topics 53 13.1 Vectors/Matrices ...... 53 13.2 Dictionaries ...... 54 13.3 Visualisation ...... 56 13.4 Exception Handling ...... 57

14 Free Online Resources 60

An introduction to Python

1 Getting started with Python

When we use applications like Scratch, the blocks are converted into code which tells the computer what you wish to do. This code is the programming language that gives instructions to a computer which could be written in Python. In Python we can write a program which is just a sequence of instructions written in code which the computer can interpret and execute. These instructions are often referred to as statements/commands but are just lines of code telling the computer what you want it to do. There are diff erent ways to write and run Python code.

Python shell and scripting

The python shell is useful for calculations or one line of code. You type in the code and get an output underneath. This code is not saved. Scripting is writing lines of code to create a program which you want to save and run in the future. You can simply write the code in a text file and save it as "filename.py" which can then be run using python.

Python editors

Often Python editors or IDEs (Integrated Development Environments) are used when writing Python scripts so that you to build up a project containing multiple Python files. There are many different editors such as Pycharm, , , PyScripter and Jupyter note-books. The examples throughout this guide are images from Trinket (trinket.io) an all-in-one coding environment designed for education. There’s no software to install to use Trinket as it runs in a web browser. Trinket provides a clean way to see the outputs clearly alongside the code input and is a great starting tool for learning Python.

Page 1

An introduction to Python

Importing libraries/functions

A function is a named sequence of statements of instructions that you can use in your programme. There are many functions/commands available in basic Python that you can use without even thinking about. Many of these functions will be used throughout this booklet. However some functions are stored within libraries and so you have to inform Python that you wish to use them. For example, suppose you wish to find the square root of 16. Typing sqrt(16) will produce an error stating sqrt not defined.

This is because the function sqrt is stored inside the math library. This is easily solved using the following code:

This will output the answer of 4 as expected. If you wanted to import the whole library, you can just use an import math statement.

Sometimes as functions can have similar names we want to ensure we are using the correct one from the required package. In this case we have two options:

Page 2

An introduction to Python

The second case is an optional shorthand that could be used if you will be using many functions from the one package. You will see this used often for popular packages such as numpy (np) or pandas (pd).

Functions or Methods

When it comes to understanding some of the terminology in Python, it can seem more complex than it is to use. Functions and methods are often confused and you can use Python without understanding the diff erence, as long as you know how to use them.

Functions are stand alone, so you must provide them with the appropriate arguments they need to produce a result. They use the syntax my_function(x) taking x as input, doing something to that and outputting the result, for example, taking a number and finding the square root like sqrt.

Methods are associated with objects or classes (groups) of object. You may have an object that is a word and you can apply a set number of operations to this object and only objects of this type. These methods use the syntax object.method() where the object is your word e.g. "HELLO".lower(). It sounds complicated but you will learn common functions and methods and so you know the appropriate syntax to use throughout this booklet.

Good Coding Standards

There are many good coding standards you should abide by when writing code in Python. The structure of statements is often referred to as syntax. The list below outlines the key principles you should follow:

• Commenting & Documentation - It is important to add comments to your

Page 3

An introduction to Python

code, not only for other users’ benefit but also your own. It should allow you to easily follow what the programme is doing, however, if a line of code is self- explanatory then there is no need to comment. Single line comments are included using the octothorpe/hashtag symbol (# This is a comment) and multiline comments use triple double quotes (""" some long comment """).

• Consistent Indentation - It is best practice to add indents or tab spaces to your code for easy reading. This becomes particularly important when we introduce functions and loops.

• Code Grouping - It is a good idea to leave spaces between related code, for example, between functions.

• Consistent Naming Scheme - There are two popular options for naming variables and functions in Python: camelCase is where the first letter of each word is capitalised, except the first word, whereas underscores uses underscores between words, like, my_name. You should stick to one type of naming scheme throughout your code.

• DRY - Don’t Repeat Yourself. If you are going to repeat some lines of code this can be defined in a function for multiple use. We will see how to implement this later.

• Limit line length - Keeping code lines short enough to follow without having to scroll across the screen is a good habit so that you can easily scan the code for errors. Combining shorter lines and indentation allows quicker reading of your code.

• Programme ordering - Often, a programme description is written as a comment at the start of the programme, followed by imports and then user defined functions. The ordering of the code should be logical so that it is easily followed and understood.

Page 4

An introduction to Python

Getting help

Python has a built in help utility, where you can get documentation about objects, methods, and attributes. To obtain documentation we just use the help() function around the name of the object e.g. help(str) will outline the definition of a string object and the functions/methods associated to that. There is also a lot of help available online at https://docs.python.org/2/library/.

Bugs and Testing

When we write programmes, we start small, ensuring that we obtain a piece of code that runs correctly and then we can build upon it. In order to ensure our code runs correctly, we must use a computational thinking concept known as debugging to check for errors and correct them. It is important to remember that not all errors will be obvious - error messages will only appear if Python fails to run the code. If our code runs, it does not necessarily mean it will produce the expected output. We must therefore test each piece of code and ensure we obtain the correct result. Testing could be done manually, however as programs become more complex, we require functions to test our code. If Python fails to run the code you may obtain an error message. The list below highlights some of the errors you may observe and what they relate to. This should help you to find and correct the code that Python is failing on. Some of these may not make complete sense yet but as you work through the booklet, you will understand these errors.

Types of Errors

• Attribute Error - Your object is the wrong data type for the method you are using. An example would be trying to append to an integer.

• Syntax Error - This suggests a problem with a sequence of characters or words. Some examples would be if quotes are missing around a string, a

Page 5

An introduction to Python

colon is missing after an if/for statement or brackets are mismatched.

• Type error - This suggests that there is a problem with the type of an object. Examples include using a function with the wrong number or type of arguments or using an object which Python expected to have a value and has None.

• Indentation error - Your code is not aligned correctly.

• Name error - Python cannot find the function/object called. Examples include calling functions before they are defined, forgetting to import the relevant module or spelling a function/variable incorrectly.

• IO error - The file you are trying to import/open does not exist

• Key error - The key does not exist in the specified dictionary.

Page 6

An introduction to Python

2 Data Types

Every value in Python has a datatype. Data types in Python include Integers (int), Floats (float), Booleans (bool), Strings (str), Lists (list) and Dictionaries (dict). These will be discussed over the next few sections. We can find the type of an object by using the type function.

There are functions and commands in Python which will only work for specific data types, for example, a function that multiplies two numbers will not work if you input two letters for the function to multiply.

Page 7

An introduction to Python

3 Numbers, Booleans and Math

Integers

An integer in Python is a whole number which can be positive or negative. It is abbreviated to int when using the type function as shown in the example above. Some examples are 1,-1,1000 etc.

Floats

A float (or floating point number) is a decimal number containing a decimal point, for example, 3.6. Floats are like real numbers in Python.

Booleans

A Boolean value can take one of two values, generally True or False. This data type will become useful when we look at conditional logic in section 10. If we converted a Boolean to a number, True is converted to 1 and False 0. The data type is abbreviated to bool.

Math

Python can be used as a simple calculator.

Operator Function Example Input Example Output

+ Addition 2+2 4 - Subtraction 5-2 3 * Multiplication 3*5 15 / Division 15.0/4.0 3.75 // Integer Division 15.0//4.0 3.0 % Remainder 15%4 3 ** Exponent 2**3 8

Page 8

An introduction to Python

Important Notes:

• If you use integers in a division calculation (/), the output will be the floored integer (i.e. rounded down). Once children begin to learn about remainders and decimals then floats can be introduced. This is Python 2 specific and in Python 3 you must use (//) to obtain the floored integer.

• Python follows the expected operational ordering BIDMAS (Brackets, Indices, Division, Multiplication, Addition and Subtraction). However, you can use brackets to be clear what you wish to calculate.

Knowledge Point

3.1 What is the data type of 7.8? Use Python to check this answer.

3.2 Use Python to compare the answers to the following math equations:

• 2+3*4

• (2+3)*4

3.3 Compare the answer for the following questions:

• 17/3

• 17//3

• 17.0/3.0

• 17.0//3.0

Can you tell the data type of the answers? Do you understand why the results are diff erent?

Page 9

An introduction to Python

4 Strings

A string is a sequence of characters which are contained inside single or double quotes. Basically a string is a word, sentence or paragraph e.g. "My name is Bob", "Hello", 'Goodbye'. If we wish to use apostrophes or speech marks inside a string we must either use the opposite quotes for defining the string or use escape characters.

"It's a lovely day today!"

'It\'s a lovely day today!'

If we have a very long paragraph, we can use triple single quotes.

'''Today we are learning about strings in python. You have to be careful when using single or double quotes together. Using Triple quotes allows strings to extend over multiple lines like this! It also allows 'single quotes' and "double quotes" to be used inside. '''

Adding Strings

When you combine two strings into one string it is called string concatenation. It is as simple as using:

Note: If you wanted to add two words with a space between them you need to tell Python that a space is needed.

Page 10

An introduction to Python

If we forget the space Python will output "GreenApple".

Repeating Strings

If we want to repeat a string multiple times we can just use the multiplication operator *.

Indexing Strings

Every character in a string is indexed which means it is assigned to a number by the order it appears in the string. Python begins counting from 0 so you have to be careful. You must also count spaces and punctuation too!

This means if we want to find the first letter of the word "Python" we would require the letter at index 0. If we require the last letter, or the 6th letter of Python, we would require the letter at index 5.

Page 11

An introduction to Python

Extracting a letter is known as subsetting which we will look at in more detail in the next section. You can also use negative indexes to count from the last letter to the first so that if we wanted the last letter we would use index -1.

It is important to note that strings are immutable meaning that they cannot be changed.

If we try to change a letter, "Python"[0]="p", we will obtain an error.

Subsetting Strings

We may wish to extract part of a string or a substring. Similar to the example above we can specify which characters we want using square brackets ([]) and a colon (:). Again remember indexing starts from 0 and when using [0:8] this specifies we want all characters from index 0 up to (but not including) 8. Here are some examples:

Page 12

An introduction to Python

We can use negative indexes to extract the last letters and we can also reverse a string using similar indexing. You will see more use for indexing and subsetting when we introduce lists in Chapter 11.

Other Useful String Functions

• upper()

Converts all letters in a string to upper case (capital letters).

• lower() Converts all letters in a string to lower case.

Page 13

An introduction to Python

• isupper()

Checks if a string is in all capitals.

• islower()

Checks if a string is in all lower case letters.

• capitalize()

Changes first letter of first word in string to a capital letter.

• split()

Splits a sentence into words.

• split(",")

Splits a sentence at the comma.

Page 14

An introduction to Python

• strip()

Removes white space from the start and the end of a string.

• join()

Join strings into one string.

• len()

Returns the number of characters in a string.

In some of these examples the string is split into a list or a list is joined into one string but we will look at lists in detail in Chapter 11 (these functions are here for reference).

Knowledge Point

4.1 Type the following phrase into Python and determine the length:

"I like Python"

4.2 What is the fourth letter?

4.3 How would you extract this letter?

4.4 Extract the word Python from the sentence.

Page 15

An introduction to Python

5 Variables

A variable is something which the user defines. It can be thought of as a container used to store information you may need later. It is realistically an allocated slot of computer memory for that piece of information. It consists of a name, a type and a value where the name is what you want to call the variable, the type relates to the type of data stored in it and the value is the data. A variable is simply defined using an equals sign (=) to assign a name to a piece of data.

Notice that we cannot just type Davidson. In that case Python would look for a variable called Davidson. Adding the quotes tells Python that this is a new piece of data that is of type string.

You can then apply functions to these variables. The following example will add the two strings (like in Section 4) with a space between them to output "Claire Davidson".

This can also be used for maths and is especially useful when learning algebra.

We tell Python that x is 3, y is 5 and ask what x plus y is, to which Python returns 8.

Page 16

An introduction to Python

Variable names can be only one word long but they can contain letters, numbers or an underscore(_). However, there are a few important rules:

• They cannot start with a number

• Names should not contain spaces

• They should not be the name as built in functions or variables (e.g. sum(), pi) as you will overwrite these functions.

• The names should generally be memorable and relevant so that you can use them efficiently throughout your code.

The names are case sensitive and so when you want to use your variable, be sure to use the correct format.

So why do we define variables?

Variables can be very useful when we want to reuse a piece of information later in our programme. It can reduce typing errors and make the programme more read-able by other individuals. The power of variables allows you to change one line of code (i.e. the value of your variable) and it will impact any code in the remainder of your program, which uses this variable. You will see how useful this can be for more complicated data types such as lists and vectors later and when programmes are more complex.

Variables are easily modified and will always take the most recent value within the code. The example below defines Apple to be 32 and adds 5 to update Apple to

37. This just overwrites our original value for Apple. The next step sets Apple to 7 which then overwrites this value of 37.

Page 17

An introduction to Python

Knowledge Point

5.1 Create a variable called radius equal to 5. Use this to find the area of a

circle with a radius of 5cm. (Area of a circle = r2 )

HINT: You have to import pi from the math package

5.2 Create three variables:

first_line = "Happy birthday to you"

third_line="Happy birthday dear friend"

comma=", "

Use these variables to write the Happy birthday song:

Happy Birthday to you, Happy Birthday to you, Happy Birthday dear friend, Happy Birthday to you

Page 18

An introduction to Python

6 Output - The print function

The print function is one of the most simple functions but very useful. At this stage when we are only writing short pieces of code we can check everything is working as expected easily and can print the values of variables simply by typing their names. This is not possible in other IDEs and when using text editors. As we begin to use more complicated code and functions, printing is very useful to ensure our code does what it should do! It allows us to view variables at any point in our program which is great for debugging. The use of the print function will become clearer when we learn about defining functions later.

You may want to print multiple values at one time which is easy in Python. There are various ways to do this, for example,

Python allows you to make great use of the + operator where you can not only add numbers, but you can add strings as seen in Chapter 4. We can also use this to combine strings and variables.

Page 19

An introduction to Python

However, if our variable contains data of any other type except a string, and we try to add this to another string, the + operator will throw an error when it tries to combine them.

To overcome this, we can use the str() function to convert the number to a string and then combine this using the + operator.

So, all the "pieces" added together should be the same data type.

Alternatively, Python 2 allows you to use %s and %d within a string to represent

strings or numbers respectively. You then tell Python which variable/values to insert

at these points after the string.

For example,

"Hello %s" % "world"

will create the string "Hello world". You can add multiple variables or values using brackets as shown in the example below. This syntax will unfortunately not work if using Python 3.

Page 20

An introduction to Python

Knowledge Point

6.1 Create a variable called Name and store your own name in it.

HINT: Remember to use quotes!

6.2 Check the data type of this variable.

6.3 Check the length of your name.

6.4 Create a variable Age with your current age stored in it and check its data type.

6.5 Print a sentence which says "My name is ... and on my next birthday I will be

... years old!", replacing the ... by using your variables.

Page 21

An introduction to Python

7 User input

You may create a programme which requires input from the user. For example, you could build a battleships game where the user must input their guesses for where the battleships lie. These inputs are then used to compare against values in the programme. An even simpler example could be that you create a small maths game which asks the user some math questions, calculates the answer and compares the user’s answer to the true answer.

We can use the function input() which takes a string that presents a question to the user.

It is also very useful to save the input to a variable for use in your programme as shown in the following example.

We are running Python 2 in a browser with trinket.io and it allows us to use input to accept data like Claire and it will recognise it as a string. However, some IDEs, like Jupyter note-books, expect data entered by the user to be in the correct data type. In the example below we obtain an error because Python will search for a saved object (such as a variable) defined as Claire. We have to specify that Claire is a string using the double quotes.

Page 22

An introduction to Python

In this case I recommend you use this function instead. It will interpret the input only when required.

If you want to use the input as a number, you can then convert it later in the problem using the int() and float() functions. Realistically, if we ask the user for a number, we would want to ensure the number they input is a number and send an error if not. We will touch on this later but in general you would use exception handling (see Chapter 13.4).

Knowledge Point

7.1 Write a few lines of code which asks the user what their name is and their age. Use these answers to print the sentence " Hello ..., on your next birthday you will be ... years old."

Page 23

An introduction to Python

8 Operators

In Python you can use operators to compare two pieces of data, some of which you may have seen from maths lessons. The examples below use numbers but you can also compare strings using operators where capital letters are considered less than lowercase letters ("H"<"h") and the first letter of each string is compared alphabetically ("apple"<"banana"). The table shows the operators, their use and an example for each. The result from operators is always a Boolean value, True or False. The statements, for example 2>3, are often referred to as conditions.

Operator Function Example Input Example Output

> Greater Than 2>3 FALSE < Less Than 3<5 TRUE >= Greater Than 3>=3 TRUE or Equal to <= Less Than 2<=5 TRUE or Equal to == Equal to 6==5 FALSE (Equivalent) != Not Equal to 5!=5 FALSE <> Not Equal 3<>6 TRUE

We can also combine multiple operators to check two conditions at once, which is often called chaining. The example below compares our variable x to see that it lies between 3 and 8. The result will be True.

Page 24

An introduction to Python

It is important to consider the diff erence between = and ==. The single equals sign should be read as "is set to" where you define a variable and set a value to that name. The double equals symbol should be read as "is equivalent to" where you check if two numbers/strings/variables are exactly the same. The example below shows the use of both symbols (notice strings are case sensitive).

There are logical operators which will also be very useful for coding in Python (especially when we cover conditional logic in Chapter 10).

1. and

This compares two conditions and it will only return True if both conditions are True. Consider the following examples:

Example a:

Example b:

Example :

Page 25

An introduction to Python

In example a, both conditions/statements are True and so the result is True. In example b only one of the conditions is True and so the and operator returns False. In example c both are False resulting in a False.

2. or This compares two conditions and if any one condition is True then it will return True. In other words at least one must be True to result in True.

Example a:

Example b:

Example c:

In this case, examples a and b both return True because at least one condition holds True. Example c remains False because both conditions are false.

3. not

This operator reverses the result of a condition, so if the condition is True, the not operator returns False and visa versa. It becomes useful when checking if values are in a list which we will see later. In the example below 5>3 yields True hence using not we obtain False.

Page 26

An introduction to Python

4. in This operator compares two objects to determine if one lies inside the other. You will see the vital use of this for lists later but for now it can be used for strings. You must be careful though as it matches characters not words.

In the first example we obtain True because "coffee" is clearly in the sentence, however we also obtain True for the second example, but why? The character string "tea" lies inside the word "instead" and so Python finds it inside our string. As it is character matching, it is also case sensitive. Therefore the operator ‘in’ is probably not best used for sentences. It could be used to check if a word contains a letter though (you may want to turn it to lower case using method lower() first).

5. not in As expected this checks if one object is not in another. The following example highlights that we must watch out for capital letters when comparing strings.

Page 27

An introduction to Python

We often combine multiple logical operators throughout our code. There is a hierarchy in how operators are calculated where the ‘and’ statement is checked before the ‘or’. To make sure you get the result you want, be sure to add parenthesis.

Knowledge Point

8.1 What do you think the answers to the following conditions are? Check answers using Python.

(a) 6>10 or 3==3

(b) 2<=3 and 2!=2

(c) not(16%4==0)

(d) "ate" in "I will be late"

8.2 Write three statements of your own using a range of operators where:

(a) At least one must be false and at least one must be true

(b) At least one should include one of the following logical operators: and, or, not, in.

Page 28

An introduction to Python

9 Defining Functions

Python comes with lots of pre-defined functions such as print which you can use without even thinking about. Packages also contain functions which can then be imported and used, for example, the sqrt function from the math package (see Section 1). Sometimes we want to create our own functions. Our good coding standards tell us that we shouldn’t duplicate code where possible, hence, if we want to repeat some code multiple times we should store this as a function. The general syntax for a function is shown below.

You must start with def statement followed by your function’s name with any inputs added in brackets. These inputs are often known as parameters or sometimes arguments. You can then carry out some transformations on those inputs and re- turn something new. As an example we could create a function which takes any two numbers, adds them together and returns the output.

In fact you have not told the function that it must be a number so it could take two strings.

Page 29

An introduction to Python

You will find functions very useful as you start to build more complex and iterative code!

There are a few very important concepts around functions to be aware of. Firstly, you have required and optional parameters. We could create a function that requires three numbers. It adds the first two numbers and then subtracts the third. In the example below our third variable x3 is optional. This is because we have assigned a default value to this variable. This means if the user sets a value for it, then Python will use that new value. However, if you do not specify x3 then the default value of 5 will be used.

Page 30

An introduction to Python

Secondly, variables created inside the function environment are not accessible from outside the function. The function environment is just any code, functions or variables written or calculated between the def and return statements of a function. We create a variable result1 during our calculations but as this is inside the function we cannot access this from outside the function environment. This is where printing can become useful! If you want to check intermediate calculations or values, you simple write a print statement inside the function environment and Python will print these values as it runs through the function code.

It is important to test your code and functions to ensure you obtain the output you expect. This can be done manually by adding in some values and ensuring you obtain the expected output, or else, by creating a test function. Testing is used to determine if there are errors in the users code. Often we hear the term unit testing which specifically tests one piece of code in isolation. Examples of errors were described in Chapter 1, however in the context of Python, two examples could be:

• Syntax errors are unintentional typing errors which result in Python being unable to understand a sequence of characters e.g. an extra period when using methods, "hello"..upper().

• Logical errors are created when the algorithm is not correct. An example of this is an index error where we may try to extract the last letter of a string is by using the length function e.g. my_string[len(my_string)]. This is due to Python indexing starting at zero and hence the index does not exist.

Page 31

An introduction to Python

Knowledge Point

9.1 Create a function called create_squiral which runs your squiral activity when you call it.

9.2 Create a function called upper_case which takes a string and returns all characters as capital letters.

9.3 Create a function which takes a number representing hours and returns the equivalent number of minutes.

9.4 Create a function which takes a number representing minutes and returns the value in hours. Print the number of full hours inside the function.

Check using minutes=90 and minutes=165.

HINT: To return the hours as a decimal you need to use floats.

Page 32

An introduction to Python

10 Conditional Logic

if

We can use if statements to only run code when a condition is met.

This example will check the variable total and if it is greater than 7 (i.e. condition is TRUE) then Python will run the indented lines and print Great. If total is less than or equal to 7, Python will stop and will not produce an output.

else

Else is commonly used in conjunction with if statements, but it can also be used with while or for statements which we will learn about in Chapter 12.

When using an if statement, code within the else statement will execute when the condition is false.

In this case we store the value 18 in our variable Age. The if statement checks if Age is less than 18 and since this is false it executes the code after the else statement. A simple example - if you open a tin of soup, you can take out the soup, else, you cannot remove the soup.

Page 33

An introduction to Python

elif

When we use if and else we can only have two possible outcomes (one if the condition holds and one if not). You will often want more than two possible outcomes. You could write multiple if statements but this requires Python to check every single one of those conditions.

In the example above, if we input monday, our Day variable meets the first if condition and so Python prints ":(" and the code stops. In the result above, Day is equal to saturday so Python will step through the conditions from the top and stop when it is met, in other words, at the second elif statement.

When using multiple conditions, it’s important to plan the order of these statements as you can actually make your code more complex than it needs to be. Compare the following example:

Consider grading a test. If their score is less than 60, they will fail. A score of 60 or over, will result in a pass with Grade D. A score of 70 or greater results in Grade C, 80 or greater is Grade B and 90 or greater is Grade A. Following this pattern we could write the following algorithm:

Page 34

An introduction to Python

This includes a lot of di erent comparisons at each stage. However, if we work

through the problem backwards,ff the code is much easier to read and requires less processing from Python.

An important thing to note here is that even though my score is in fact greater than 70 and 60, the condition score>=80 was met and hence our score is not compared to any of those conditions below. However compare this to the previous example. If we did not have the second condition, our elif statement would read elif score>=60: and since our score is greater than 60, we would see an incorrect Grade of D as Python would not continue to the following elif statement.

Page 35

An introduction to Python

Nested Conditionals

As problems become more complex, our code will also increase in complexity. Some-times nested conditionals are used where further conditions can only hold if the first condition is met. They generally help the readability of your code but you must ensure you maintain good coding standards such as indentations within your syntax.

As you can see in this example, Python first checks if the input age is over 18, if not, it will jump straight to the last else and would print "child". If the age is over 18, it will then test this age against the nested if condition. On larger more complex problems, this could save significant processing time and allows greater flexibility in your functions.

Page 36

An introduction to Python

Knowledge Point

10.1 Create a function which take two numbers as input and returns the diff erence between these two numbers.

10.2 Extend this function so that we only want non-negative answers, in other words, no matter what order you input the two numbers, Python will return the biggest minus the smallest.

10.3 Write a function which returns the statements: "positive integer", "zero" or "negative integer" where appropriate. Test this function using -10,10 and 0.

10.4 Extend this function by checking if the input is an integer. If not, return an error message, "That is not an integer". Test this with 3.4 and 3.

HINT: Consider the order of your conditional statements - a nested statement could also be used.

Page 37

An introduction to Python

11 Lists

We have already covered a few lists when we looked at strings but we have not yet defined these data types. A list is an object that contains multiple values in an ordered sequence. It is collection of items where items could be strings, integers, variables or even other lists. The elements in a list do not have to be the same data type however multiple data types can limit the functions that can be applied to the list. When you combine lists, conditional logic and loops (in the next chapter), you have all the tools required to write quite complex algorithms.

Creating Lists

To create a new list all values are defined within square brackets, separating each element with a comma. We often want to save it to a variable using the same syntax as was used for strings and numbers. We can create an empty list using simply [ ] or store this as a list named x using x=[ ].

When saving a list as a variable, we must not use the name "list" as this is a function in Python which converts a string (and other iterable objects) into a list.

Page 38

An introduction to Python

Another very useful function for creating a numerical list is range(). This becomes very useful for loops as we will see later.

In the first example above, we only specify one parameter which tells the range function where to stop. The range function will count integers starting from 0 up to but not including this stop value. In the second example we tell Python where to start (2), where to end (up to 12) and the steps between each (in this case 2). The step parameter can take negative values where you want to create a decreasing list as shown in the third example.

Basic functions such as printing can be applied as shown in the examples above or we could find the length of the list using len(listname).

Other useful functions mentioned for strings was in and not in. This is great for lists where we can check if elements lie inside a list or are missing from a list. We can compare our variable shopping_list from the start of this section.

Page 39

An introduction to Python

When using numerical lists, you may wish to use some of the following functions/methods:

• min(list) - find the minimum value of a list

• max(list) - find the maximum value of a list

• sum(list) - find the sum of all elements in the list

• list.index(item) - find the index for an item in the list. This finds the index of the first instance of that value in your list. (Note: If you wanted to find the indexes of all occurrences this would require more complex code.)

Subsetting Lists

We may want to extract only certain elements in a list and the syntax is the same as subsetting a string. Remember that Python indexing starts from 0. The lists used in these examples are from the start of Chapter 11.

Page 40

An introduction to Python

Updating Lists

Lists are mutable so we can change elements of them after definition. Changing elements of a list may not seem that useful yet however this becomes extremely useful when you start to build programmes. This example changes the second value "Bananas" (index=1) to "Pears".

We may also want to delete elements of a list using the del function. We must be careful as this then changes all the indexes of the following elements. In the example below we may have repeated the letter "c" three times and we want to remove the repetitions. The extra "c" elements are found at index 3 and 4 but after deleting the first "c" all the following elements move up by one. So you must be careful when deleting elements iteratively.

Page 41

An introduction to Python

An alternative way to remove elements from a list is to tell Python what the value of the element is you want to remove and use the method remove().

There are two functions to do add elements to a list. Append is used to add to the end of a list whereas insert is used to add elements at a specified index.

Page 42

An introduction to Python

It can also be useful to order a list either alphabetically or in numerical order. You could for example have a list of scores from a test and you want to list them from highest to lowest. There are two ways to sort a list.

Firstly, you can use the .sort() method as shown in the following example.

Since lists are mutable, the sort method overwrites your current list to an ordered list. You cannot convert this back to your original list. This is suitable in some cases, but if, for example, you enter the scores relative to your class list, then you will lose track of who received which score.

Page 43

An introduction to Python

An alternative is to use the sorted() function which will sort a list but you must store the result in a new variable if you want to re-use the sorted list. This means you could sort a list and use that to do some calculation, for example, find the median, but you will still have access to the original list and the order it was input in.

You can also sort a list in DESCENDING order. The default for parameter reverse is False and so would be in ASCENDING order unless otherwise specified.

Page 44

An introduction to Python

There is also the possibility to reverse a list. If you have a list of ascending numbers you may want to reverse this so they are descending. You can use the method

.reverse(), but this is similar to .sort() above where it replaces your original list. An alternative is to use a subsetting method as shown below.

Combining lists

Adding two or more lists creates one long list and it can be as simple as using the + operator between each list name. An alternative approach can be to use the extend() method however there is no real benefit to doing so.

Other similar data types

1. Tuples - A tuple is a sequence of immutable Python objects. Tuples are sequences but unlike lists, tuples cannot be changed. Tuples use parentheses,

Page 45

An introduction to Python

whereas lists use square brackets. An example could be ("Claire", 23) which is a tuple of two elements. You can add tuples to a list and then access elements in a similar way to lists. This is useful if we want to keep related objects together for example name and age of each person in the class.

2. Sets - Sets are lists with no duplicate entries. Sets can become useful when we want to find elements in more than one list or elements in one list that are not in another. It’s exactly the same idea as a set in mathematics where you may draw a Venn diagram to visualise where they overlap. It is also an easy way to find the unique elements in a list.

Knowledge Point

11.1 Split the sentence "I love to go to the beach" into words and find the length of the result. Does this make sense?

HINT: See Chapter 4

11.2 Write a function that takes a list and returns a new list with the first and last elements removed.

11.3 Write a function that takes a list and modifies it by removing the first and last elements but returns None.

Page 46

An introduction to Python

11.4 Write a function called is_sorted that takes a list and returns True if it is in ascending order and False otherwise.

11.5 Extend this function so that it returns True if the list is in ascending or descending order and returns False otherwise.

11.6 Create a function anagram which takes two strings and determines if they are anagrams of one another i.e. if they contain all the same letters (You may want to ignore the case of the strings that are input).

Page 47

An introduction to Python

12 Loops

If you want to carry out an operation many times iteratively, loops are essential.

There are two important types of loops: a for loop and a while loop.

For loops

For loops are used when we want to iterate lines of code for a set number of iterations or in other words, repeat code multiple times. This involves looping over a list which can contain numbers or strings.

In this first example we create a list and tell Python to loop over each item in that list. So Python will select "Apples", carry out all the code in the loop and then move to the next item, "Pears". It will continue to move along the list until there are no more items. The syntax is important; it begins with for x in y, where y is some list and x is a name used to specify a single item in that list. This means you create a variable x where the first item "Apples" is stored, then after one iteration, you update this variable to "Pears". Any lines of code that must be executed inside the loop should follow a colon (:) and be indented four spaces.

A useful function for loops is range (see Chapter 11). As a reminder, range(0,10,2) creates a list from 0 up to (but not including) 10 in steps of 2. In this second example we use this function and update a variable x in each iteration using the looping variable i. Note that since the print statement is not indented, Python knows that this is not part of the loop.

Page 48

An introduction to Python

While loops

A while loop continues carrying out some code until our condition fails. You must be careful because while loops can continue forever if the condition can never be broken. In the example below, we continually add 7 until the answer is over 20. So Python will check the value of x and if it is less than 20, it will complete another iteration.

The example below highlights where you can run into trouble with while loops. We

Page 49

An introduction to Python

tell python to subtract 5 while x is less than 20. However since x starts at 10 and is reducing it will always be less than 20! Hence, the code never ends. The user must interrupt python if this happens (use CTRL+C /CMD+C) so be careful when writing while loops.

When using an else statement with a while loop, the code after the else statement will only execute once the condition becomes false and the while loop has broken.

The while loop continues to increase x by 1 until x is two (x<2 is false), then Python executes the else statements.

Control Flow Statements

In Python, the statements break and continue help you to control the flow of your loops.

A break statement is used to tell Python to exit the entire loop once a condition is met.

Page 50

An introduction to Python

In this example, Python loops through each letter in your string. At each iteration, it tests if the letter is equal to "c". If it is not equal to "c", Python continues with the rest of the code (hence printing "a" and "b"). If the condition is met where the letter is equal to "c", the break statement tells Python to stop the entire loop. As you would expect, it breaks the loop. If you wanted a program to run until a criteria is met, you can either use a while loop with a condition, or in other cases it may be useful to use a forever while loop and break the loop once a criteria is met. To generate a loop that continues forever, we use:

The continue command is used to skip the succeeding code when a condition is met and move onto the next element in the sequence (iteration in the loop).

Again, Python loops through each letter of the string, but in this case when the condition that the letter is equal to "c" is met, Python just skips all the code below the continue statement and moves on to the next iteration, using the letter "d". Note: The following knowledge points are more challenging and include using many

Page 51

An introduction to Python

of the functions and concepts learnt across all the chapters.

Knowledge Point

12.1 Create a Python program which counts the number of even numbers and the number of odd numbers in a given list.

12.2 Create a function that takes a list of names and returns a list of those which do not contain the letter "a".

12.3 Design a game where the computer generates a random number between one and twenty and the user must guess this number. The game should respond to the input with "too high", "too low" or "well done" appropriately.

12.4 Extend this game so that you can guess forever until you get it correct

12.5 Change the game so you are allowed five guesses and keep track of the number of guesses the user requires to obtain the correct answer. If they still are wrong, stop the game and tell them the correct answer.

Page 52

An introduction to Python

13 Additional Topics

13.1 Vectors/Matrices

Vectors and matrices can be created in Python by using the array function from the numpy package. This allows you to add, subtract and multiply vectors, calculate the dot product and cross product and carry out matrix multiplication. A few examples of using Python for vector calculations are shown below:

Page 53

An introduction to Python

Similarly, we can use python for matrix calculations and a few examples are:

13.2 Dictionaries

We have already seen how Python uses lists and vectors to store information and a dictionary is another way to store data. Dictionaries in Python store everything in key-value pairs where the key is usually a string representing a name for the object stored as the associated value. A value can be a number, a string, a Boolean value, a list and even another dictionary. To understand this, we could think of an actual oxford dictionary. We look up the words in the dictionary to find their definitions. The keys are the words and the values are the related definitions. Dictionaries are specified using curly brackets so an empty dictionary would be {}. The key-value pairs are separated by commas and colons are used to define each pair e.g. {key1:value1, key2:value2}.

Page 54

An introduction to Python

In the following example we have three keys (Name, Age and Hobbies) and their three associated values. It is important to know that dictionaries cannot have a specific order and hence no indices. Therefore, we cannot use the same sub-setting techniques used for lists. They are just a collection of unordered key-value pairs. So we use our keys to extract the associated values. Notice that if the dictionary contains a list we can then use list indices in separate succeeding square brackets. If you specify a key which is not defined then you will obtain an error.

Dictionary Functions

• .keys()

Returns a list of the keys in a dictionary.

• .values()

Returns a list of the values in a dictionary.

• del dict["key"]

Deletes the specified key-value pair from dictionary

Page 55

An introduction to Python

• dict["newkey"]=value

Adds a new key to the dictionary or if key is already defined, replaces the value for that key.

• dict1.update(dict2)

This is a useful way to combine two dictionaries. Any new keys in dict2 that are not in dict1 will extend dict1. Any keys already present in dict1 will be updated with the values from dict2.

13.3 Visualisation

Python has various packages to help you create really e ective graphs. Starting with

more basic plots such as line graphs and bar chats, you canff use matplotlib.

There are plenty of resources online to outline how to create visualisations but a basic plt.plot(list1,list2) will plot elements of list1 on the x-axis against the elements of list2 on the y-axis. A simple example is shown below:

Page 56

An introduction to Python

13.4 Exception Handling

In Chapter 10 (Knowledge point 10.4), we created a function that checks if a number is an integer and then determines if it is positive, negative or equal to zero.

Page 57

An introduction to Python

If we ask the user in input a value using input, this will automatically be stored as a string. Hence our function will always fail.

If we try to convert a number entered to a string we may bump into some problems:

Page 58

An introduction to Python

Python cannot convert our input into an integer. To overcome this problem we can use a simple exception handling technique. We tell Python to convert the input to an integer if it can, then if an error is produced, we can tell Python an alternative line of code to use (usually output a simple error message to the user).

Page 59

An introduction to Python

14 Free Online Resources

Some additional resources (as of January 2018) can be found at:

https://docs:python.org/2:7/

http://inventwithpython.com/chapters/

http://thinkpython.com

https://automatetheboringstuff.com

http://inventwithpython.com/pygame/chapters/

http://anandology.com/pythonpracticebook/index.html

https://www.learnpython.org/en/Welcome

Page 60