This notebook will walk you through some very simple python code. You'll learn to work with strings and basic aritmetic, and how to change what code is executed based on simple conditions.
It's important that you use this notebook interactively. Read the text and then read the code cells. Think about what you expect the code to do. Then run the cell (by pressing shift and enter) to find out. Then change the inputs to the functions in that cell and run it again to check you understand what the function is for and that it behaves in the way you expect.
The classic first program is Hello World, a program to output a string. A string is just a sequence of letters and other characters. In python we use quote marks (') to indicate where a string begins and ends. Run the cell below.
Then try changing the text to make it output something different and run the cell again.
You can use double quotes(") instead of single quotes (') and it will work exactly the same - try replacing 'Hello World!' with "Hello World!" What happens if you don't use quote marks at all?
print('Hello World!')
When you run the next cell it will cause an error. That's because the backslash character \ has another purpose in python strings. If you want to print \ you have to write \\ - try replacing 'Hello World\' with 'Hello World\\' and run the cell again.
print('Hello World\')
The backslash is used to help write special characters. For example, quote marks or tabs or newlines. Look up 'python escape characters' online to learn more, and run the cell below to see some more examples.
print('Hello \n World!')
print('Hello\b World!')
print('Hello\tWorld!')
print('Hello \100 World!')
Reading code is hard. It is very important to make notes as you go along to explain what your code is meant to achieve. For example, in the previous cell we used some special characters. To make that code easier to understand we can add comments that explain those characters. Python uses the hash character # to indicate comments. Any line starting with # is ignored by the python interpreter. Even if the rest of the line contains valid python code, it won't actually do anything if the first character is #.
# \b is backspace character - expect output Hell World!
print('Hello\b World!')
# \100 special character to print 'at' symbol
print('Hello \100 World!')
# next line does nothing
# print('Hello World')
You can give multiple inputs to the print function, as well as specifying how they should be separated and an ending. The separator is set to a space by default.
print('Hello', 'and goodbye', sep=', ', end='!')
You can use the print function to output to a file, although it's not the most common way to do this in python. Run the next cell and you will see a file called 'output.txt' appear in the same directory as this notebook.
print('Hello World!', file=open('output.txt', 'w'))
The cell below shows a couple of different ways to use variables in the print function. Change the values of the variables and re-run the cell to see how the output changes.
myName = 'Fred'
myEyeColor = 'blue'
myAge = 22
print('Hi', myName, 'I like your', myEyeColor, 'eyes', end='.\n')
print('%s is %d years old.'% (myName, myAge))
print('{} has {} eyes.'.format(myName, myEyeColor))
print('{name} has {color} eyes. I like the color {color}.'.format(name=myName, color=myEyeColor))
The format()
function is very flexible.
For example, we can specify the width of a field or how the value within that field should be aligned; for floating point numbers we can specify the precision to which those numbers are displayed.
Here is an example for creating space in the output.
The ':' character indicates the start of the extra specifications.
'<' indicates that the value in this field should be left aligned, '^' that it should be centered, '>' that it is right aligned.
The number indicates the (minimum) width of the field.
print('|{:<10} | {:^10} | {:>10}|'.format('Left', 'Center', 'Right'))
There's lots more you can do with strings other than just printing them out...
You can find more in the documentation, and there are examples of some of the most useful (in my opinion) below.
In all cases you should try these functions on some examples of your own. Just change the values of the variables and re-run the cell to see what happens.
First, some functions for checking basic properties of strings - does this string contain only numbers, only letters, only uppercase letters, only whitespace?
You could also try the following functions, see if you can figure out what they are testing for:
isdecimal()
isalnum()
islower()
istitle()
myString = 'This is a string'
alphaString = 'thisIsAString'
numberString = '10947'
capsString = 'THISISASTRING'
whiteString = ' \n \t \r'
print('myString is alpha:', myString.isalpha())
print('alphaString is alpha:', alphaString.isalpha())
print('numberString is alpha:', numberString.isalpha())
print('numberString is numeric:', numberString.isnumeric())
print('capsString is all in capital letters:', capsString.isupper())
print('whiteString only contains white-space characters:', whiteString.isspace())
Similar functions allow us to force a string to all uppercase, all lowercase, or the first letter of each word to be uppercase. There's also a function to remove white-space from the start and end of a string, which can be very helpful for formatting.
myString = 'This is a string'
print(myString.upper())
print(myString.lower())
print(myString.title())
extraString = ' too many spaces '
print(extraString)
print(extraString.strip())
Each character in a string is associated with a number, starting from zero. The first character has number 0, the second character has number 1, and so on.
This means you can access a particular character from the string by indicating which position it's in. Next module we'll look at python lists in more detail.
myString = 'This is a string.'
myString[3]
And putting many short strings together into a longer one.
myString = 'This is a string'
otherString = 'This-is-another-string'
print(myString.split())
print(otherString.split('-'))
myListOfWords = ['One', 'Two', 'Three']
print(', '.join(myListOfWords))
The find()
function returns the position of the first time the input sequence appears in this string.
If the sequence you're looking for is longer than one character long, find()
returns the position of the start of the sequence in the string being searched.
The replace()
function finds every time that some sequence appears in your string and replaces all of them with the alternative string. The new string could be empty, then the sequence is just deleted.
myString = 'This is a string'
myString.find('s')
myString = 'This is a string'
print(myString.replace('s', '\\'))
print(myString.replace('string', ''))
Complete the cell below to produce text saying 'Hi I'm #your_name# and I come from #your_home#. I like to #your_hobby#.', with variables for your name, home and hobby.
myName =
myHome =
myHobby =
print()
Your computer system stores a list of names of the company's customers.
All of this can be achieved with only the functions we've introduced so far and no explicit loops or list functions. If you're not sure how to solve the whole problem start by finding a way to print the list of names with some special charater between them. An example solution is given at the end of the worksheet, but you may find a different way to do it.
listOfNames = ["John O'Connell", "steven Jones", "Freddy McFredface", "is this even a name?", "Mrs. Smith "]
a = 3 + 4
b = 4 - 3
c = 3 * 4
d = 3**2
e = 8/2
print('3 plus 4 is', a)
print('4 minus 3 is', b)
print('4 multiplied by 3 is', c)
print('3 squared is', d)
print('8 divided by 2 is', e)
# try some aritmetic here
4**-1
You may want to store an integer in a variable, then modify that integer and have the result stored in the same variable. Python has a useful shorthand for doing this. The following two cells have the same result.
a = 5
a = a + 1
print(a)
a = 5
a += 1
print(a)
The same style of syntax is available for subtraction and multiplication, as well as division, exponentiation, and modulus (see below).
a = 5
a -= 2
print(a)
a *= 4
print(a)
Notice how 8/2 prints out as 4.0 rather than just 4. Python has automatically converted the answer to a different type of number, called a float. Floats allow us to represent decimals as well as integers. When using division the answer might not be an integer (for example 7/2 is 3.5) and therefore python gives the answer as a float.
You can find out what sort of number a variable is with the function type()
.
a = 3
b = 3.5
c = '3.5'
print(type(a).__name__)
print(type(b).__name__)
print(type(c).__name__)
There is a special type of division that always outputs an integer. The integer answer is always rounded down from the decimal answer.
Alternatively, we could force a float to become an integer using int()
, which simply truncates the number and outputs whatever is before the decimal point.
This function outputs the nearest whole number, with .5 rounding up. You can also give an optional argument saying how many decimal places you want the number rounded to.
a = 7/2
b = 7//2
c = -7/2
d = -7//2
print('7 divided by 2 is', a)
print(a, "has type", type(a).__name__)
print('Integer division of 7 by 2 is', b)
print(b, "has type", type(b).__name__)
print('-7 divided by 2 is', c)
print('Integer division of -7 by 2 is', d)
a = 7/2
b = 7//2
c = -7/2
d = -7//2
print('The integer part of 7 divided by 2 is', int(a))
print('The integer part of -7 divided by 2 is', int(c))
print('Rounding 7 divided by 2 to the nearest integer gives', round(a))
print('Rounding -7 divided by 2 to the nearest integer gives', round(c))
print('Rounding 3.57 to one decimal place gives', round(3.57, 1))
We can compare two numeric values to find out if they are equal or if one is bigger than the other. The symbols < and > stand for 'less than' and 'greater than' respectively. Because the equal symbol is used to assign a value to a variable, we use == to check for equality.
The code in the next cell should be read as 'is 3 equal to 4?'
Run the cell and it will output False
.
Change the content of the cell so that it outputs True
when you run it.
3 == 4
The next cell shows how the user can be asked to input something, which is then assigned as the value of a variable. The rest of the code is then run using the values that the user provided.
Change the final line of the cell to a different comparison operator. Try all of the following operators to check you understand what they do.
Symbol | Meaning |
---|---|
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to |
== | equal to |
!= | not equal to |
x = input("Enter a number: ")
y = input("Enter another number: ")
x < y
You can compare floats as well as integers, or even compare a float to an int. It is also possible to compare strings using these operators. The comparison is based on the unicode value of each charater in the strings. If your strings only contain letters then you can think of 'less than' as 'would appear first in the dictionary'. What happens if you compare a string (e.g. '3.5') with an integer (e.g. 4)?
a = 3
b = 3.5
a >= b
a = 'apple'
b = 'asteroid'
a < b
The sum()
function returns the sum of a list of numbers, either floats or ints.
a = sum([1,2,3,4,5])
b = sum([5.5, 2.4, .1, 1])
print('1 + 2 + 3 + 4 + 5 =', a)
print('5.5 + 2.4 + .1 + 1 =', b)
The modulus function % returns the remainder after a division, e.g. 7 divided by 3 is 2 with remainder 1. The modulus function would return 1 in this case.
a = 15//4
b = 15%4
print('15 modulus 4 is', b)
In general, the following formula holds:
Make sure you understand why.
x = input("Enter a number: ")
y = input("Enter another number: ")
# convert the inputs to integers (they are read in as strings)
x = int(x)
y = int(y)
# z should equal x, whatever values for x and y are entered
z = (x//y)*y + x%y
print(z)
For more advanced mathematical functions you can use the math module.
Among other things this module includes
The next cell shows how to import the module and use it to access
You should look at the python documentation for the math module if you're interested in doing fancy stuff with numbers. Run the cells below and then try out some of the other functions listed in the documentation for this module.
There are also python modules for statistics and random number generation, as well as numpy and pandas modules which are really useful for handling data sets. We will look at some of these later in the course.
import math
print(math.pi)
print('e to the power 5 is', math.exp(5))
print('5! is', math.factorial(5))
print('The square root of 25 is', math.sqrt(25))
print('The greatest common denominator of 18 and 24 is', math.gcd(18, 24))
Find the volume of a cylider with radius 5 and height 12 to the nearest whole number.
import
radius = 5
height = 12
volume =
Find the length of the hypotenuse to 2 decimal places in a right angled triangle where the other two sides have length 5 and 6.
side1 = 5
side2 = 6
hypotenuse =
If you found exercise 4 quite easy then try implementing the cosine rule, which is a generalisation of Pythagoras' theorem, to calculate the length of a side in any triangle given the lengths of the other two sides and the angle between them. You'll need to look up a function to find the cosine of an angle in the math module. How does your answer need to be different if the angle is given in degrees or radians? https://en.wikipedia.org/wiki/Law_of_cosines
Boolean values are True
and False
, which we have already seen when learning about comparison operators.
We can connect together Boolean values (or expressions that output Boolean values) using and
and or
and not*
Use parentheses to avoid ambiguity -- like you would with arithmetic.
True and False
a = 3
b = 4
c = 5
(a < b) and (b < c)
((a < b) and (c < a)) or (b == c)
Sometimes we want to have a variable that doesn't have any value, for example because it will be set later in the code but the value isn't known yet.
In this case python has a special variable type called None
.
Use the is
keyword to check whether a variable has the value None
.
x = None
x is None
myName = 'Brandon'
myHome = 'Leeds'
myHobby = 'write python programs'
print('Hi I\'m {} and I come from {}. I like to {}.'.format(myName, myHome, myHobby))
Just printing everything in the list, one item per line, is simple with the join()
function and '\n' (the 'new line' special character).
out = '\n'.join(listOfNames)
print(out)
And we can use replace()
to get rid of the incorrect entry.
out = "\n".join(listOfNames)
out = out.replace('is this even a name?\n', '')
print(out)
We can use the title()
function to make the start of the second entry into a capital
out = "\n".join(listOfNames)
out = out.replace('is this even a name?\n', '')
out = out.title()
print(out)
But now "Freddy Mcfredface" is wrong. Either we could explicitly replace "steven" with "Steven", or use a trick to make sure names starting "Mc" are treated corectly, for example
out = "\n".join(listOfNames)
out = out.replace('is this even a name?\n', '')
out = out.replace('Mc', 'Mc ')
out = out.title()
out = out.replace('Mc ', 'Mc')
print(out)
The volume of a cylinder is the height multiplied by the area of the base. The base of a cylinder is a circle so its area is the square of the radius multiplied by pi. Finally, we round the volume to one decimal place and print the output.
import math
radius = 5
height = 12
area_of_base = radius**2 * math.pi
volume = area_of_base * height
round(volume, 1)
Pythagoras theorem states that for a right angled triangle the square of the length of the hypotenuse is equal to the sum of the sqares of the other two sides.
import math
side1 = 5
side2 = 6
hypotenuse = math.sqrt(side1**2 + side2**2)
round(hypotenuse, 2)
You'll need to use the math.cos function. This expects the input to be an angle in radians. If you know the angle in degrees you can convert to radians using math.radians().
import math
side1 = 5
side2 = 6
a_degrees = 60
a_radians = math.radians(a_degrees)
c = math.sqrt(side1**2 + side2**2 + 2*side1*side2*math.cos(a_radians))
round(c,1)