Introduction to Python

Exercises 1: Getting Started with Python

Preliminaries

Please read part 1 of the notes before attempting these exercises.

PLEASE NOTE: be warned!

Indentation is very important in Python (as we will soon see throughout the tutorial). If you precede your expression with even one stray space character, the Python shell will complain of an Indentation Error and refuse to execute your code.

Arithmetic

Begin by entering some arithmetic expressions, after the print statements, using the basic arithmetic operators: + (plus), - (minus), * (multiply), / (divide). Try using different mixtures of the arithmetic operators, with and without brackets to fix the scope of operations. For cases without brackets, see if you correctly anticipate the operator scopes that Python assumes. Try expressions that mix float and integer types. A particular case to be careful of is integer division, where both numbers are integers, e.g. try entering 2/3 - what result do you get and why? This behaviour is a common source of errors in people's code.

In [1]:
#Insert a series of arithmetic expressions after each statement to test everything that is required above

print(5+5+5+5)
print((55-44)*28)
print(68/24)
print(2/3)
20
308
2.8333333333333335
0.6666666666666666

Using variables

Run the following cell to see how Python handles value assignment. We use "=" to assign a value to a variable (whose name appears to the left of =). Elsewhere, when a variable is evaluated (e.g. when it appears in an arithmetic expression), its value is accessed and used at that position.

