You are on page 1of 29

Python Work Book

I rate my understanding:

Part Don’t Know Can do Confident


Name:
Inputting strings
Class:
Teacher: Integers/floats

String method

If statements

Maths
Target Grade:
Decisions

loops

Nesting

Functions

Lists
This Workbook Starting Python
When you open python you need to start your programming in a New
This workbook is very important, look after it carefully. When you do your controlled assessments you will be
Window – or the code won’t work.
able to refer to it to help you.
To open a new window – select FILE from the menu bar (top left of
the screen). Then select NEW WINDOW.

Help
Ask for help from others

Complete them in sequence and do not move on to the next challenge until you have successfully got the
program running.

If possible try the extension tasks.

Look at the programs that you have completed in previous lessons for help if you struggle

Get Organised
Life will be much harder if you don’t save your work carefully. Spelling
Python is an American program; this means that the spelling is the
Create the following folders:
AMERICAN. This means words like Colour is spelt COLOR.
My Documents
Running your programmes
Once you have typed in your code. Press F5 to run your programme.
Computing You will need to say it before you run the programme.

Python

You will be asked to save your Python programs before you run them. If you save them in the python folder, it
makes it easier to find.
Inputting information and strings What is a print function?

print() function Explain what happens when you type in the code
The print function prints information to the screen. Type this in:

print (“Hello World”)


Annotate and explain what each part of the code does/why you need it:
Press F5 key to run the programme. (you will have to save the
programme).

What happens? How does this code work? How can you change the
message to GOOD DAY!
print (“Hello World”)

Write down the code you could type in to get the python to display ‘Good day’:
input() function
The input function allows the user to enter information into the Explain what the command INPUT does:
computer which the computer will save. Type this in:

name = input("Hi. What's your name ? ") What happens when you type in the code?

print ("Hello, ", name)


Annotate and explain what each part of the code does/why you need it
Variables
A variable is what is used to store information. In the program above
the variable is called name. This means what the user has typed in is name = input("Hi. What's your name ? ")
stored under the word name. You can call your variable anything you
want, and when you ask the computer print the variable you have called
print ("Hello, ", name)
it, it will retrieve it. Because the variable is in quotes “”, the variable
type is called a string.
Challenge 1: Applying your understanding of input and print functions, variables
Put your code here:
and strings. Write a programme that asks the user for their first name, surname
then prints their names in order saying hello, then prints goodbye with their
surname followed by first name.

Hints
1. Asks the user for their first name, in a way that allows the computer to save
their response as first_name
2. Asks the user for their surname, so that it can be saved using the variable
surname
3. Prints hello, then first_name and then the surname name Explain how it works and what each part does:
4. On the next line print good bye, then surname and then the first name

Part 2:
The name may not have a space between first and second names, work out how to
add one.

Easy? Ask the user their first name, surname, age and house. Print out a
statement greeting them by their name, reminding them of their age and house.

Not working?
Check the spelling, gaps, and punctuation marks
You can add existing variables together and call them a different variable name Put your code here:
You can also add two stings together.

For example:

name= input(“What is your name”) (variable 1)


surname = input(“what is your surname”) (variable 2)
fullname = name + surname (variable 1+2 = variable 3) print(“hello
“ fullname) (show variable 3)

Challenge 2:
Applying the ability to add existing variables together, adjust the code you have written
in Challenge 1 to do this.
Explain how it works and what each part does:

Hints:
1. fullName = first_name + surname
2. print (fullName)

Easy? Applying your understanding write a code for an electronic class register, with 10
students writing their first name and surname, then printing all the names for the
teacher.

Not working?
Check the spelling, gaps, and punctuation marks
Look at the code below. Describe what you think the code does:

numberOne = input(“Enter a number between 0 and 10 ”)


Describe what happens:
numberTwo = input(“Enter a number between 0 and 10 ”)
print(numberOne + numberTwo)

Explain why this happens?


Explain what you think it does?
Type in the code. Run it.
What happens?

Describe what this code does:


Adding integer command
Type in this code and run it
numberOne = int(input(“Enter a number between 0 and 10 ”)) Explain what an integer command (int) is?
numberTwo = int(input(“Enter a number between 0 and 10 ”))
print (numberOne + numberTwo)
Why has it got two brackets at the end?

