Starting Python and using IDLE
Before we start, a bit of information about how you are going to use Python on your computer. You are going to use a program called IDLE to write your Python code in. IDLE is what is known as an integrated development environment (IDE). It has some really useful features like being able to run (interpret) your programs as soon as you write them and context sensitive colour highlighting as you code. IDLE has two windows, a Python Shell where the output of your programs is shown and a File window where you write and run your code.
You can start Python by clicking on the Windows Start button (bottom left) and typing either ‘Python’ or ‘IDLE’ into the Program search bar. Click on Python when it is displayed and the Python Shell will appear.
Open up a new file from the Python Shell so you can write your code and save it for later. You can do this by clicking on the ‘File’ menu and selecting ‘New File’ (Short cut: just press the Ctrl and ‘N’ keys together).
Get in to the habit of saving your work (Short cut: press the Ctrl and ‘S’ keys together), even before you type anything. To run a Python program, you will need to save it first and then click on ‘Run’ and select ‘Run Module’ (Short cut: press the F5 key).
Introduction to variables
What is a variable?
- A Variable is a location in memory that stores a value that can change as the program is running.
- Think of it like a shoe box, that you give a label and put data inside.
Rules for naming variables
- A variable name should reflect what is stored in it e.g. name, score, answer etc.
- I would suggest using lowercase for all of your variables as it will avoid errors
- Variables cannot contain spaces but _ could be used instead
Creating a variable
When a number or string is put in to a variable it’s called assigning a value to the variable. You can use an ‘=’ sign to do this.
Type this code in to your new Python file:
If you run this program (F5) you should get the following output in the Python Shell:
Note that the variable ‘a’ was initially assigned a vale of 2 and was then reassigned a value of 4. The print() command is used to show something on the screen (it has nothing to do with the printer). You can use it to show the value of a variable i.e. print(a).
Types of data
Unlike Small Basic, Python has different types of data that can be assigned to a variable, the two basic types are numbers and strings (text).
Python has two data types for numbers. ‘Integers’ are whole numbers (numbers without a decimal point). ‘Floats’ are numbers with a decimal point. An integer can be used to count things such as sheep, while a float can be used to measure things such as weight.
sheep = 10 (This will automatically assign the data type as an Integer)
weight = 15.5 (This will automatically assign the data type as a Float)
A piece of text in Python is called a ‘string’. Strings can include letters, numbers, spaces and symbols such as full stops and commas. They are usually put inside single quote marks (but some versions like double quote marks).
name = ‘Shaun the Sheep’ (This will automatically assign the data type as a String)
In Python, a Boolean always has a value that is either ‘True’ or ‘False’. In both cases, the word begins with a capital letter.
a = True or b = False (This will automatically assign the data type as a Boolean)
print(a) will output ‘True’
Which data type?
Variables can contain any type of data but it is often important that you know which type of data your variables are storing. Problems can occur if you try to mix different types together. Try running the following program and see what happens:
You will end up with an error like this:
This is Python telling you that can’t mix data types. We have just tried to get Python to add a string (‘1’) and an integer together and it doesn’t like it. To get around this problem, you can convert one data type to another. Most often, you will be converting a string to a number so you can do math on it. The command you need is int().
Modify your program so it looks like this:
Adding int(apples) will convert the string value of apples (‘1’) to an integer (1) and the program should output 2! NB, int() only works on strings that are whole numbers, int(‘dog’) isn’t going to work!
Using the input command
The input() command gets some text from the user. It will also display some text (usually a question) if you add a string inside the brackets like below.
input(‘Hello, what is your name?’)
You can assign whatever is entered by the user to a variable using code like this below. Remember, unless you tell Python otherwise, what goes into the variable will be a string.
Run it, enter your name and see what happens.
If you think you understand the basics of variables in Python and are happy using the commands print(), int() and input(), move on to the next section and have a go at the tasks.
Python challenges grading system (RAG)
Red challenges are the hardest to do and will take some serious thinking, we are not expecting everyone to be able to do these straight away. You should not attempt red challenges unless you have completed all of the Amber challenges.
Amber challenges are a bit of a step up from Green and will often involve some maths. Do not attempt Amber challenges until you have completed all of the green challenges.
Green challenges are suitable for everyone. Do not think you can just skip them as they are full of useful tips and skills that you will need in order to complete the harder challenges.
Python Variables Introduction
01) Write a program that prints “Hello World” to screen
02) Write a program that will ask the user for their first name and then print that name to screen. Look at the example above, it’s the same code.
03) Write a program that will ask the user for their first name and then their surname. Your program should then print these two pieces of data to screen.
04) Write a program that asks for the users favourite colour. Your program should then print this colour to screen, along with a suitable message e.g. “Blue, that is my favourite colour also” or “Blue, I hate that colour”.
05) Write a program that asks the user to input their first name, surname and the town they live in. Your program should then print to screen a message using all of this data e.g. “Hello Billy James from London, I hope you are well”
06) Write a program that will ask the user to enter one number, then another, and then print the sum of the two numbers using something like print(a+b). If you don’t get the answer you were expecting first time, think about data types. You can check what data type is in your variables using type() in the Python Shell.
07) Create a program that will ask the user to input two numbers, multiply them together and print the answer to screen.
08) Write a program that will ask the user to input three numbers and print to screen the answer of them all added together.
09) Write a program that will ask the user to input two numbers and print to screen answer of the second subtracted from the first
10) Write a program that will ask for the user to input two numbers and print to screen the answer of the first divided by the second. Make sure you test this with numbers where you know the answer in advance!
11) Write a program that calculates the area of a rectangle. Ask the user for the length and width. Make your output ‘user friendly’ by using something like print(“The area of your rectangle is”, width*length) where ‘width’ and ‘length’ are variables.
12) Write a program that asks the user for the date in the month e.g. 20. Then asks for the month e.g. September and finally, asks the user for the year e.g. 2018. The program should then print() to screen something like: “Today’s date is 20 September 2018”
13) Write a program that asks the user, “What times table would you like to see? “. Your program should then print() the correct times table as shown below.
Tip: Use print(“3 x “, number, ” = “, 3 * number) and use Ctrl C & Ctrl V
1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 ... through to ... 12 x 8 = 96
14) Write a program that calculates the area of a triangle if the user inputs the length of the base and the height of the triangle.
15) Write a program that calculates the area of a circle (pi = 3.141) if the user enters the radius.
16) A gardener wants to know how much turf he needs to lay a new lawn. The garden is rectangular but has a circular flower bed in the middle of it. Write a program that will allow the gardener to input all the relevant information, e.g. length, width & radius and then gives him the number of square meters of turf that he needs to order. Make your program user friendly, this gardener isn’t very good on computers.
17) Write a program to calculate journey times. What information do you need from the user? Distance & Speed? Think about your units (e.g. miles and mph) and ask sensible questions before giving a sensible response.
18) Write a currency conversion program that will convert Pounds (£) to Dollars ($). The user should input the amount of pounds to be converted and then program should output the equivalent in dollars. Note: You will need to search the latest exchange rate and assign that value to a variable in your program.
19) Write a program that coverts degrees Celsius to degrees Fahrenheit. The formula you need is multiply by 9/5 and add 32. Make the input and output user friendly.
20) Write a program that calculates how many litres of water are needed to fill a rectangle swimming pool that has a shallow and deep end.
21) Write a program that can estimate more complicated journey times for a journey like for example, from Lymington to London. This will involve traveling on minor roads at 30mph, A roads at 50mph and motorway at 70mph. Ask the user to enter how far they will travel on each type of road and work out an overall journey time.
22) The recipe for 1.25 litres of lemonade is: 3 unwaxed lemons, 100g caster sugar and 1 litre cold water. Write a program that will ask the user for the price of a lemon and the price of 1Kg of sugar (assume the water is free!) and calculates the cost of making 1.25 litres of lemonade. Get your program to also calculate the cost price per cup, assuming that 1 cup of lemonade = 0.25 litres, round the result down to the nearest penny using int().
23) On the 15th February 1971, Britain abandoned the pre-decimal (£sd) system and moved to a new decimal system where one pound sterling is divided into 100 new pence. In the old system, there were 12 old pence (d) in a shilling (s) and 20 shillings, or 240 pence, in a pound (£). Write a program that converts a pre-decimal price to a decimal price. The output to screen should look like the screen image below. To get output correct, you will need to use str() and + to join strings together.
24) You are in charge of exporting cars overseas. You need to tell the captain of the container ship how much weight you are going to add to his ship before you load the cars up. Write a program that calculates the shipping weight in tonnes for your cars and the containers they are shipped in. Each car weighs 1200kg. An empty container weighs 2500kg and can hold 5 cars. Your program should ask how many cars need to be shipped and print out to screen the total shipping weight in tonnes (1000kg in a tonne). This is trickier than it looks, it took me a whole lunch to get rid of a logic error.
25) Voyager 1 is a space probe launched by NASA on September 5, 1977, it was part of the Voyager program to study the outer Solar System. Voyager 1 is now hurtling into deep space beyond the limits of the Solar System. Voyager 1’s average speed is roughly 38,000mph. See if you can come up with a program that work out roughly how far away Voyager 1 is now if you can enter its launch date and today’s date. This is tricky, you are going to have to come up with a way of working out the hours elapsed between the two dates. For each date, maybe try asking the user for the year and how many days into the year their date is.
26) HMS Victory was a First Rate Ship of the Line made famous by Admiral Nelson and the Battle of Trafalgar. Victory carried 104 guns on 3 gun decks, including the massive 32 pounder cannons mounted on the lower gun deck. These 3.5 tonnes cannons shot a 14.7Kg (32 pound) cannonball with a muzzle velocity of 487 metres per second.
If the maximum elevation of these cannons was 5 degrees, what would be the maximum range of Victory’s 32 pounders if Nelson wanted to hit the lower gun deck of a similar sized enemy ship?
Write a program to work it out. You will need to know the following:
To find the distance a projectile will travel, use this equation:
d = ( v² SIN( 2Θ ) ) / g where: d = distance (m) v = initial velocity (m/s) Θ = angle of elevation (in radians) g = gravity (9.8 m/s²)
You will need to start your program with:
Which will allow you to use functions like math.sin(angle) and math.radians(angle)
Python has a built in library that supports turtle graphics called the “turtle”. Importing this module gives you access to all the turtle graphics functions you need to draw vector graphics in a graphics window.
In turtle graphics you control a cursor (frequently called the Turtle). The Turtle has the following properties: an x,y position on the graphics window; an orientation / heading and a pen that can draw coloured lines on the screen.
You can copy the program below in to your Python programming file to see an example of what Python Turtle can do.
import turtle colors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange'] for x in range(360): turtle.pencolor(colors[x % 6]) turtle.width(x / 100 + 1) turtle.forward(x) turtle.left(59) turtle.exitonclick()
Basic Turtle commands
This will import the Turtle library into your python code. You have to have this line in order to use Turtle graphics.
This function will pause your program at the end until you click on the graphic window. You should place it at the end of your program.
This will move the turtle forward by 100.
This will move the turtle backwards by, in this case, 10.
This function will rotate the turtle’s direction by 90 degrees to the left.
This function will rotate the turtle’s direction by 120 degrees to the right.
Pencolor will change the colour of the lines displayed by your turtle. Note the American spelling: COLOR instead of colour! You can use the basic colours; red, green, blue, yellow etc.
Pendown places the pen on the ‘page’ ready to draw.
Penup lifts the pen so it can be moved without drawing. Penup / Pendown are useful if you are drawing more than one shape in different locations.
Using these basic Turtle commands, try the following tasks:
27) Draw a Square
28) Draw a Triangle
29) Draw a Hexagon
30) Draw a Pentagon
31) Draw an Octagon
32) Draw a six pointed star
33) Draw a five pointed star
34) Draw a house (with door and windows)
35) Your initials (shapes not lines)
36) Ask the user to enter a value for length and then draw a square with that length sides.
37) Use the previous program but allow the user to choose the colour too.
Introduction to Selection
What is Selection?
“The pathway through a program is selected by using a condition to decide on what instructions to execute next”
Watch this video by Bill Gates if you would like further explanation on what selection is in coding.
Making decisions – Programs make decisions about what to do by comparing variables, numbers and strings in comparison statements. The result of these comparisons is always either True or False.
Python has a number of comparison operators, here are the most common:
- == ‘Equals’ operator (Used to check if two values are the same)
- != ‘Not equal to’ operator
- < ‘Less than’ operator
- > ‘Greater than’ operator
- <= ‘Less than or equal to’ operator
- >= ‘Greater than or equal to’ operator
Here are some examples of the outcomes of conditional statements:
- 8 == 2 False
- 8 == 8 True
- 2 != 3 True
- 7 < 3 False
- 7 > 3 True
- 7 <= 7 True
- 1 >= 2 False
The if’ command checks a conditional statement, if the outcome is True it will run the following block of commands, if it is False it won’t run the following block of commands. The block after the ‘if’ command is indented by four spaces. Here’s a small Python program showing the syntax of the ‘if’ command:
If you ran this program and entered ‘sunday’, the output would be ‘Have a lie in.’ If you entered anything else, there wouldn’t be any output as the conditional statement would be False. Please note the ‘:’ at the end if the ‘if’ command line, it’s often forgotten.
The ‘if’ command can be combined with an ‘else’ command which allows one thing to happen if the condition is True and something else to happen if it’s False. Extending our program above:
This time, if you entered anything other than ‘sunday’, the output would be: ‘Get to work!’
Finally, the ‘elif’ command (short for else-if) allows you to check a condition, if it is True the following block of code will be run, if not the program will move on to the next condition and check that. Look at this coding example to see how it works:
Python Selection Challenges
38) Can you create a program like the one below and check that it works.
39) Can you create a program that replicates the following flow diagram:
40) Can you make your own version of the program below and check that it works as it should:
41) Recycle the code from the last two tasks to create a program that replicates the following flow diagram:
42) Take the add/subtraction program that you saw previously (also below) and add more functions so it can also give answers for multiplication and division.
43) Write a program to allow the user to INPUT the length and width of a rectangle and calculate the area. If the length and width are equal the OUTPUT should recognize that it is a square NB, use print(‘This is a square of area’, area). Otherwise, the OUTPUT should recognize that it is a rectangle NB, use print(‘This is a rectangle of area’, area).
44) Write a program to display a menu of options:
45) Write a program that allows the user to select from three shapes, e.g. Square, Star and Triangle. Your program should then draw that shape. Refer back to your Turtle Tasks, copy and paste the relevant code.
46) Refer back to task 16 ‘A gardener wants to know how much turf he needs to lay a new lawn… etc.’ Add an if… else… statement to make sure it is not possible to end up with a negative output. Give sensible outputs for both options.
47) Write a program that asks for a pupil name and their score (percent) from an exam, then outputs the corresponding grade i.e.
- 90 or above is equivalent to an A grade
- 80-89 is equivalent to a B grade
- 70-79 is equivalent to a C grade
- 60-69 is equivalent to a D grade
- 59 or below is equivalent to an F grade
The output should be in the following format: name achieved x grade in their exam.
Test you program close to the grade boundaries.
48) Copy and paste Task 45. Extend it’s functionality so the user can also select a pen colour from a list of at least three colours.
49) Extend the functionality of Task 44 so it is password protected. The user has to enter the correct password before they get to see the menu. You will need to assign the correct password string to a variable in your program and compare this to what the user has entered. You will need to use nested IF statements to solve this one.
50) Write a program that allows the user to enter three numbers. It should then output them in ascending order. You will also need to use nested IF statements to solve this one too.
51) Type in the following program and test how it works:
52) Type in the following program and test how it works:
53) Type in the following program and test how it works:
54) Write a program that requires the user to enter a username and a password. These should both be checked against previously assigned values using ‘and’ in a selection statement. If the username and a password are correct, the user should be told they are logged in.
55) Write a small three question quiz that deals with whether the user capitalizes or not the answer. Use ‘or’ in the selection statement. Remember to test after the first question.
56) Acme products shop is open from 9 to 5, Monday through Friday except on Wednesday when they shut at 1. They’re shut all weekend. Write an app for their website where the user enters the day and hour and are told if the shop is open or not.
57) Write a program to simulate the FizzBuzz game. The game works be outputting ‘Fizz’ if a number that is divisible by 3, ‘Buzz’ if its divisible by 5 and FizzBuzz if it’s divisible by both. If it’s none of these, the entered number is printed. The Python modulus ‘%’ operator gives a remainder. e.g. if number % 3 == 0 will be True if number is exactly divisible by 3.
58) Write a Python program to display astrological sign if the user enters their date of birth. Expected Output:
Enter your birthday: 15 Enter the month of your birth (e.g. march, july etc): may Your Astrological sign is : Taurus
59) Write a Python program that will output the next day if the user enters a date. Expected Output:
Enter a year: 2016 Enter a month [1-12]: 08 Enter a day [1-31]: 23 The next date is [yyyy-mm-dd] 2016-8-24
60) Write a small adventure program using nested IF … ELIF … ELSE structures. If your adventurer takes a wrong option, you can terminate the program using ‘break’. You will need an introductory paragraph to set the scene and the objective.
Introduction to Iteration
The syntax for a FOR loop (Iteration) in Python looks like this:
start is the number you would like x to start on. The default is 0
stop is the number you would like x to stop at. When x gets to this number the loop will stop and not process any more of the indented commands. Warning! This is often misunderstood and leads to logic errors.
At the end of each loop, x will increase by step. The default is 1.
Watch Mark Zuckerberg explain why loops are so useful…
Python Iteration Challenges
61) Recreate the program shown below and run it.
Try changing the values of start, stop and step and see what the output is.
62) Use the program above to print out the ‘4 times table’. NB, the syntax for the print statement will be: print(x, ‘X 4 =’, x*4)
63) This program introduces Python Turtle Graphics in to the mix. You will need to import the ‘turtle’ library as shown in line 1. ‘forward(100)’ tells the Turtle to move forward 100 and left(90) tells the Turtle to turn (anticlockwise) 90 degrees. The Turtle starts in the middle facing right. Recreate the program below and see what it does. Note that we are now introducing the variable ‘sides’ into the For loop.
64) Copy and edit your last program so it will output the following in the graphics window. You will need to turn your Turtle before the loop starts to get it to look exactly like this:
65) Copy and edit your last program so it will output an octagon in the graphics window
66) And again so it outputs a star like below. The angles on this one are a bit more tricky and like the triangle, you’ll need to turn the Turtle before it starts drawing if you want to match the output below:
67) Here’s a bit of code to play with it. Try to understand what the code is doing, feel free to change parameters and see the results. Impress me!
68) Snow day! Work it out!
69) Try and create a program that replicates the game FizzBuzz. Your program should count from 1 to say, a hundred, and output either ‘FizzBuzz’ if the number is divisible by both 3 and 5, ‘Buzz’ if it is only divisible by 5, ‘Fizz’ if it is only divisible by 3 or just the number itself otherwise. You will need the condition: number % 3 == 0 to check whether something is exactly divisible by (in this case) 3.
70) See if you can use turtle graphics to replicate this optical illusion:
Here’s some code that might get you started:
You will also need the penup() and pendown() functions.
71) Welcome to the world of nested loops! This is a very common technique used in programming. See if you can write a program that gives and output similar to a 24 hour clock i.e. starting at 00:00, 00:01 through to 23:58 , 23:59. You will need two lots of iteration to achieve this, one For loop that deals with the hours and a second For loop that deals with the minutes but inside the hour loop. Good luck!
72) Write a program that outputs the following. You will need to use a loop with a negative step:
73) Write a number guessing program that selects a random number between 1 and 100 and then allows the user to attempt to guess that number. The program should say whether they guessed low, got it write or guessed high. When they get it right, they should be told how many turns it took. The out put should look like this:
I started with this following code:
import random found = False turns = 0 random_number = random.randint(1,100) while found == False:
74) Write a program that will calculate the size (in Mb) of a music file on your storage device. The program should ask for the sample rate, the audio bit depth and the song length. The output should look like this:
75) Write a random sentence generating program. Get your program to randomly select one name from four, a verb from four and an object from four objects. Get your program to produce four random sentences from the randomly selected words so the output looks something like this (run twice):
76) Write a program that outputs the times table (up to 12) for what ever number the user enters. Think about the formatting of the output, it should look like this:
77) Write a program that gets your turtle to make a spiral pattern. Spirals are made by using loop code similar to how you would make a circle but using the loop counter in the turtle.forward command. To get a turtle you will need this command:
Your pattern should look like this:
78) Count down to the zombie apocalypse! Write a program that predicts (randomly between 2020 and 2099) the year in which the world will end. Your program needs to output something like: “Don’t panic, the world doesn’t end until 22nd June 2044”. This is tricky as you have to factor in different length months, leap years and 1st, 2nd, 3rd, 4th etc. Good luck and watch out for zombies!
Introduction to lists
Please watch video number 10 from the playlist below…
80) Write a small program that creates list of the different houses at Priestlands School; Forest, Hurst, Solent, Avon. Your program should then print this list to screen.
81) Edit your program so that the list will be OUTPUT in its original state and also in reverse, for example;
82) Recreate the program below. Can you guess what it does?
83) Recreate this program in IDLE and check it runs as it should. Modify the program so the user can enter a string and the number of letters in the string will be output.
84) Write a program that checks if an ‘a’ appears. You will need to add a selection statement like: if letter == “a”: Output how many times ‘a’ appears in the string.
85) Write a program that counts the number of vowels in a string. This time you are going to have to loop through the string and check if each letter is in a string of vowels. e.g. if letter in string: and vowel_count = vowel_count + 1 Output the number of vowels.
86) This time we are checking if a word appears in a string but this program has a potential logic error in it. Recreate it, test it and see if you can find the issue. What Python function will you need to address this issue?
87) Recreate the program below in IDLE. Can you guess what it will do?
88) Modify the program above so it asks the user how they are feeling and gives a sensible response based on what they enter.
89) Do the same but for a different question like, “What’s the weather like today”
90) Write a small program that creates a shopping list with the following items: Ketchup, Sugar, Milk, Beans and Bread
91) Extend your program so it uses iteration to print out the shopping list.
92) Edit your program so it just prints out the number of items in the shopping list. There are two different ways you can do this; you can add a counter in your loop or you can use the len(mylist) function.
93) Edit your program so it prints out the 5th item in the list. What happens if you try to print out the item with an index of 5?
94) Ask the user to input an item of shopping and save it in a variable. Then replace the first item on the list with the item the user entered. Finally, print out the new revised list.
95) Ask the user for an item of shopping. Display the shopping list as before (but with each item’s index number too) and ask them for the index number of the item they wish to replace. Replace the selected item with the newly entered item and print out the revised list.
96) Create a program that asks the user which shopping item they would like to check for in the list. It should then inform the user if the item is in the list or not and where in the list it is. Your output should look like this:
This is harder than it looks. Think about how you are going to deal with 1st, 2nd, 3rd etc.
97) Write a program that uses two lists to simulate a small contact database. Your program should output a list of say 10 entries displaying their name (first name, second name) and email address. Use this random name generator site to make up the names. Don’t do too many!
98) Add some functionality to your program above. Allow the user to have the option to add another name / email address to your lists and then display the revised list.
99) Now allow the user to remove an entry from the list. You will probably need to display the index position now too and maybe a small menu of options after you’ve displayed the list. Use del mylist to remove an item from your lists.
100) Lastly, add some functionality to your program that allows a user to edit an existing entry. There should now be 4 items on your options menu; Add, Remove, Edit and Quit.