Welcome to the programming with Python. This page is going to help you learn the worlds most popular programming language (see image below). You should work through each of the tasks on this page at your own pace but remember that these do get difficult!
Variables and Assignment
A variable is a named memory location used to store data. This means that when you create a variable you reserve some space in the computers memory. Creating a variable in Python is easy. You type the name of your variable followed by a single = and then the data that you would like ASSIGNED to this variable. See the examples shown below:
myMessage = “Hello, World”
school = “Priestlands”
year_of_birth = 1987
Variable Naming Rules
- Variable names must NOT have spaces
- Variable names must not use any reserved keywords (See below)
- Must begin with a letter (a-z, A-z) or underscore (_)
- Other characters can be letters, numbers or _
- Variable names are case sensitive (this means that when ever you refer to a variable in your code it should look exactly as it did when you declared it)
- Use a logical name that describes what is stored in the variable e.g. FirstName
Python allows you to make your code more efficient by allowing multiple assignments of values to variables e.g. shoe_size, height = 5, 179
Now watch video 2 at this link and then have a go at the following tasks…
1) Which of these variable names and assignment statements will NOT cause a syntax error? Create them in Python to see!
- continue_list = 15
- red Counter = True
- 154.2 = length
- _1234 = ‘password’
- my_best_friend = “Thomas”
2) Create a variable named carname and assign the value “BMW” to it. OUTPUT this to screen using a print statement.
3) Create a variable named a and assign “Hello” to it. Create a variable named b and assign “World” to it. OUTPUT both of these variables to screen using print statements.
4) Create variables called x, y , z and assign “One”, “Two”, “Three” to them. Use print statements to OUTPUT these to screen. (Challenge: can you code this in 2 lines?)
5) Create a variable named x and assign “Python is ” to it. Create a variable called y and assign “amazing” to it. Use a print statement to print these on one line.
6) Create a variable called message and a variable smiley message. Assign “Have a nice day” to message and “:)” to smiley. Output this to screen using a print statement on one line.
7) Create a program that OUTPUTS the quote below. You need to create three variables, quote, name and year. The following data should be assigned to each of these;
- quote = “You want to know the difference between a master and a beginner? The master has failed more times than the beginner has ever tried.”
- name = “Master Yoda”
- year = “1979”
8) Create the variables; Firstname, Surname, Age and assign sensible data to each of them. Use print statements to OUTPUT them to screen.
9) Create variables to store the first 5 letters of the alphabet. Output these to screen on a single line. (Challenge: can you code this in 2 lines?)
10) Create three variables to store “Python”, “Visual Basic”, “Java”. Print these to screen on one line in alphabetical order.
11) Create four variables to store “Computer Science”, “Maths”, “Physics”, “History”. Print them to screen like the example below…
12) Create a program that OUTPUTS to screen hello in four different languages. Create variables named english, spanish, german, italian and french. Assign to them the their translation for hello. Your program should then use print statements to OUTPUT the following…
13) Create variables named one, two, three, four, five, six, seven and assign the data show below to each;
- one = “Mr. and Mrs. Dursley”
- two = “of number four”
- three = “Privet Drive”
- four = “were proud to say that they were perfectly normal”
- five = “thank you very much”
- six = “They were the last people you’d expect to be involved in anything strange or mysterious”
- seven = “because they just didn’t hold with such nonsense”
You then need to use a print statement to OUTPUT them in one paragraph, adding in the commas and full stops in the correct places as shown below…
“Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you’d expect to be involved in anything strange or mysterious, because they just didn’t hold with such nonsense.“
14) Write a Python program to print the following string in the format shown below. You need to use variables to store each line but be smart, some lines repeat…
Help: This code will help you…
Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are
15) Write a program to calculate and OUTPUT the area of a square with a side length of 9.7cm.
16) Write a program to calculate and OUTPUT the area of a rectangle with side lengths of 11cm and 6cm.
17) Write a program to calculate and OUTPUT the volume of the cuboid shown below…
18)Write a program to calculate and OUTPUT the area of the triangle shown below. Remember the formula for the area of a triangle is (base * height) /2
19)Write a program to calculate the area of a circle with a radius of 6.7cm and PRINT the result of the calculation. Set the value of Pi = 3.142.
20)Write a program to calculate and OUTPUT the area of a square. The program should prompt the user to input the side length of the square and then OUTPUT the area to screen using a print statement.
Data Types: An Introduction
Have a go at the 5 small programming problems below. Save each of these in your Python folder.
Watch video 3 at this link before attempting the tasks below.
21)Create a program that stores two numbers in variables and outputs the answer of them added together
22)Create a program that stores two numbers in variables and outputs the answer of the second subtracted from the first
23)Create a program that stores two numbers in variables and outputs the answer of them multiplied together
24)Create a program that stores two numbers in variables and outputs the answer of first divided by the second
25)Create a program that prompts the user to enter their name and then OUTPUTS a message “Hello ” + name + ” I hope you are well”. The message should appear on two lines using one print statement.
26)Create a program that allows the user to input two numbers and outputs the sum of the numbers.
Watch video 4 at this link before attempting the extension tasks below
27) Create a program that will allow the user to input two numbers and output the remainder (if any) of the first divided by the second. Remember to test your program with logical numbers to see if it is working as expected.
28) Run the code below to see what it does. Re-write the program so that it OUTPUTS “o” to screen
29) Run the code below to see what it does. Re-write the program so that it OUTPUTS “programming” to screen
30) Re-write your code to output “I love” to screen
31) Re-write your code to output “I” to screen
32) Try the code below to see what it outputs to screen. Re-write the program to OUTPUT 5 to screen.
33) Write a program that asks the user to input a string and then outputs the length of this string with a suitable message. Your output should look like this…
34) Write a program that asks the user to input two strings and will output how long both strings are added together.
35) Try the code below to see what it outputs to screen. Can you see what it is doing?
Write a comment line to explain what .strip() does above the line, some thing like this…
36) Run the following code to see what it does.
Re-write the program to take a user input and convert it all to upper case.
Please watch video 5 at this link and then have a go at the following tasks…
37) Edit the program below so that it outputs “Y is bigger”
38) Create a program that prompts the user to INPUT their age and then OUTPUTS IF they are old enough to drive.
39) Create a program that allows the user to INPUT 2 numbers and will OUTPUT the largest number.
40) Create a program that allows the user to input an integer. The program should then output if the integer is greater than zero.
41) Create a program that allow the user to input any number. The program should then output if the number is positive or negative
42) Create a program that asks the user to input the temperature in Celsius. The program should then output “wear shorts” if the temperature is greater than 20 or “Wear Trousers” if the temperature is less than 20.
43) Edit the program below so that it outputs the string “Both conditions are true”
44) Create a program that allows the user to INPUT 3 numbers and will OUTPUT the smallest number.
45) Create a program that allows the user to INPUT 3 numbers and will output them in order from largest to smallest.
46) Write a simple program that might be used inside a police speed camera.
The Requirements are:
- It must allow the user to Input a driver’s speed
- IF the speed is over 70mph, it should Output “Issue Fine”
- Otherwise it should Output “No Action“
47) Create a program that will prompt a user to input the current time using the 24hr clock. If the user Inputs a number less than 12.00 then your program should Output “Good Morning”, If the user Inputs a number greater than 12.00 but less than 18.00, it should Output “Good Afternoon” and If the user Inputs a number greater than 18:00 but less than or equal to 23.59 then it should Output “Good Evening”. An example of what your program should Output can be seen below:
48) Write a program that will convert a dogs age into human years. The program should ask for the dogs name and age as inputs and then output a message that includes the dogs name and human age. The following information will help you:
It’s a generally accepted belief, to assume that one year in the life a dog corresponds to seven years in the life of a human being. But apparently there are other more subtle methods to calculate this haunting problem, haunting at least for some dog owners.
Another subtler method works like this:
- A one year old dog roughly corresponds to a fourteen year old child
- A dog who is two years old corresponds to a 22 year old human
- Every further dog year corresponds to five human years
49) Write a program that could be used to assign grades to test marks automatically.
Greater than or equal to 90% is an A*
Greater than or equal to 80% is an A
Greater than or equal to 70% is a B
Greater than or equal to 60% is a C
Greater than or equal to 50% is a D
Greater than or equal to 40% is a E
Greater than or equal to 30% is a F
Greater than or equal to 20% is a G
Less than 20% is a fail
It should OUTPUT a ‘certificate’ on screen, showing the students name, the possible mark, students mark, percentage and grade.
50) Create a program that will ask the user 10 general knowledge questions. The program should OUTPUT if the user gets each question correct, a current score and a certificate at the end that shows the users total score along with a message that includes their name.
TIP: The syntax below can be used to increment (increase) a variable. Both lines do the same thing, but the bottom one is the short hand version
51) Code the simple game shown below in Python. Your program should allow the user to INPUT a number and the OUTPUT should either be “Fizz”, “Buzz”, “FizzBuzz” or the original number.
TIP: The syntax below will help with this task. This line is saying; If number divided by 3 has no remainder…
52) Can you create a Rock, Paper Scissors game in Python using Conditional Statements. Your program should do the following:
- Allow the user to INPUT their choice (Rock, Paper or Scissors)
- Generate a Random number (Use the tip below to help you do this)
- Use this random number to assign the computers choice
- Use a selection statement to decide who wins
TIP: You will need to generate a random number in your program to set the computers choice. Use the syntax below to help you do this…
To generate a random number you need to type ‘import random’ at the top of your program. To assign a random number to a variable you type the following:
- variable_name = random.randint(a, b)
- a and b are the values that you want the random number to be between
53) Can you create a game based around a random coin flip. Maybe the user INPUTS their guess and then a coin is flipped. IF they guess correct then they get a point ELSE the computer gets a point. To generate a random number you need to type ‘import random’ at the top of your program. To assign a random number to a variable you type the following:
- variable_name = random.randint(a, b)
- a and b are the values that you want the random number to be between
54) Can you create a program that will allow the user to INPUT a fruit that they would like to buy and INPUT how many they would like. IF the user wants 10 or more of the fruit then they get a 10% discount. The program should then OUTPUT the price, including any amount discount. The price of each fruit can be seen below:
Apple = 20p, Banana = 17p, Orange = 24p
55) ‘PerfectHoliday’ is a program that asks the user to enter their preferences and then match them to their perfect holiday. The program works like this:
- The user is asked to select whether they prefer either sightseeing OR shopping holidays.
- If they select sightseeing, they should then be asked whether they want to travel for more than 2 hours by airplane.
- If they select no, the program will assign ‘Paris’ to the variable ‘destination’. If they select yes, the program will assign ‘Athens’ to the variable ‘destination’.
- If they select shopping, they are then asked whether they want to travel for 5 hours or more on a plane.
- If they select no, the program should assign ‘Milan’ to the variable.
- If they select yes, the program should assign ‘New York’ to the variable.
- The program will print the variable ‘Destination’ to screen.
Iteration is a posh way of saying “loop” (iteration literally means to do something again).
Loops are absolutely vital in programming in order to avoid having to write sequences of code out again and again. They come in several forms:
Now watch video 7 at this link and then have a go at the following tasks…
These will repeat code a set number of times and are ideal if we know how many times we want to repeat in advance. Have a look at the example below. Code this yourself to see what it does…
Now write the code in your book along with the table below under a title of ‘For Loops’. Change the numbers in the brackets and write in your table what the program OUTPUTS. This should help you get your head around what the numbers are doing.
For each of the following programs you need to write the code for each in the front of your book and add comment lines to each program. You need to make commenting your programs a habit as you will gain marks in the controlled assessment for this.
) Create a program that will OUTPUT a simple sentence 10 times
) Create a function that will prompt the user to INPUT a string and then will repeat this 5 times
) Create a program that will OUTPUT numbers 1 – 10 but will pause after OUTPUTTING each. The following lines of code will help you;
) FizzBuzz Version 2.0: Create a program that will OUTPUT numbers 1 – 100 and apply the FizzBuzz rules. Your program should also have a short delay between OUTPUTTING each. Use the code that you researched from the previous program to help you with this delay.
) Create a program that will OUTPUT the 12 times tables using a for loop. The OUTPUT should look something like this:
) Create a program that will OUTPUT all of the odd numbers from 1 – 100. The OUTPUT should look something like this:
) Can you create a program that will OUTPUT the integers from 10 down to 1 and then the string “BLASTOFF”
) Can you create a that will display all of the hours and minutes from 12:00 to 14:59. HINT: You will need to use a nested loop (a loop within a loop).
) Sometimes you need to stop a loop before coming to the end of the original instructions….Look at the example below that shows you how can break out of a loop if a condition is met;
Write a program that will start at 1 and end at 1,000,000. The program should print each number followed by its square but break once this square is bigger than 4096. You will need to research how to break from a loop in Python.
) Create a program that will ask its user 10 random Math questions. These can either be +, -, * or / questions. Your program should keep score and OUTPUT this score at the end. If you want to challenge yourself then try and code it so that the quiz OUTPUTS random -, +, /, * questions. You will need to make use of random numbers to be able to code this. Remember you generate random numbers like this;
) For loops can also be used to loop through variables. For example the following code will loop through each letter in the variable word and OUTPUT each letter.
Create a program that will allow the user to INPUT a string and then use a For loop to iterate through it and OUTPUT each letter. Your program should OUTPUT something like this:
) Create a program that will allow the user to INPUT a string and will OUTPUT how many vowels (AEIOU) the string has. Use the loop shown in task 37 to help you do this. Your program should OUTPUT something like this:
) Create a program that will allow a user to INPUT a Floating point number and how many times the user would like this number OUTPUTTED. Your program should OUTPUT something like this:
) Can you use a For Loop to create the following OUTPUTS:
Now watch video 8 at this link and then have a go at the following tasks…
) Write a program that asks the user to input a series of numbers and adds them to a total until the user enters zero. (This stopping value is often called a rogue value).
) Write a program which asks the user to set a password and then asks the user to enter the password again. Program it so that if the second password doesn’t match the one set, the request to enter the password is repeated until it does match the set password.
) Write a program that asks the user for a number between 10 and 20 and validates (which means ‘tests’) that the input is within the correct range. It should repeatedly ask the user for a number from this range until the input is within the valid range.
) Write a program that will OUTPUT the string “Hello World” while the user does NOT input x. When the user INPUTS ‘x’ your program should exit the loop. Look at the example OUTPUT and useful code below to help you:
) Create a program that uses a While Loop to create an OUTPUT like shown:
) Use a while loop to create the following OUTPUT:
) Use a while loop to create the following OUTPUT:
) Use a while loop to create the following OUTPUT:
) Create a program using a while loop that will OUTPUT all of the even numbers between 1 and 100. Your program should OUTPUT the number followed by the string “is an even number”
Write a program using a While Loop that will OUTPUT random maths questions to a user. The questions must be a random selection of +, -, / or *. The program should continue looping until the user inputs a certain number e.g. 9999. If the user INPUTs this number then the program should OUTPUT a message, their current score and then end.
Can you make your program robust (difficult to crash). For example if the user INPUTS a string your program should not crash and instead warn them that they have INPUT invalid data. Try using page 74 of your Python Programming booklet to help you.
Please copy the below code into the programming section of your book and highlight/annotate where the following has been used (use the Glossary in your revision guide to help you!)
- Comparison Operator
An array is a special type of variable that allows you to store multiple values under one name. An array in Python is called a list. Each item/element in the list has an index number by which it can be referred….
A list in Python can be declared like this;
Notice that the elements in the second list (numbers) shown above do not have speech marks around them. This is because they are integers and these may have calculations performed on them!
Now watch video 10 at this link and then have a go at the following tasks…
) Declare a list with 4 elements and OUTPUT it to screen:
) Declare a new list with 5 elements, reverse it and OUTPUT it to screen:
) Declare a new list with 4 elements, sort it into alphabetical order and OUTPUT it to screen:
) Add an item to the list that you have just sorted alphabetically and OUTPUT it to screen:
) Now try to remove an item from this list and OUTPUT the list to screen:
) OUTPUT the index of an element in your list like so:
) Count the occurrences of a particular element in the list and OUTPUT this to screen:
) Insert an item into index position number 1 in your list and OUTPUT it to screen:
) Now lets extend the program above and add some user input. Edit your previous program to prompt the user to INPUT a fruit and an index position that they would like their chosen fruit to be inserted into. This list should then be OUTPUT like below:
Can you create a program that will allow the user to INPUT a series of numbers, followed by a stop value e.g. 9999. The program should then OUTPUT the Range of the numbers the user has INPUT, along with a suitable message.
File Handling (Reading & Writing)
LO: To be able to Read from and Write to text files in Python
In Python, like all other programming languages, it is possible to store in text files data held within the program (such as data in variables and lists). This is great as is means that when our program closes, we can still keep our data.
Now watch video 11 at this link and then have a go at the following tasks, read the information below and and then have a go at the tasks…
These slides will also help you understand how we can Read & Write from/to text files in Python…
Writing to file tasks…
) Can you write the definition of a variable to file
) Can you write the name of three data types to file (on separate lines)
) Can you ask the user to INPUT the following data:
And then write this to file. This should be on a single line, separated by commas.
Here are a couple of useful loops when reading from text files…
For For example, the text file below would output the following…
Reading from file tasks…
) Can you set up a text file with 20 Computer Science definitions that you have learnt since the start of the course and OUTPUT them to screen in Python?
) Can you OUTPUT to screen only definitions 1-10?
) Can you OUTPUT definitions 1, 3, 5, 7, 9, 11, 13, 15, 17, 19?
) Can you OUTPUT a definition at random?
) Can you OUTPUT a definition of the users choosing? For example, you may simply ask them what number definition they would like, and your program will then OUTPUT that definition.
) Can you store all of the definitions in list and then OUTPUT them to screen in reverse order?
) Can you create a file containing some names, DOBs and telephone numbers. Something like this…
) Can you create a program that will output a line of the users choosing? They should be given multiple choice options for which data to be outputted to screen e.g…..
Sub Programs (Procedures and Functions)
Functions and procedures are blocks of organised code that perform a specific task; we can reuse them to make our code more efficient. Python has many ready-made functions that we can use – these are called built in functions – and you will already have used the print() and input() functions regularly.
Now watch video 14 at this link and then have a go at the following tasks…
Functions v Procedure: Whats the difference?
In Python, the blocks of code that we write are all known as functions. However, in programming terms you will need to know the technical difference between a function and a procedure.
- A PROCEDURE is a self contained block of code that performs a specific task e.g. calculating the average of two numbers, printing out a list of numbers. The procedure may return a value but does not have to
- A FUNCTION is a self contained block of code that performs a specific task e.g. asking for data input from the user and checking that it is valid. A function will always return a value.
Here is an example of a procedure. NOTE: The last line is very important. This is ‘calling’ the procedure. In other words it is telling Python to run the code indented under the line ‘def greeting():’
) Can you create your own version of the example shown above?
) Write a procedure to add two numbers together and output the answer. Use the following variable names and values; x = 17, y = 22
) Write a procedure to multiply x and y together and divide by z. Use the following variables in your procedure; x = 6, y = 4, z = 8
) Can you create a procedure that OUTPUTS the volume of the shape shown below?
) Can you create a procedure that outputs the 10 times tables in the form “1 times 10 is 10” and so on until 12
Now watch video 15 at this link and then have a go at the following tasks…
) Develop a procedure that uses parameters to supply the following arguments; x = 15, y = 13, z = 5. Your program should output the answer of x + y + z.
) Write a procedure that has one parameter and will take in any string as an argument and print it to screen, followed by “You’re welcome”. Supply the following argument to the procedure; “There are only 10 types of people in the world”
) Re-write your times table procedure to use a parameter so the user can input any number they would like
) Develop a FUNCTION that accepts a string as an argument and will RETURN whether the string has an odd or even number of letters
) Have a go at programming the exam question below…Click for Exam Board Marking Scheme
) Create a function that prompts the user to input a password twice. If the passwords match, then the function should end. If the passwords do not match then the function should run again
) Develop a function that has one parameter. The function should take a number between 1-5 as an argument. It should then output a joke depending on the number passed into it. It should also allow the user to select if they would like to re-run the function with a different argument.
) Have a go at programming the exam question below. Remember that it is asking you to RETURN the day of the week NOT print it
) Create a function that displays a menu of options. The function should RETURN the users choice. This choice should then be stored, added to a list and outputted to screen. Look at the example below…
) Can you create a function that has two parameters. The function should take in two numbers as arguments and RETURN the smaller of the two numbers
) Write a function that has three parameters. The function should take in three numbers as arguments and RETURN the largest of the three numbers
) Write a function that adds together all the numbers in a list and RETURN the sum of all the numbers
) Write a function to multiply all the numbers in a list and RETURN the answer
) Write a function that checks if a number is in a given range (e.g. between 1 and 10). The function should have three parameters, the lower bound, upper bound and the actual number. The function should RETURN TRUE if the number is within the range or or FALSE if it is not.
) Write a Python function that accepts a string and RETURN the number of upper case letters and lower case letters
Sample String : ‘The quick Brow Fox’
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
) Write a Python function that takes a number as a parameter and will RETURN if the number is prime or not. Note: A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]
) Write a Python function that takes a list and will RETURN a new list with the unique elements of the first list
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
) Write a Python function that checks whether a passed string is a palindrome or not. Your function should RETURN TRUE or FALSE
Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run
) Write a Python function to check whether a string is a pangram or not. Your function should RETURN TRUE or FALSE
Note : Pangrams are words or sentences containing every letter of the alphabet at least once.
For example : “The quick brown fox jumps over the lazy dog”
) Write a Python function to create and RETURN a list of square numbers between a user defined range. For example…
) Create a Caesear Cipher function. This should allow the user to input a string and RETURN the newly encrypted string. It should also ask for a “key” value. This is the amount that the original characters should be shifted along the alphabet. Look at the example below to help you…
) Brute Force Attack. Create a procedure that will generate random passwords. These passwords should be a random word followed by a random selection of digits. The first password to output should always be the word on its own. The next ones should then have digits following it, for example…
) Pin Number Combinations. Create a procedure that will OUTPUT all of the possible combinations of a 4 digit pin number. You need to work out how many combinations there are first so that you can test your program outputs this many
) Create a substitution cipher that will encrypt data. This is where you create a Cipher alphabet (see below) to encrypt data. Traditionally, mixed alphabets may be created by first writing out a keyword, removing repeated letters in it, then writing all the remaining letters in the alphabet in the usual order.
Using this system, the keyword “zebras” gives us the following alphabets:
A message of
flee at once. we are discovered
SIAA ZQ LKBA. VA ZOA RFPBLUAOAR
NOTE: Think about how your are going to store your original alphabet and cipher alphabet