Type in two for number one and five for number two. What happens? Why?

Type in 1.1 for number one and 4.5 for number two. What happens? Why?

Adding float commands


Type in this code and run it
What is a float command?
numberOne = float(input(“Enter a number between 0 and 10 ”))
Not working?
numberTwo = float(input(“Enter a number between 0 and 10 ”))
Check the spelling, gaps, and punctuation marks
print (numberOne + numberTwo)
Calorie Counter Who is this calorie counter for?Program this for the opposite sex.
Now let’s build a calorie counter. The NHS recommends that an adult male takes
Challenge? Give the option to input if you are male or female
on board 2,500 calories per-day and an adult woman takes on 2,000 calories per-
Copy your code here
day. Build your program for a woman or a man.

print("Your calorie counter")


calories = int(input("How many calories have you eaten today? "))
s=2000-calories
print("You can eat", s, "calories today")

Challenge 3:
Write a program that asks the user to enter how much they have spent on their Copy your code here
school dinner in a way that the computer can remember as dinnerCost.
Then make the program subtract the dinnerCost from the money the user had at
the start of the day.
Display the result on the screen.
 

Hint,
Adapt the calorie counter

Easy? program the computer to repeat this for 5 days and if the total goes Explain how it works:
negative, give a warning message that they do not have enough money on their
account.

Not working?
Check the spelling, gaps, and punctuation marks
Applying your skill
Complete ONE of the tasks below: Copy your code here

Area Calculator
Jennifer wants to carpet her new room with pink carpet. Create a program
that will ask the user for the two dimensions of a room (length and width)
and then calculate the area of the room, (length x width), before finally
displaying the answer.

Going Shopping
Write a program that monitors a user’s shopping trip and calculates how
much the spent
Get the program to ask for the first Item bought so that the computer
can remember this
Develop the program to ask for and remember the cost of the first Item
bought, what the second Item bought was, and the cost of the second
Item.
Develop the program further so that it calculates the total cost of the
items bought and then displays what was bought and the total amount Explain how it works
spent.

Pizza
Pizzas come in various shapes and sizes. We can use python to calculate
which pizza is the best in terms of size and price
The mathematical formula for area is 3.142 times radius squared if it’s a
circle and length times width if it’s a rectangle.
Imagine a pizza 20cm in diameter costing £4.99 and another 20cm in
length by 15cm wide and costing £6.99.Write a program in python that
calculates the surface area per £ and displays to the program user which
is the best value pizza, the round one or the rectangular one

Not working?
Check the spelling, gaps, and punctuation marks
String method
Strings are variables that contain letters, numbers and symbols. There are lots of
things that can be done with strings.

Type in the following code:

quote = “I am AN excellent programmer”


print (quote)

What happens?

Type in the following code:

quote = “I am AN excellent programmer”


print (quote.lower()) String Explain what happens

lower()
What happens?
upper()
This is what we call String method.
title()
swapcase()

capitalize()

Not working?
Check the spelling, gaps, and punctuation marks
Type in this code What happens?

quote = “I am AN excellent programmer” Change the first line to quote=“number ten!”


print (len(quote)) What happens?

Explain what the command len do?

What happens?
Type in this code

quote = “I am AN excellent programmer” Change the send line to print(quote[12])

print(quote[5]) Explain what is happening?

(Note – the first letter is always number 0)

What do you need to type in to get the letter t?

Type in this code


What is happening now?
quote ="I am AN excellent programmer"
Explain what does [n:n] do:
print(quote[7:17])

What would you need to type in to get the word programmer?

Type in Strings can also be joined together. This is called Concatenation.

gift1 =input("What gift would you like most")

gift2 =input("What gift would you like second")

giftTotal = gift1+gift2 Not working?


Check the spelling, gaps, and punctuation marks
print(giftTotal)
Boolean Operations Explain what you think this code is doing?
IF
Look at the code below. What do you think it is doing?
Annotate and explain what each part of the code does:
Type in the code below:

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: ")) num1 = float(input("Enter the first number: "))
if num1 > num2: num2 = float(input("Enter the second number: "))
print (num1, " is great than ", num2) if num1 > num2:
if num1 < num2: print (num1, " is great than ", num2)
print (num2, " is greater than", num1) if num1 < num2:
if num1 == num2: print (num2, " is greater than", num1)
print (num1, "is equal to", num2) if num1 == num2:
print (num1, "is equal to", num2)

