2. Python 101

Welcome to Python!

Python is a simple programming language with straightforward syntax. It’s open source, freely available, and very widely-used. It’s also relatively easy to learn, so it’s a great place to start to learn programming.

To begin, we’ll look at the main types of data used in Python.

2.1. Strings

Strings are sequences of characters such as letters and numbers. An example of the string data type is text.

Try typing the commands following the >>> symbols into the interpreter window. Be careful to type it exactly, or you might get an error.

>>> print 'Hello world!'
Hello world!

>>> print "I can get Python to print anything I type"
I can get Python to print anything I type

>>> print 'Even numbers like 6 and symbols like #'
Even numbers like 6 and symbols like #

With these simple commands, we’ve instructed Python to print the text we’ve given it to the screen. By putting those characters inside quotation marks (‘’, or “”), we’ve told Python that this data is a the string type.

We can also run the print command as a script using a text editor. Here Python will execute commands in order from top to bottom. In your text editor, type:

print 'Hello world!'
print 'Goodbye world!'

… and save the file as `my_first_script.py`. To execute this script, in the interpreter window type run my_first_scripy.py.

>>> run my_first_script.py
'Hello world!'
'Goodbye world!

If you manage to replicate this output, congratulations! You’ve just written your first program in Python.

But what if we want to include a ‘ or ” symbol in our string? If we aren’t careful, Python will think that we want to end the string. The first option is to enclose single quotation marks within double quotation marks (or double quotation marks within single quotation marks):

>>> print "I can even get Python to print a ' symbol."
I can even get Python to print a ' symbol.

>>> print '...and a " symbol'
...and a " symbol.

Alternatively, we can use the escape character (\) as follows:

>>> print 'I can also get Python to print a \' symbol using the escape character.'
I can get Python to print a ' symbol using the escape character

>>> print 'And even a \\ symbol.'
And even a \ symbol.

2.1.1. Exercise: Write a story

Now it’s your turn to write a Python script.

  • Write a Python script in the script window that tells a short story. Save it as story.py, and run it in the interpreter window.

Here’s an example that I wrote in a text editor:

print 'A little girl goes into a pet shop and asks for a wabbit. The shop keeper looks down at her, smiles and says:'
print '"Would you like a lovely fluffy little white rabbit, or a cutesy wootesly little brown rabbit?"'
print '"Actually", says the little girl, "I don\'t think my python would notice."'

…and ran using the interpreter:

>>> run story.py
A little girl goes into a pet shop and asks for a wabbit. The shop keeper looks down at her, smiles and says:
"Would you like a lovely fluffy little white rabbit, or a cutesy wootesly little brown rabbit?"
"Actually", says the little girl, "I don't think my python would notice."

2.1.2. An aside: comments

Comments are important aspects of programs. Comments are used to describe what your program does in readable language, or to temporarily remove lines from a program.

# This is a comment. When executing this program, Python will ignore this line.
# Anything that comes after the # character is ignored.
print 'This text will be printed' # But not this text
# Comments are often used to disable lines in a program
print 'I want this line to be executed'
# print 'I do not want this line to be executed right now'
>>> run code.py
This text will be printed
I want this line to be executed

I will now use comments to describe the code I give you. Adding comments to your code is good practice as it makes your code easier for other people to use, and helps you to remember how your own code works. Get used to adding comments to the scripts you write.

2.2. Numerical data

2.2.1. Integers

An integer is a whole number. Examples of integers are 1, 3, and 10.

We can use Python like a calculator to perform arithmetic on integers. Try the following:

>>> 1 + 2 # Addition
3

>>> 1 - 2 # Subtraction
-1

>>> 3 * 4 # Multiplication
12

>>> 5/2 # Division
2

The last of these examples is interesting. Why do you think the answer to 5 divided by 2 isn’t 2.5?

2.2.2. Floating point numbers

Unlike integers, floating point numbers (floats) have a decimal point. A float can be specified by including a decimal point (e.g. 1.0 or 1.).

We can apply all the same operators to floats as integers, but they will sometimes behave differently. Try these examples:

 >>> 3.5 + 1.2
 4.7

 >>> 8.2/2.3
 3.5652173913043477

 >>> float(1) # We can convert from integers and floats
 1.0

 >>> int(1.0) # ...and from floats to integers
 1

 >>> 3/4.5 # An integer interacting with a float results in a float
 0.6666666666666666

 >>> 'Hello ' + 'World!' # We can also add strings together