Most of the time, it is better to use meaningful names for variables, rather than simple names such as x. For example, we might use a variable named balance to store our bank balance as a foating point number, or a variable message to store a string that is to be printed as a message. Using meaningful variable names makes your code much more readable and understandable, and is a key feature of good programming style. It not only helps someone else to understand your code (e.g. me, if I'm marking it), it also helps you understand your own code, which is vital if you're trying to figure out why it doesn't work, or does something that you're not expecting. Note that variable names can contain letters, digits and underscores (i.e. _), but must begin with a letter. Note also that there are some special words, Python's keywords, that cannot be used as variable names.

In [2]:
x = 12.5
print(x)

y = 3 * x + 2
print(y)

x = x + 1.1

print(x)
12.5
39.5
13.6

Strings

As it is mentioned above, strings are just character sequences between paired quotation marks. Python doesn't mind if you use " or ' for this, as long as you have the same quotation mark at both the start and end of the string. Some of the arithmetic operators, specifically + and *, have additional special meanings when used with strings. Below you have two strings, s1 and s2. We can evaluate expressions such as s1 + s2 and s1 * 10. Investigate the effects of these operations below. Also, investigate precedence for these operators, e.g. by entering: s1 + s2 * 10.

In [3]:
s1 = "Hello "
s2 = "World "

#Insert each expression in bold from above after a print statement

print(s1 + s2)

print(s1*10)

print(s1 + s2*10)
Hello World 
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello 
Hello World World World World World World World World World World 

Simple printing

Try entering some simple print commands. The print command will print a single value, or multiple values that are separated by commas (when it adds a single space between each value printed). By default, print also adds a newline character at the end of what it prints. You can prevent Python from adding a newline at the end of what it prints by adding end='' to the end of the print statement, for example print("hello", end=''). You won't be able to see the difference when entering print commands to the interpreter, but the difference matters when you have multiple print statements in a code file. Note that you can add extra linebreaks to what's printed by using the special character \n, for example try printing the string "hello\n\nthere".

In [4]:
# Insert different commands to be printed after each statement
# Try to experiment with the commands and follow the instructions from above

print("hello",5+5)

print("hello\n\nthere")

print("hello",end="")

print("\n",5+5+5,"\n")
hello 10
hello

there
hello
 15 

First Python program

The first line (preceded by #) is a comment and it is ignored by Python. The remaining lines are commands that we might have entered at the Python shell. If we call python to run this program (or script), it will execute each line in turn, producing results just as if they had been entered at the shell. Take a short while to study the code, and understand what it does.

Clearly, the code takes an initial distance in miles (i.e. the value assigned to the variables miles) and converts it to kilometers, on the basis that a kilometer is five eighths of a mile. The initial and converted distances are then printed, with some 'supporting text'. Now run the cell to compile the script.

In [5]:
# Converts distance in miles to kilometers
miles = 22.7
kilometers = (miles * 8.0) / 5.0
print("Converting distance in miles to kilometers:")
print("Distance in miles: ", miles)
print("Distance in kilometers:", kilometers)
Converting distance in miles to kilometers:
Distance in miles:  22.7
Distance in kilometers: 36.32

Taking input from the user

As it stands, we can only do other distance conversions by editing the script file, so that different initial values are assigned to the miles variable.

Python provides the input function for reading what a user types in whilst a program is running. As shown below, this takes a single (optional) argument, which is a string. When called, the function prints this string as a 'prompt', and then reads in whatever text the user types up to the first line return. It expects to find something that look like a single Python type, such as integer or float, in which case it creates this value and returns it.

In [6]:
#Input example

t = input('Introduce a sentence here.')
print(t)
Introduce a sentence here.hi
hi

Modifying the first Python program

To avoid having to edit the function for each different calculation, we could instead use the input function to read in the start value for the calculation. Copy the distance conversion algorithm from above into the next cell and modify it so that the user can enter itself a value to be converted.

In [8]:
#Insert the distance conversion algorithm here and modify so as the user can enter a value every time the function is run

miles = int(raw_input('Enter number of miles here.'))
kilometers = (miles * 8.0) / 5.0
print("Converting distance in miles to kilometers:")
print("Distance in miles: ", miles)
print("Distance in kilometers:", kilometers)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-dd6bc44d616e> in <module>()
      1 #Insert the distance conversion algorithm here and modify so as the user can enter a value every time the function is run
      2 
----> 3 miles = int(raw_input('Enter number of miles here.'))
      4 kilometers = (miles * 8.0) / 5.0
      5 print("Converting distance in miles to kilometers:")

NameError: name 'raw_input' is not defined

Writing our first Python program

Using the distance converter script as a template, write in the marked cell bellow a new script for converting temperatures. Your script should do the following. Firstly, it should ask the user for a temperature in degrees celsius (a.k.a. centigrade). Next, it should compute the corresponding temperature values on both the fahrenheit and kelvin scales. It should then print a summary of its results, similar to that of the distance converter program.

As you probably know, to convert a celsius temperature to the fahrenheit scale, we multiply it by 9/5 and then add 32. The kelvin scale has the same sized units as the celsius scale, but its zero point corresponds to absolute zero, which is equivalent to -273,15 °C, so converting from celsius to kelvin requires only that we add 273.15.

In [ ]:
# Insert your first Python program here

celcius = input('Enter degrees celcius here.')
fahrenheit = (celcius * (9/5)) + 32
kelvin = celcius + 273.15
print("Fahrenheit: ", fahrenheit)
print("Kelvin:", kelvin)

Defining a Python Function: reusable functionality

A good way of creating conveniently reusable chunks of functionality is to define a function. Converting the code of the distance conversion to have the form of a Python function might give the following function, as it is in the next cell.

Here, the first line starts with the keyword def, indicating a function definition. What follows the keyword indicates that the function has name convert_distance and takes a single argument. When the function is called, the argument value provided is assigned to the variable miles (indicated in the brackets of the definition's first line). Note how the body of the definition is indented relative to the first line (which is not indented). This indentation is crucial because it signals that the indented lines belong to the body of the definition.

PLEASE NOTE: be warned! - getting indentation right is crucial to successful Python programming. You should create indentation by using the TAB key. You should never attempt to indent code 'manually' by using spaces. If you run this code, the interpreter will actually just read and remember the function definitions. We can then call the function as follows, i.e. using the function's name with the required argument value supplied in brackets.

In [ ]:
def convert_distance(miles):
        kilometers = (miles * 8.0) / 5.0
        print("Converting distance in miles to kilometers:")
        print("Distance in miles: ", miles)
        print("Distance in kilometers:", kilometers)
        
convert_distance(44)

convert_distance(125.5)

Making your function return its values

A common mistake when learning Python is to confuse printing a value with returning the value. See below about the use of return. Modify your convert_distance function so that it returns the value it computes, i.e. so you can assign the value to a variable.

In [ ]:
def next_number(x):
    return x+1

x = 5
y = next_number(x)

print(x, y)
In [ ]:
# Insert here your modifie
def convert_distance(miles):
        kilometers = (miles * 8.0) / 5.0
        print("Converting distance in miles to kilometers:")
        print("Distance in miles: ", miles)
        print("Distance in kilometers:", kilometers)
        return kilometers
convert_distance(44)

convert_distance(125.5)

How to import your code

The usual way to access pre-existing code, either written by yourself, or code in library module, is to import it (i.e. as opposed to simply 'running' the code, as we did above, which doesn't usually make sense). For example, there is a module math providing many goodies, such as (e.g. a variable pi defined with quite an accurate value of π. If we import this module with the statement import math, we would need to refer to this variable with the 'long name' math.pi.

The alternative import statement from math import * brings everything (*) in with a 'local name', i.e. so we could refer to the variable as just pi. This saves on typing but is considered bad practice. See http://www.walkingrandomly.com/?p=6209 for a discussion.

In [ ]:
#Insert here your code for the temperature conversion function

def convert_temperature(celcius):
    fahrenheit = (celcius * (9/5)) + 32
    kelvin = celcius + 273.15
    print("Fahrenheit: ", fahrenheit)
    print("Kelvin:", kelvin)
    return fahrenheit,kelvin
In [ ]:
#Add a series of test calls of your defined function to see how it works

x = convert_temperature(100)
print x