This tests each combination and does something (prints a line out) if the test is TRUE
Python can do other things if the test is FALSE:

Do another test – If the test is False we can get Python to another test: we use elif (short for “else if”)
Do something else – If all the other tests come out false do something else: we use else

Type in the code below: Describe what elif and else do:

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
if num1 > num2: Explain why we do not need to type in: if num1=num2?
print (num1, " is great than ", num2)
elif num1 < num2:
print (num2, " is greater than", num1)
else:
print (num1, "is equal to", num2) Not working?
Check the spelling, gaps, and punctuation marks
Notice there is a ‘gap’ in front of the word ‘print’: Task

if num1 > num2: Applying your understanding of using if, elif, and else, with the Boolean
print (num1, " is great than ", num2) codes complete ONE of these tasks:
elif num1 < num2:
print (num2, " is greater than", num1)
else: Write a programme which tells the user to put on a coat if the temperature
print (num1, "is equal to", num2) of outside is less than or equal to 12 degrees C, wear shorts if the
temperature is greater than 22 degrees C, or else do nothing.
This is called Indenting. This is very important in Python, it’s a necessary
part of how you write the code. Indenting tells Python where blocks of
code start and where they end. The Python IDE programme you are using Write a programme which works out the grade in a test if the score is less
will do this for you – just be aware that it is doing it. than 40% a fail, 41%-60% pass, 61-80% merit, and 81%+ a distinction.

Other Boolean commands are:

> Greater than


< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Greater than or equal to

Not working?
Check the spelling, gaps, and punctuation marks
Maths in Python Applying this information write a programme to work out the answers to these questions:
Maths in python is easy, you just need to know: The total cost of money spent on lunch over 5 days, based on the cost of the lunch bill on
one day:
+ = add
- = subtract
• = multiply
/ = divide An Aunt wins on the lottery. She gives £1000 to you. You are thinking of sharing it with
% = modulus some of your family. How much would each person get (try this with different numbers in
your family)
Modulus
If we divide two numbers and they don’t divide evenly we
get a remainder. Modulus gives us the remainder of a sum. From your £1000 you have decided to share it between you, your sister and your brother. If
For example 7/2 = 3 with remainder 1. This would be typed it is shared equally as an integer, how much is left over?
in as

Print(7%2)

Challenge: Copy your code here:

Applying your understanding of using maths, write a problem to solve the


following questions:
1. Two people eat dinner at a restaurant and want to split the bill.
2. The total comes to £100 and they want to leave a 15% tip. How much
should each person pay?
3. Make the program ask how many people there are, what percentage the
tip should be and how much the bill comes to

Explain how it works:

Not working?
Check the spelling, gaps, and punctuation marks
Hashtags, import, random and range Consider and explain what the following parts of the code do:

Type in this code and run it:


#

# this programme creates a random number between 1 and 10