'Hello World!'

 >>> '1' + 1.0 # ... but trying to add a string to a float results in an error. Why is this?
 ---------------------------------------------------------------------------
 TypeError                                 Traceback (most recent call last)
 <ipython-input-1-be0d736a4237> in <module>()
 ----> 1 '1' + 1.0

 TypeError: cannot concatenate 'str' and 'float' objects

2.2.3. An important detour: Variables

In programming, variables are names that we give for something. They ensure that code is readable, and offer a means of ‘saving’ a value for later use. We assign a value to a variable using the = character, with the variable name on the left and it’s value on the right. Try these examples of how variables work:

>>> x = 1 # Define a variable named x

>>> x
1

>>> y = 1 + 2 # Define a variable named y

>>> y
3

>>> x + y # Operators and logical tests work identically with variables
4

>>> var1, var2, var3 = 1, 'two', 3.0 # Multiple variables can be defined at once

>>> print var1, var2, var3
1 two 3.0

Now you the basics of how variables work, you can start to write simple scripts that perform calculations for you. Write out the following program, and save it as miles_to_km.py.

# Prompt the user to input a distance in miles and save it to a variable named distance_miles
distance_miles = input('Input a distance in miles: ')

# Convert distance_miles to a float
distance_miles = float(distance_miles)

# Convert the distance to kilometers, and save it to distance_km
distance_km = distance_miles * 1.61

# Convert distance_km to a string
distance_km = str(distance_km)

# Finally, print the distance in kilometers
print 'That is a distance of ' + distance_km + ' kilometers'

… and run it in the interpreter window:

>>> run miles_to_km.py
Input a distance in miles: 5
That is a distance of 8.05 kilometers

Can you make the code run? Note: There are three functions in this script (input(), float(), and str()), which convert between data types. Make sure you understand what each line does.

2.2.4. Exercises

  1. Use the +, -, *, and - operators to compute the following:
    • 123456 plus 654321
    • 123456 minus 654321
    • 123456 multiplied by 654321
    • 123456 divided by 654321
  2. Can you work out what the following operators do? HINT: You can access help documentation in python with a command like help('+').
    • %
    • <
    • >
    • **
  3. The basal area of a tree (BA) can be calculated using the equation:
    • BA = π(DBH/2)^2
…where DBH is the tree diameter at breast height and π = 3.14. Write a Python script to calculate the basal area of a tree from its diameter at breast height.

2.3. Boolean data

Boolean data can take two values; True or False (also denoted as 1 or 0). The boolean data type is most commonly associated with logical expressions. The main logical expressions we use in programming are as follows:

>>> # An equivalence statement tests whether two arguments have the same value.

>>> True == True
True

>>> True == False
False

>>> False == False
True

>>> # A negation statement tests is the opposite of an equivalence statement.

>>> True != True
False

>>> True != False
True

>>> False != False
False

>>> # The 'and' statement (conjunction) returns True where both arguments are True.

>>> True and True
True

>>> True and False
False

>>> False and False
False

>>> # The 'or' statement (disjunction) returns True where either of the arguments is True.

>>> True or True
True

>>> True or False
True

>>> False or False
False

Boolean logic may be quite different from anything you’ve learned before, so make sure you understand these statements before going any further.

Logical statements can involve other data types, and also be combined:

>>> 1 + 1 == 2
True

>>> 'one' == 'two'
False

>>> x = True

>>> y = False

>>> x and y
False

>>> (False or True) and (False and True) # Can you work out what's happening here?
False

2.3.1. Exercise: logical expressions

Try and predict the outcome of the following boolean expressions. Input them into Python to see how you did.

  1. True and True
  2. False and True
  3. True or False
  4. False or True
  5. 'this_string' == 'this_string'
  6. 'this_string' == 'that_string'
  7. 'this_string' != 'that_string'
  8. 1 == 1
  9. 1 == 1 and 1 == 0
  10. 1 == 1 or 1 == 0
  11. 1 == 1 and 1 != 0
  12. 10 > 5 and 5 < 0
  13. True and 3 == 4
  14. 1 + 2 != 3
  15. (True and False) == (1 and 0)
  16. (True or False) and ('this_string' == 'this_' + 'string')

2.4. Groups of things

Frequently we will want to group multiple values together in a single variable. The main mechanisms for doing this in Python are tuples, lists and dictionaries. As our time is limited, we’ll only look at lists (and later arrays), but you should be aware that other ways of grouping data exist.

2.4.1. Creating Lists

Lists are a group of ordered elements. They are created as follows:

>>> my_list = [2, 4, 6, 8] # Use square brackets to define a list, separating elements using commas

>>> my_list
[2, 4, 6, 8]

>>> my_list.append(10) # Add a new element to the end of a list

>>> my_list
[2, 4, 6, 8, 10]

