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
When you create variables and choose a name for them there are some basic rules we must follow:
- 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…
Before you start you need to create a Python folder within your Computer Science folder. You should then create a Python file and name it “Python Programming”. This file will contain all of the tasks from this page and will make it much easier to work out where you go to between lessons.
01)Which of these variable names and assignment statements will NOT cause a syntax error?
- continue_list = 15
- red Counter = True
- 154.2 = length
- _1234 = ‘password’
- my_best_friend = “Thomas”
02)Write a program to calculate and OUTPUT the area of a square with a side length of 9.7cm. Add comment lines using # to annotate your code and then save this under a logical name in your Python folder that you created earlier.
03)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. Add comment lines using # to annotate your code and then save this under a logical name in your Python folder.
04)Write a program to store the following variables:
Use one PRINT function to display the information in a sentence. Add comment lines using # to annotate your code and then save this under a logical name in your Python folder.
05)Write a program to calculate and OUTPUT the area of a square with a side length of USER INPUT. Add comment lines using # to annotate your code and then save this under a logical name in your Python folder.
Data Types: An Introduction
Have a go at the 5 small programming problems below. Save each of these in your Python folder. Make sure you add comment (#) lines into you code to annotate what you have done.
Watch video 3 at this link before attempting the tasks below.
06)Create a program that stores two numbers in variables and outputs the answer of them added together
07)Create a program that stores two numbers in variables and outputs the answer of the second subtracted from the first
08)Create a program that stores two numbers in variables and outputs the answer of them multiplied together
09)Create a program that stores two numbers in variables and outputs the answer of first divided by the second
10)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.
11)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
12) 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.
Please watch video 5 at this link and then have a go at the following tasks…
13)Create a program that prompts the user to INPUT two whole numbers. OUTPUT a message “The average of your two numbers, ” (number1) and (number2) is (average).
14)Create a program that prompts the user to INPUT their age and then OUTPUTS IF they are old enough to drive.
15) Create a program that allows the user to INPUT 2 numbers and will OUTPUT the largest number.
16) Create a program that allows the user to INPUT 3 numbers and will OUTPUT the smallest number.
17) Create a program that allows the user to INPUT 3 numbers and will output them in order from largest to smallest.
18) 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“
19) 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:
20) 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
21) 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.
22) 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
23) 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…
24) 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
25) 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
26) 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
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.
27) Create a program that will OUTPUT a simple sentence 10 times
28) Create a function that will prompt the user to INPUT a string and then will repeat this 5 times
29) Create a program that will OUTPUT numbers 1 – 10 but will pause after OUTPUTTING each. The following lines of code will help you;
30) 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.
31) Create a program that will OUTPUT the 12 times tables using a for loop. The OUTPUT should look something like this:
32) Create a program that will OUTPUT all of the odd numbers from 1 – 100. The OUTPUT should look something like this:
33) Can you create a program that will OUTPUT the integers from 10 down to 1 and then the string “BLASTOFF”
34) 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).
35) 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.
36) 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;
37) 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:
38) 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:
39) 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:
40) 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…
41) 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).
42) 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.
43) 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.
44) 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:
45) Create a program that uses a While Loop to create an OUTPUT like shown:
46) Use a while loop to create the following OUTPUT:
47) Use a while loop to create the following OUTPUT:
48) Use a while loop to create the following OUTPUT:
49) 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…
50) Declare a list with 4 elements and OUTPUT it to screen:
51) Declare a new list with 5 elements, reverse it and OUTPUT it to screen:
52) Declare a new list with 4 elements, sort it into alphabetical order and OUTPUT it to screen:
53) Add an item to the list that you have just sorted alphabetically and OUTPUT it to screen:
54) Now try to remove an item from this list and OUTPUT the list to screen:
55) OUTPUT the index of an element in your list like so:
56) Count the occurrences of a particular element in the list and OUTPUT this to screen:
57) Insert an item into index position number 1 in your list and OUTPUT it to screen:
58) 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…
59) Can you write the definition of a variable to file
60) Can you write the name of three data types to file (on separate lines)
61) 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…
62) 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?
63) Can you OUTPUT to screen only definitions 1-10?
64) Can you OUTPUT definitions 1, 3, 5, 7, 9, 11, 13, 15, 17, 19?
65) Can you OUTPUT a definition at random?
66) 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.
67) Can you store all of the definitions in list and then OUTPUT them to screen in reverse order?
68) Can you create a file containing some names, DOBs and telephone numbers. Something like this…
69) 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():’
70) Can you create your own version of the example shown above?
71) Write a procedure to add two numbers together and output the answer. Use the following variable names and values; x = 17, y = 22
72) 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
73) Can you create a procedure that OUTPUTS the volume of the shape shown below?
74) 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…
75) 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.
76) 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”
77) Re-write your times table procedure to use a parameter so the user can input any number they would like
78) Develop a FUNCTION that accepts a string as an argument and will RETURN whether the string has an odd or even number of letters
79) Have a go at programming the exam question below…Click for Exam Board Marking Scheme
80) 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
81) 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.
82) 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
83) 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…
84) 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
85) Write a function that has three parameters. The function should take in three numbers as arguments and RETURN the largest of the three numbers
86) Write a function that adds together all the numbers in a list and RETURN the sum of all the numbers
87) Write a function to multiply all the numbers in a list and RETURN the answer
89) 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.
90) 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
91) 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]
93) 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]
94) 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
95) 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”
96) Write a Python function to create and RETURN a list of square numbers between a user defined range. For example…
97) 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…
98) 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…
99) 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
100) 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