# the user guesses the number. It ends when the user guesses the number correctly
import random
guess ="" Import random
print("I've thought of a number between 1 and 10. Try to guess it.")
randomNumber = random.randrange (1,10)
# this loop runs until the number guessed equals the randomNumber
while guess != randomNumber: Random.randrange(1,10)
guess = int(input("Guess the number“))
print("You got it wrong")
input("Well done. Press any key to exit.“)

Explain how the code works:

Not working?
Check the spelling, gaps, and punctuation marks
Making decisions in programmes Not working?
Python can make decisions based on the input. To make decisions, programs check Check the spelling, gaps, and punctuation marks
to see if a condition is true or not.
Python has a few ways to test something, and there are only two possible answers
for each test: true or false
Complete the table explaining what each line does
Type in and run the following code to make a magic 8 ball:
Programme Explain what each line does
import random import random
answer1= ("Absolutely!") answer1=(“Absolutely!”)
answer2= ("No way Pedro!")
answer3= ("Go for it tiger.") answer2=(“No way Pedro!”)
print("Welcome to the Magic 8 Ball game—use it to answer answer3=(“Go for it tiger.”)
your questions...") print(“Welcome to the Magic 8 Ball
question = input("Ask me for any advice and I’ll help you out.
Type in your question and then press Enter for an answer.") game—use it to answer your
questions...”)
print("shaking.... \n" * 4)
choice=random.randint(1,3) question = input(“Ask me for any
if choice == 1: advice and I’ll help you out. Type in
answer=answer1
elif choice == 2: your question and then press Enter
answer=answer2 for an answer.”)
else:
answer=answer3 print(“shaking.... \n” * 4)
print(answer)
choice=random.randint(1,3)

if choice == 1:
What happens?
answer=answer1
elif choice == 2:
Easy? Develop the programme so it contains 5 different
answer=answer2
answers.
else:
Challenge 5
Applying the knowledge gained so far, complete ONE of the tasks below: Copy your code here:

1. Write a program in python which asks the user how many hours they slept last
night and remembers their answer. Then if the answer is less than 4 print “Back
to bed”, and if the answer is 7 or less print “Not bad”, otherwise print “Well done”
 
2. Write a program in python which asks the user how old they are. If they are
over 16 but under 18 ask if they are at work or college or sixth form and display
the result. If they are over 18 ask a question about driving lessons and display the
results. If they are 16 or under, ask a question about GCSE courses and display
the results.
 
3. Write a program in python which asks the user how they got to school today and
displays their answer plus a comment about their choice of travel. Make sure you
have covered the options of walking, getting the tram, getting the bus or traveling
by car. Think about how to make allowances for users not writing an answer you
expect.

Explain how it works:

Not working?
Check the spelling, gaps, and punctuation marks
Challenge 6
Applying the knowledge gained so far, complete ONE of the tasks below: Copy your code here:

1. A local shop is having a promotion. If you spend over £10 you will get a £1
voucher to spend next time you come in the store. If you spend over £20 you get a
£3 voucher.
Write a programme to tell the sales assistant which voucher to give the customer.

2. Write a programme that gives users a message depending upon how happy they
say they are.
You could get the user to rate how happy they feel on a scale between 1 and 10. If
the reply is 3 or less it gives one message.
Between 4 and 7 (including these numbers) they get another message.
8 and above they get a different message.
Try to make the messages ones to make them happy all day long!

3. You want to see how much a mobile phone will cost. There are charges for
sending pictures (£0.35), for texts (£0.10) and for data (£2.50 for 500MB).
Write a program that asks the user for how many pictures, texts and data they
would use each month. It should then calculate a total bill for the month.
If the total comes to more than £10 they would be better on a contract. Get the
programme to give them this advice.
Explain how it works:
4. Make a program where the user has to enter a secret password to use the
programme.
The programme could be one you’ve already written, or make it display a message
when they have got the password correct.

Not working?
Check the spelling, gaps, and punctuation marks
For loops
Not working?
Sometimes we want to do something a number of times.
Check the spelling, gaps, and punctuation marks
We may know how many times we want to do it – and we use a counting loop
OR
We may want to do it until something happens – and then we can use a
conditional loop.

Conditional Loops

These are the simplest loops. Test these and explain what they do

for a in range (10): Explain what this does


print(a)

for a in range (1, 10): Explain what this does


print(a)

for a in range (1, 11): Explain what this does


print(a)

for a in range (1, 11,2): Explain what this does


print(a)

Annotate and explain what each of the numbers tells the loop:
for a in range (1, 11,2):
Applying your understanding, write a loop which
• displays numbers 10 to 100 in steps of 5.
• displays the 5 times table
While loops
This programme should be familiar to you apart from the while loop. Type in the code, run it then
explain what each line does.
Explain what each line in this code does next to it
import random
guess =""
print ("I've thought of a number between 1 and 10. Try to guess it.")
randomNumber = random.randrange (1,10)
while guess != randomNumber:
guess = int(input("Guess the number"))
print("You got it wrong")
input ("Well done. Press any key to exit.")

The while loop repeats whist the conditions is TRUE.


In this case this is when guess is NOT equal to randomNumber Explain why is the int necessary?
guess = int(input("Guess the number"))

Easy?.
Can you make the programme show how many guesses have been taken?

Try this code. Explain what happens: Explain what happens in this code:

import random
print ("you will be given something that will help you out of here but it’s not as easy as you think")
selection = random.choice(["key","sword","rope"])
if selection == ("key"):
print ("here is your key use it wisely as it only opens one door")
elif selection == ("sword"):
print ("here is your sword incase you run into some trouble use it wisley as it might break")
elif selection == ("rope"):
print ("here is a rope find where to use as it will come in use one time")
else:
print ("bye")
Not working?
Check the spelling, gaps, and punctuation marks
Challenge 7 Copy your code here:
Applying your understanding write a code to play the rock, paper, scissors
game. The computer will play against you.

Get the computer to ask for the player’s name.


The game rules are simple: rock beats scissors, scissors beat paper, paper
beats rock. Two of the same gives a draw.

Hints:
Look at the while loop code.

Try the initial lines:

import random
selection=random.choice(["rock","paper","scissors"])
print (selection)

Easy?
Ask the user how many rounds they want to play, between 3 and 10.
Keep score and show this at the end of the game.
 
Or Check to make sure the user can only enter a number between 3 and 10
and give them an error message.

Explain how this code works.

Not working?
Check the spelling, gaps, and punctuation marks
Using AND and OR

You can represent more complicated options using AND and OR

For example:
x=45 x=45 x=45 x=45
while x<50: while x >45 and x<47 while x<50 and x<47 while x<50 or x<47
x=x+1 x=x+1 x=x+1 x=x+1
Print (x) print (x) print (x) print (x)

Type in and test each one:

What does it return?

Explain how does it work

Not working?
Check the spelling, gaps, and punctuation marks
Nested Loops
With a times table we start with a number and then multiply this by a series of
numbers. Not working?
For the 2 times table we multiply it by 1 to 12, before moving on to do the 3 times Check the spelling, gaps, and punctuation marks
table, etc.

Computers are very good at this sort of task and we can do it using loops within loops
to consider every combination – these are called NESTED LOOPS.

Read through the code below. Explain what you think it will do. Explain what you think the code does?
Type in the code and run it

for i in range(1,13):
print (i, "Times table\n")
for j in range (1,13):
print (i, "times", j, " = ", i*j)

How does it work?


for i in range(1,13): i is the first number we are going to x by
print (i, "Times table\n") prints the number of the table we are multiplying
for j in range (1,13): loops through the number we are multiplying it by
print (i, "times", j, " = ", i*j) prints the results

Now Copy your program here


Applying your understanding of nested loops, produce a program that works out
combination of ingredients in a chicken wrap. The ingredients are tortilla, chicken,
salad, and chilli's sauce. Run the code below and adapt it to show all ingredients

print("\tTortilla \tChicken \tSalad \tChilli Sauce")


count=1
for tortilla in (0,1):
for chicken in (0,1):
print("#", count) Explain how it works
print ("\t\tt",tortilla, "\t\t\", chicken )
count =count+1
N.B. The \t aligns the columns and data
Functions
Programming languages have pre-made functions for us to use. Python has some such
as print() or random.
But we can make our own functions, these are called user-defined functions:
A function is a block of organised, reusable code that is used to perform a single
action.
By using functions we can make our programs modular (made up of separate parts)
and simpler, because we don’t have to write the same instructions many time but
reuse the same code.

We will now use this technique to work out area and perimeter of a rectangle. N.B to work out the area and perimeter of a rectangle, the following sums apply:
Area = length * width
We will define the area under the function name shapeArea(). When we want to call Perimeter = length *2 + width *2
the function up, after we defined it, we can then use the term shapeArea()

Type in and run the code below:


Explain how the code works:
length = 200
width = 100
def shapeArea():
shapeArea = length * width
print("Area = ",shapeArea)
shapeArea()
Applying this theory, produce a program which will define the function of
shapePerimeter. Copy this below:
Explain how this code works.

Applying this theory, produce a programme that can define the function of the
perimeter. Call this shapePerimeter

Not working?
Check the spelling, gaps, and punctuation marks
Type in and run the program below. Explain what each line does:
Explain why do you think the functions are defined first?
Programme Explain what each line does  

length = 200
width = 100
def area():
shapeArea = length * width
print("Area = ",shapeArea)
Explain what would happen if the user input were first?
def perimeter():
shapePerimeter = length*2 +
width*2
print ("Perimeter = ",
shapePerimeter)
response =input("Do you want to
calculate area or perimeter? Enter a
or p")
if response =="a":
area()
elif response =="p":
perimeter()

Develop this programme to:


Have the programme ask the user to input their own measurements.

Applying your understanding, produce a programme which works out the


volume of a cuboid

To work out the volume of a regular cuboid shape is:


length * width * height Not working?
Check the spelling, gaps, and punctuation marks
Lists
A list is different to a string or an array in that it allows you to identify and Not working?
manipulate individual elements of a variable. Check the spelling, gaps, and punctuation marks

A list is denoted using the [ ] brackets.


Example :

fruit=[“apple”, “banana”, “pear”]

The numbering system used by lists is also a bit odd in that it starts counting at
0.
In the example above apple would be fruit[0] – this is the 1 st item in the list, pear
Type in this code and run it. Annotate and explain what each part of the
would be fruit[2] - this is the 3 rd item in the list
code and explain how it works:
 
In python, lists have some built in functions

We have looked at len when we were looking at strings. numbers= [5, 4, 10, 30, 22]
print(len(numbers))
numbers= [5, 4, 10, 30, 22]
print(len(numbers))

Test the following codes, explaining what each function does: Explain what happens?

Max
numbers= [5, 4, 10, 30, 22]
What does max do?
print(max(numbers))

Min Explain what happens?


numbers= [5, 4, 10, 30, 22]
print(min(numbers))
What does min do?
Change
Explain what happens?
numbers= [5, 4, 10, 30, 22]
numbers[2]=77
print(numbers) What does numbers[2]=77 do?

Delete Explain what happens?

numbers= [5, 4, 10, 30, 22]


del numbers[2]
print(numbers) What does del numbers[2] do?

Clear
Explain what happens?
numbers =[5, 4, 10, 30, 22]
del numbers[0:5]
print(numbers)
What does del numbers[0:5] do?

Append
Explain what happens?
numbers=[5, 4, 10, 30, 22]
numbers.append(45)
print(numbers) What does del numbers[0:5] do?

Extend
Explain what happens?
one = [1,2,3]
two =[4,5,6]
one.extend(two) What does one.extend do?
print(one)
Index
Explain what happens?
a=["hey", "now", "brown", "cow"]
print(a.index("brown"))
What does a.index do?

Insert
Explain what happens?
a=["hey", "now", "brown", "cow"]
a.insert(2, "horse")
print(a)
What does a.insert do?
Pop

a=["hey", "now", "brown", "cow"]


a.pop(1) What does a.pop(1) do?
print(a)

Reverse
a=["hey", "now", "brown", "cow"] What does a.reverse() do?
a.reverse()
print(a)

Remove
a=["hey", "now", "brown", "cow"] What does a.remove do?
a.remove("brown")
print(a)

Not working?
Check the spelling, gaps, and punctuation marks
Making use of the list index
Not working?
Lists can sometimes be very long so there are a number of index features to make
Check the spelling, gaps, and punctuation marks
lists more helpful
Remember the index counter in lists starts at 0 so the third item in a list is
indexed as [2]
Explain what happens
Type in the following code.
names=["Alf","Betty","Charlie","David"]
print(names[2]) How can you get it to return the name David?

Explain what happens with all these commands


Explain what happens with the following commands
names=["Alf","Betty","Charlie","David"]
print(names[2:3])

names=["Alf","Betty","Charlie","David"]
print(names[2:4])

names=["Alf","Betty","Charlie","David"]
print(names[-3:-1])

names=["Alf","Betty","Charlie","David"]
print(names[-3:])

names=["Alf","Betty","Charlie","David"]
print(names[:2])

names=["Alf","Betty","Charlie","David"]
print(names[:])

names=["Alf","Betty","Charlie","David"]
print(names[0:3:2])
Challenge 8
Explain what this code does:

listOne =[128,64,32,16,8,4,2,1]
listTwo =[1,0,1]
result =listOne[0]*listTwo[0]
print(result)

Not working?
Check the spelling, gaps, and punctuation marks

You might also like