>>> my_list.append('dog') # Lists can contain multiple different types of data

>>> my_list
[2, 4, 6, 8, 10, 'dog']

>>> my_list.append([2.0, 3.0, 'cat']) # They can even contain other lists (a 'nested' list)

>>> my_list
[2, 4, 6, 8, 10, 'dog', [2.0, 3.0, 'cat']]

2.4.2. Exercises

  1. Try to create your own list containing the letters ‘A’ to ‘F’
  2. Append the letter ‘G’ to the end of your list
  3. What happens when you add (+) two lists together?

2.4.3. Indexing Lists

We can access individual elements of a list using indexing. We do this using square brackets and specifying the numeric location of the elements we want to access.

Note

In Python (and most other programming languages), we start counting from 0. So the first element of a list is 0, the second element is 1, the third element is 2 etc.

Here are some examples of how we index lists:

>>> zoo = ['Tiger', 'Parrot', 'Bear', 'Sloth', 'Giraffe'] # A list of animals in a zoo

>>> zoo[0] # Get the first element of the list
'Tiger'

>>> zoo[3] # Get the fourth element of the list
'Sloth'

Using negative numbers, we can access elements from the end of a list:

>>> zoo[-1] # Get the last element of the list
'Giraffe'

>>> zoo[-2] # Get the second to last element of the list
'Sloth'

2.4.4. Slicing Lists

We can also select multiple elements of a list (‘slicing’), as follows:

>>> zoo = ['Tiger', 'Parrot', 'Bear', 'Sloth', 'Giraffe']

>>> zoo[1:4] # Get the second to fourth elements from the list
['Parrot', 'Bear', 'Sloth']

>>> zoo[:2] # Get the first two elements of the list
['Tiger', 'Parrot']

>>> zoo[3:] # Get all elements from the fourth onwards
['Sloth', 'Giraffe']

>>> zoo[::2] # Get every second element
['Tiger', 'Bear', 'Giraffe']

>>> zoo[::-1] # Reverse the list
['Giraffe', 'Sloth', 'Bear', 'Parrot', 'Tiger']

>>> # We can apply these same methods to strings

>>> animal = 'Lion'

>>> animal[0]
'L'

>>> animal[1:]
'ion'

2.4.5. List functions

We can determine various properties of list contents using the following functions:

>>> my_list = [2, 4, 6, 8, 10]

>>> min(my_list) # Returns the minimum value of a list
2

>>> max(my_list) # Returns the maximum value of a list
10

>>> len(my_list) # Returns the number of elements (length) of the list
5

2.4.6. Exercises:

  1. Write a program that takes a list as input, reverses it, and prints the output.
  2. Write a script that prints the highest and lowest values in a list

2.5. Flow control

Now you know the basics of data types, we can begin to make some complex programs. To do this we need to learn how to control the flow of a program.

2.5.1. The if statement

An if statement looks at whether a boolean statement is True, then runs the code under it. If the boolean statement is False, the code is skipped.

Have a look at these two if statements:

>>> cats = 10 # Declare a variable called cats

>>> if cats > 8: #A boolean statement
...:    print 'We have too many cats!' #New block executed where the boolean statement == True
...:
We have too many cats!

>>> if cats < 3:
...:   print 'We need more cats!'
...:

>>>

In the first, the boolean statement was True, so Python executed the indented block of code. In the second, the boolean statement was False, so Python did not execute the indented block of code.

We can combine multiple boolean tests in a single if statement by adding elif (‘else if’) and else statements. To see how this works, write out this program in the script editor, and save it as cats.py:

cats = 5

if cats > 8:
    print 'We have too many cats!' # This is a new block. It's indented by 4 spaces.
elif cats < 3:
    print 'We need more cats!'
else:
    print 'We have the right number of cats :)'

…and run it in the interpreter window:

>>> run cats.py
'We have the right number of cats :)'

Try setting cats to equal 2 or 10. Do you understand what is happening here?

2.5.2. Exercise

  • Can you write an if statement that tests whether a string begins with the letter ‘m’?

2.5.3. The for loop

The for .. in statement is a looping statement which iterates over a sequence (e.g. a list). This allows you to perform an operation on each item in the list in turn.

Try these out for yourself to get a feel for how lists work:

>>> rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

>>> for colour in rainbow: # Note the colon
...:    print colour
...:
red
orange
yellow
green
blue
indigo
violet

>>> for i in range(6): # For each integer from 0 to 5...
...:    print i
...:
0
1
2
3
4
5

Everything that is indented will be executed for each item in the list. for loops are very useful for bulk-processing data. For example, by providing a list of filenames we could process a stack of satellite images one at a time.

2.5.4. Exercises

  1. Look at how we used range in the last example. What does range do?
  2. use a for loop to print the integers 1 - 10
  3. Use a for loop to print ‘Hello World!’ 10 times
  4. Write a script to add the integers 1 - 100, and display the total.
  5. Write a for loop that iterates from 0 to 20. For each iteration, check if the current number is even or odd, and print that to the screen. HINT: Remember the % operator?

2.5.5. The while statement

A while loop is similar to a for loop, but will keep executing code so long as a boolean expression is True. Unlike a for loop which will stop when it gets to the end of a list, a while loop can continue indefinitely.

>>> count = 0 # Set a variable named 'count' to 0

>>> while count < 5: # As long as count is below 5...
...:    count = count + 1 # ...add 1 to count...
...:    print count # ...and print the value of count
...:
1`
2
3
4
5

2.5.6. Exercises

  1. Predict what the following script will do. Try and run it, if you dare…
i = 0

while True:
    i = i + 1
    print i
  1. Can you repair the script to stop iterating when i reaches 10000?

2.5.7. Combining conditional statements

Consider the following program, which is a number guessing game:

number = 50

your_guess = input('Enter an integer : ') # Input an integer

if your_guess == number:
    # This is a new block. It is indented by 4 spaces.
    print 'Well done, you correctly guessed the number!'

elif your_guess < number:
    # This block will be executed where the guess is lower than the correct number
    print 'Wrong! The correct number is higher than that.'

else:
    # This block will be executed where neither of the two conditions above are reached.
    print 'Wrong! The correct number is lower than that.'

print 'Done' # This final statement is always executed

Save it as if_game.py, and try and play it:

>>> run if_game.py
Enter an integer : 20
Wrong! The correct number is higher than that.
Done

>> run if_game.py
Enter an integer : 60
Wrong! The correct number is lower than that.
Done

>> run if_game.py
Enter an integer : 50
Well done, you correctly guessed the number!
Done

It works, but we can include a while statement to improve this game. Be very careful with indentation of the blocks, as the if statement is nested inside the while statement so some blocks are indented by 8 spaces.

number = 50
run_code = True

while run_code:

    # This is a new block. It is indented by 4 spaces.
    your_guess = input('Enter an integer : ') # Input an integer

    if your_guess == number:
        # This is another new block. It is indented by 8 spaces.
        print 'Well done, you correctly guessed the number!'
        run_code = False # This will exit the while statement

    elif your_guess < number:
        # This block will be executed where the guess is lower than the correct number
        print 'Wrong! The correct number is higher than that'

    else:
        # This block will be executed where neither of the two conditions above are reached.
        print 'Wrong! The correct number is lower than that'

print 'Done' # This final statement is always executed

Save it as while_game.py, and try and play it:

>>> run while_game.py
Enter an integer : 20
Wrong! The correct number is higher than that
Enter an integer : 60
Wrong! The correct number is lower than that
Enter an integer : 50
Well done, you correctly guessed the number!
Done

2.5.8. Exercise

  1. Can you modify the number guessing game to limit the number of guesses allowed to 10?
  2. Search the internet to work out how to generate a random integer between 1 and 100. Can you modify the game to randomly generate a new integer each time it is run?

2.6. Functions

You’ve already used several functions in python. Examples are len, max, and input. These in-built functions are useful, but sometimes you want a function that can perform a more specific operation. With Python, you can create your own functions, which you can re-use multiple times in a script.

Here’s an example of a very simple function, which we will name hello:

>>> def hello():
...:     print 'Hello!'
...:

>>> hello()
'Hello!'

>>> hello()
'Hello!'

This simple function had no inputs or output variables. Here’s a more complex function that converts distance from miles to kilometers. This function will have one input (distance_miles) and one output (distance_km).

>>> def miles_to_km(distance_miles):
...:    distance_km = distance_miles * 1.61 # Convert miles to kilometers
...:    return distance_km # And return the distance in kilometers

>>> distance_km = miles_to_km(5)

>>> distance_km
8.05

You will recall we wrote a complete script to do this earlier. Now that it is contained within a function, we can easily repeat the calculation multiple times:

>>> miles_to_km(1)
1.61

>>> miles_to_km(200)
322.0

We won’t look any further into functions as part of this tutorial, but you should be aware that they exist, and that the more complex your programs get the more essential they become to keeping your scripts tidy.

2.6.1. Exercise:

  1. Write a function to convert temperature from fahrenheit to celcius. The equation to convert from °F to °C is:

    • [°C] = ([°F] − 32) * 5⁄9