ks3python
ks3python
Copyright Notice
All material is Copyright ICT Interactive unless otherw is e stated. Each worksheet can be photocopied
within the purchasing institute as long as they remain at the institute which made the initial purchase.
No form of this resource can be transmitted electronic ally, digitally, mechanically, paper based, or
otherwise outside the purchasing institute w ithout prior permission of the publisher or author.
Microsoft Windows, Windows NT, Vista, XP, Seven/Eight, Ten, Offic e 2003, Office 2007/2010 and/or
other Microsoft's products referenced are either trademarks or registered trademarks of Microsoft.
Macromedia/Adobe and/or other such Adobe products referenced are either trademarks or registered
trademarks of Adobe.
Disclaimer
The publisher or author has tried their very best to ensure that the resource pack is accurate and up-
to-date. However, the publisher or author takes no responsibility if any of the information content is
inaccurate or incorrect that may contradict or mislead in anyway at the time w hen the resource was
published. The publisher and author specif ically dis claim any responsibility for any liability, loss, or
risk, personal or otherwise, which is incurred as a consequence, directly or indirectly, of the use and
application of any of the contents of this [Link] purposes of illustrating the content and
techniques described in this resource, the author has created variety of names, company names,
mailing, e-mail and internet addresses, phone and fax numbers and similar information, all of w hic h
are fictitious. Any organiz ation, website or software application referenced in this resource is not an
endorsement by the publisher or author. Any websites referred to within this resource may have
changed at the time of publishing and reading of this resource.
The publisher or author cannot guarantee that the content in the resource w ill help, assist and
progress the learning of the purchaser and/or institute including students/learners/teachers in any
formal or informal exams or coursework practices. The purchasers own self judgement must be used
to ensure information is understood, delivered, used responsibly, appropriately and effec tively . It is
the sole discretion and responsibility of the subject teacher/purchaser who will determine how , when
and decide the best method of using the resource pack relating to any form of examination,
coursework or lesson/class.
Every effort has been made to ensure all images are acknowledged and referenced accordingly. ICT
Interactive will be happy to amend any details or make special arrangements to whom copyright
holder has not been contacted.
ICT Interactive is not affiliated w ith AQA, OCR, Edexcel or any other exam board or priv ate/corporate
institute.
Acknowledgement
The content in the book refers to either a specif ication or softw are application and all intellectual
property rights of the software/specif ication are owned by that institute/organis ation. The publisher or
author neither accepts responsibility of ownership of the softw are application and/or specific ation as
their own.
For further details of Acknowledgements/Disclaimers please refer to the ICT Interactive website.
2
KS3 COMPUTING
2.5 Python Variables 41
2.5 Python Variable Types 42
2.7 Python IF Statement 43
2.8 Python Functions 44
2.9 Python Functions with Arguments 45
2.10 Python For Loops 46
2.11 Python While Loops 47
2.12 Python Strings 48
2.13 Python Common Strings Methods 49
2.14 Python String Indexes 50
2.15 Python Lists 51
2.16 Python Common Lists Methods 52
2.17 Python Tuples 53
2.18 Python Dictionary 54
2.19 Python Formatting 53
2.20 Python Exceptions 55
2.21 Python Reading to a File 56
2.22 Python File Reading Methods 57
2.23 Python Writing to a File 58
2.24 Python Classes 59
2.25 Python Testing 60
2.26 Python Complier 61
2.27 Python Interpreter 62
Python Answers
3
KS3 COMPUTING
THANK YOU FOR PURCHASING THIS RESOURCE
ICT I nteractive would like to thank you very much for purchasing this resource. We
hope you are fully satisfied w ith this resource.
This resource pack has been designed to help students learn and support teachers
in delivery of Python at KS3-5
Summary Disclaimer
The publisher or author cannot guarantee that the content in the resource pack
will help, assist and progress the learning of the purchaser and/or institute including
students/learners/teachers in any formal or informal exams or coursework
practices. The purchasers own self judgement must be used to ensure information
is understood, delivered, used responsibly, appropriately and effectively. I t is the
sole discretion and responsibility of the subject teacher w ho w ill determine how,
when and decide the best method of using the resource pack relating to any form
of examination, coursework or lesson/class.
Feedback
Request a Resource
Register your email to receive free future updates and other resources from I CT
Interactive
4
KS3 COMPUTING
Suggested Resources
KS4 Python Resource Pack has been professionally designed and developed as a
natural progress from the KS3 Python Resource Pack. This resource is ideal for an
students to build upon their existing KS3 Python Programming skills when starting the
GCSE Computer Science Qualification. The resource pack is ideal for guidance and
support with the NEA for ALL exam boards.
5
KS3 COMPUTING
This Resource
This resource pack has been specifically designed and developed to support and assis tance in
the delivery of Python at Key Stage 3. The resource pack contains actually activities and
worksheets that provide a range of activities catering for all learning styles. The worksheets can
be used as starter, main, plenary or homework sheets. There are a series of assignment and
tasks that introduce the programming language which students can follow.
1. Python environment.
2. Python commands, syntax, code and use.
3. How to create python programs
How to use:
The KS3 Python resource pack is ideal for Y7-9 students learning Python programming at Key
Stage 3.
The model assignments of 10 programs for students to develop are ideal for Year 9 students after
they have had some experience of Python coding. The activities assignments are suitable for
students in Year 7 and year 8.
What is Python?
Python is a programming language that lets you work more quickly and integrate your
systems more effectively. You can learn to use Python and see almost immediate gains in
productivity and lower maintenance costs. Python runs on Windows, Linux/Unix, Mac OS X,
and has been ported to the Java and .NET virtual machines.
Python is free to use, even for commercial products, because of its OSI-approved open
source license.
The Python Software Foundation holds the intellectual property rights behind Python,
underwrites the PyCon conference, and funds many other projects in the Python community.
Please visit:[Link]
6
KS3 COMPUTING
Python
Model Assignments
7
KS3 COMPUTING
Model Assignment 1: Python Programs
Activity
Before you begin, make sure you are using Python V3 and that you save your programs in PY
extension before you run your program.
Tasks
1. Write a Python program to print the calendar of a given month and year.
Note: Use 'calendar' module.
4. Write a Python program to get the difference between a given number and 17, if the number
is greater than 17 return double the absolute difference.
5. Write a Python program to test whether a number is within 100 of 1000 or 2000.
6. Write a Python program to calculate the sum of three given numbers, if the values are equal
then return thrice of their sum.
8. Write a Python program to display your details like name, age, address in three different lines
10. Write a Python program to find out the number of CPUs using
Notes:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
8
KS3 COMPUTING
Model Assignment 2: Python Programs
Activity
Before you begin make sure you have using Python Version 3 and that you save your programs
within the file extension py before executing your program.
Tasks
1. Write a Python program which accepts the user's first and last name and print them in reverse
order with a space between them
2. Write a Python program to print the calendar of a given month and year.
4. Write a Python program to get the difference between a given number and 17, if the number
is greater than 17 return double the absolute difference
5. Write a Python program which accepts a sequence of comma-separated numbers from user
and generate a list and a tuple with those numbers
6. Write a Python program to test whether a number is within 100 of 1000 or 2000
7. Write a Python program to calculate the sum of three given numbers, if the values are equal
then return thrice of their sum.
10. Write a Python program to accept a filename from the user and print the extension of that.
Notes:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
9
KS3 COMPUTING
Python
Practise assignments
10
KS3 COMPUTING
Activity 1: Hello World
Activity
In this task you are going to create a simple python program that prints
“hello world” on the computer screen.
Remember appropriate indentations and to save with py extension, then run your program.
print('Hello, world!')
print('Hello, my school!')
Tasks
3. Add to the program by adding your class, tutor name and your best friend’s name
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
11
KS3 COMPUTING
Activity 2: Twinkle
Activity
In this task you are going to create simply calculation using Python.
print("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!")
Tasks
4. Improve the code to ask a user for their preferred nursery rhyme.
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
2. What other commands can you use to make the code more efficient?
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
3. What commands can you include storing a user input into this program?
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
12
KS3 COMPUTING
Activity 3: Performing Calculations
Activity
In this task you are going to create simply calculation using Python.
2+5
11+12
1+6
234+890
a=2
b=3
sum = a + b
print(sum)
Tasks
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
2. Compare the two methods and decide which ones is most appropriate and why?
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
13
KS3 COMPUTING
Activity 4: More Calculations
Activity
In this task you are going to create simply calculation using Python command line.
Remember appropriate indentations and to save with py extension, then run your
program.
sum = a + b + c + d + e
print(sum)
num1 = 3
num2 = 5
sum = num1+num2
print(sum)
Tasks
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
14
KS3 COMPUTING
Activity 5: Adding Numbers
Activity
In this task you are going to create simply calculation program by adding two numbers
provided by the user.
Remember appropriate indentations and to save with py extension, then run your program.
Tasks
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
15
KS3 COMPUTING
Activity 6: Odd and even numbers
Activity
In this task you are going to create simply calculation program which determines
if a number is odd or even based on a user input.
Remember appropriate indentations and to save with py extension, then run your program.
mod = num % 2
if mod > 0:
else:
Tasks
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
16
KS3 COMPUTING
Activity 7: number Checker
Activity
In this task you are going to create simply calculation program which checks a number
from a user input.
Remember appropriate indentations and to save with py extension, then run your program.
if num % 4 == 0:
print(num, "is a multiple of 4")
elif num % 2 == 0:
print(num, "is an even number")
else:
print(num, "is an odd number")
if num % check == 0:
print(num, "divides evenly by", check)
else:
print(num, "does not divide evenly by", check)
Tasks
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
2. Name the variables used in this program and define their content:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
17
KS3 COMPUTING
Activity 8: What’s Your Name
Activity
In this task you are going to create a simple python program that prints
“What’s your name”. and returns a string.
Remember appropriate indentations and to save with py extension, then run your program.
Tasks
1. Create a simple program that asks for your age and prints the age
2. Add to the program, when you were born and print the date
3. Add to the program, name of your school and prints the name of your school
4. Add to the program, the class you are in and prints the class name
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
18
KS3 COMPUTING
Activity 9: Hello World/what’s your name
Activity
In this task you are going to create a simple python program that combines
Hello world and what’s your name”.
Remember appropriate indentations and to save with py extension, then run your program.
print('Hello, world!')
Tasks
2. Include the a message that asks “how are you today” and replies “I am fine”
Questions
...........................................................................................................................................................
...........................................................................................................................................................
2. Which command is used to store the response and enter the name?
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
19
KS3 COMPUTING
Activity 10: What’s Your Age
Activity
In this task you are going to create a simple python program that prints
“What’s your age and how old you will be in an 100 years.
Remember appropriate indentations and to save with py extension, then run your program.
print(name + " will be 100 years old in the year " + year)
Tasks
1. Create a simple program that asks for your age and prints the age
2. Improve the program, by adding, when you were born and print the date
3. Add to the program, name of your school and print the name of your school
4. Add to the program, the class you are in and print the class name
Questions:
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
20
KS3 COMPUTING
Activity 11: Find the Square Root
Activity
In this task you are going to create simply calculation that finds the square root.
Remember appropriate indentations and to save with py extension, then run your program.
num = 8
Tasks
Questions:
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
21
KS3 COMPUTING
Activity 12: Guess the Number
Activity
In this activity you are going to create a simple python game called guess the number.
Remember appropriate indentations and to save with py extension, then run your program.
number = 7
guess = -1
if guess == number:
print("Well Done! You guessed it right!")
elif guess < number:
print("It's bigger...")
elif guess > number:
print("It's not so big.")
Tasks
Questions:
1. Name and explain the command used for a loop in the above code?
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
22
KS3 COMPUTING
Activity 13: Division Number
Activity
In this activity you are going to create a simple python program that asks
the user for a number and then prints out a list of all the divisors of that number.
Remember appropriate indentations and to save with py extension, then run your program.
listRange = list(range(1,num+1))
divisorList = [ ]
if num % number == 0:
[Link](number)
print(divisorList)
Tasks
Questions:
1. Name and explain the command used for a loop in the above code?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
23
KS3 COMPUTING
Activity 14: Rock. Paper, Scissors
Activity
In this activity you are going to create a simple python for the rock, paper,
scissors game Remember appropriate indentations and to save with py extension,
then run your program.
import sys
print(compare(user1_answer, user2_answer))
Tasks
24
KS3 COMPUTING
Activity 15: Hangman
Activity
In this activity you are going to create a python program which is the
hangman game.
import random
def choose_random_word():
words=[]
with open('[Link]', 'r') as file:
line = [Link]()
while line:
[Link](line. replace("\n","".strip()))
line = [Link]()
choice=words[[Link] (0,len(words)-1)]
return choice
print("Welcome to Hangman!")
secret_word=choose_random_word()
dashes=list(secret_word)
display_list=[]
for i in dashes:
display_list.append("_")
count=len(secret_word)
guesses=0
letter = 0
used_list=[]
while count != 0 and letter != "exit":
print(" ".join(display_list))
letter=input("Guess your letter: ")
if [Link]() in used_list:
print("Oops! Already guessed that letter.")
else:
for i in range(0,len(secret_word)):
if [Link]() == secret_word[i]:
display_list[i]=[Link]()
count -= 1
guesses +=1
used_list.append([Link]())
if letter == "exit":
print("Thanks!" )
else:
print(" ".join(display_list))
print("Good job! You figured that the word is "+secret_word+" after guessing %s letters!" % guesses
Tasks
25
KS3 COMPUTING
1. Python: Basics
Activities and Worksheets
26
KS3 COMPUTING
Name……………………………… Class…………….........
1. What is python?
............................................................................................................................................................
........................................................................................................................................................[2]
........................................................................................................................................................[1]
Name ………………………………
3. Explain how Python Interpreter type of language: Class…………….........
1.3............................................................................................................................................................
Python benefits
........................................................................................................................................................[2]
Python can be used to develop prototypes, and quickly because it is so
4. Name to
easy work with and
organisations whichread. use Python:
Most automation, data mining, and big data platforms rely on Python. This
is because it is the ideal language to work with for general purpose tasks.
........................................................................................................................................................[1]
Python allows for a more productive coding environment than massive
languages
5. Give like C# and
two advantages forJava.
the use Experienced
of Python:coders tend to stay more organized and
productive when working with Python, as well.
Python1is easy to read, even if you're not a skilled programmer. Anyone can begin
Advantage
working with the language, all it takes is a bit of patience and a lot of practice. Plus, this
makes it an ideal candidate for use among multi-programmer and large development
............................................................................................................................................................
teams.
It has a massive support base thanks to the fact that it is open source and community
........................................................................................................................................................[1]
developed.
Advantage 1
............................................................................................................................................................
........................................................................................................................................................[1]
27
KS3 COMPUTING
Name……………………………… Class…………….........
One of the most important things you'll do when working with any programming
language is setup a development environment which allows you to execute the
code you write. Without this, you will never be able to check your work and see
if your website or application is free of syntax errors. With Python, you also need
something called an interpreter that converts your code - which makes up the
entirety of your application - to something the computer can read and execute. Without this
interpreter, you'll have no way to run your code.
To convert your code, you must first use a Python shell, which calls upon the interpreter through
something called a "bang" line.
QUESTIONS
1. Explain the Python Environment:
...........................................................................................................................................................
....................................................................................................................................................... [1]
....................................................................................................................................................... [1]
...........................................................................................................................................................
....................................................................................................................................................... [1]
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
28
KS3 COMPUTING
Name……………………………… Class…………….........
Both Ruby and Python share a significant amount of growth in the job market, so choosing either
language would be beneficial in terms of a career. PHP is also used often though the application
is different.
QUESTIONS
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [1]
....................................................................................................................................................... [1]
...........................................................................................................................................................
....................................................................................................................................................... [1]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
29
KS3 COMPUTING
Name……………………………… Class…………….........
QUESTIONS
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
30
KS3 COMPUTING
Name……………………………… Class…………….........
The following identifiers are used as reserved words, or keywords of the language,
and cannot be used as ordinary identifiers. They must be spelled exactly as written
here:
QUESTIONS
1. Explain the purpose for reserved words in Python:
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
31
KS3 COMPUTING
Name……………………………… Class…………….........
There are many reserve words in Python which are important. These reserve
words are used to create programs.
Activity
1. Name as many different reserve words in Python as you can think of: [6] (First
one has been completed for you)
32
KS3 COMPUTING
Name……………………………………… Class…………….........
1. Explain how the following reserved words in Python; give an example of use [4]
Elif
Import
Pass
33
KS3 COMPUTING
Name……………………………………… Class…………….........
1. Python is a
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
4. Loops are
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
8. An example of a variable is
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
...........................................................................................................................................................
34
KS3 COMPUTING
2. Python: Commands
Activities and Worksheets
Name……………………………………… Class…………….........
With every programming language we have our operators, and Python is no different. Operators
in a programming language are used to vaguely describe 5 different areas: arithmetic,
assignment, increment/decrement, comparison, 35 logical. There isn't really much need to explain
all of them as I have previously in the other categories, which means we will only cover a few of
them. For example
KS3 COMPUTING
Name……………………………………… Class…………….........
A Python identifier is a name used to identify a variable, function, class, module, or other object.
An identifier starts with a letter A to Z or a to z, or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @,
$, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower
and manpower are two different identifiers in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
Starting an identifier with a single leading underscore indicates that the identifier is
private.
Starting an identifier with two leading underscores indicates a strongly private
identifier.
Questions
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
36
KS3 COMPUTING
Name……………………………………… Class…………….........
A comment begins with a hash character(#) which is not a part of the string literal and ends at
the end of the physical line. All characters after the # character up to the end of the line are part
of the comment and the Python interpreter ignores them. See the following example. It should be
noted that Python has no multi-lines or block comments facility. For example
# First comment
print "Hello, Python!"; # second comment
Questions
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
37
KS3 COMPUTING
Name……………………………………… Class…………….........
When you want to write a long code in a single line you can break the logical line in two or more
physical lines using backslash character(\). Therefore when a physical line ends with a
backslash characters(\) and not a part of a string literal or comment then it can join another
physical line. See the following example.
Questions
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [4]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
38
KS3 COMPUTING
Name……………………………………… Class…………….........
Python uses whitespace (spaces and tabs) to define program blocks whereas other languages
like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow control. The
number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within
the block must be the indented same amount. For example:
if True:
print "True"
else:
print "False"
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [4]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
39
KS3 COMPUTING
Name……………………………………… Class…………….........
In the heart of every good programming language, including Python, are the variables. Variables
are an awesome asset to the dynamic world of the web. Variables alone are dynamic by nature.
However, Python is pretty smart when it comes to variables, but it is sometimes quite a pain.
Python interprets and declares variables for you when you set them equal to a value. Example:
a=0
b=2
print(a + b)
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
40
KS3 COMPUTING
Name……………………………………… Class…………….........
What is that int() thing? This is how you cast one variable type into another. In this example, we
cast the string 0 to an integer 0. Let's take a quick peak at a few of the important variable types
in Python:
a = "0"
b=2
print(int(a) + b)
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
[2]
41
KS3 COMPUTING
Name……………………………………… Class…………….........
In the heart of programming logic, we have the if statement in Python. The if statement is a
conditional that, when it is satisfied, activates some part of code. Often partnered with the if
statement are else if and else. However, Python's else if is shortened into elif. If statements are
generally coupled with variables to produce more dynamic content. For example:
a = 20
if a >= 22:
print("if")
else:
print("else")
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
42
KS3 COMPUTING
Name……………………………………… Class…………….........
Functions in Python are super useful in separating your code, but they don't stop there. Any
code that you think you will ever use anywhere else, you should probably put in a function. You
can also add arguments to your functions to have more flexible functions, but we will get to that
in a little bit. You can define a function by using the keyword def before your function name. Let's
use our first Python function.
def someFunction():
print("boo")
someFunction()
It is necessary to define functions before they are called. Even though we have to skip over the
function while reading to see the first statement, someFunction(). This throws us back up into the
def someFunction():, again with a colon following it. Then after we acknowledge that the function
is being called, we create a new line with four spaces for our simple print statement.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
43
KS3 COMPUTING
Name……………………………………… Class…………….........
Simple functions like the one above are great and can be used quite often. However, there
usually comes a time where we want to have the function act on data that the user inputs. We
can do this with arguments inside of the () the follows the function name.
print(a+b)
someFunction(12,451)
Using the statement someFunction(12,451), we pass in 12, which becomes a in our function,
and 451, which becomes b. Then, we just have a little print statement that adds them and prints
them out.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
44
KS3 COMPUTING
Name……………………………………… Class…………….........
It's time for an awesome part of Python. Python's for loops are pretty amazing compared to
some other languages because of how versatile and simple they are. The idea of a for loop is
rather simple, you will just loop through some code for a certain number of times. I won't get a
chance to show you the flexibility of the for loops until we get into lists, but sure enough its time
will come. Onto an example
for a in range(1,3):
print (a)
First, print is indented for a reason. Remember that Python is picky about spacing. It is
somewhat complicated to understand exactly what a is in the example. In this instance, a is a
variable the increments itself every time we run through the loop. Next, we use the range
keyword to set the starting point and the point right after we would finish.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [4]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
45
KS3 COMPUTING
Name……………………………………… Class…………….........
While loops in Python can be extremely similar to the for loop if you really wanted them to be.
Essentially, they both loop through for a given number of times, but a while loop can be more
vague. Generally, in a while loop you will have a conditional followed by some statements and
then increment the variable in the condition. Let's take a peek at a while loop really quick:
a=1
while a < 10:
print (a)
a+=1
We have our conditional of a < 10 and a was previously declared and set equal to 1. So, our first
item printed out was 1, which makes sense. Next, we increment a and ran the loop again. Of
course, once a becomes equal to 10, we will no longer run through the loop.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
[2]
46
KS3 COMPUTING
Name……………………………………… Class…………….........
As with any programming language, strings are one of the most important things to know about
Python. Also as we have experienced in the other languages so far, strings contain characters.
Strings are not picky by any means. They can contain almost anything if used properly. They are
also not picky by the amount of characters you put in them. For example:
myString = ""
print (type(myString))
The type() is awesome. It returns the variable type of whatever is inside the parentheses, which
is very useful if you have a few bugs that you can't figure out or if you haven't looked a large
chunk of code for awhile and don't know what type the variable is.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
47
KS3 COMPUTING
Name……………………………………… Class…………….........
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
48
KS3 COMPUTING
Name……………………………………… Class…………….........
One of the really cool things about Python is that almost everything can be broken down by
index and strings are no different. With strings, the index is actually the character. You can grab
just one character or you can specify a range of characters.
a = "string"
print (a[1:3])
print (a[:-1])
Let's discuss the print (a[1:3]) because it is the easiest to explain. Remember that Python starts
all indexes from 0, which would have been the 's' in our variable a. So, we print out 'tr' because
we printed everything up to our range of 3, but not 3 itself.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
49
KS3 COMPUTING
Name……………………………………… Class…………….........
We don't have arrays; we have Python lists. Lists are super dynamic because they allow you to
store more than one "variable" inside of them. Lists have methods that allow you to manipulate
the values inside them.
sampleList = [1,2,3,4,5,6,7,8]
print (sampleList[1])
The brackets are just an indication for the index number. Like most programming languages,
Python's index starting from 0. So, in this example 1 is the second number in the list. Of course,
this is a list of numbers, but you could also do a list of strings, or even mix and match if you
really wanted to (not the best idea though).
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
50
KS3 COMPUTING
Name……………………………………… Class…………….........
There are number of methods for lists, but we will at least cover how to add and delete items
from them. All of the list methods can be found on Python's documentation website. Methods
follow the list name. In the statement [Link](2), append() is the method.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
51
KS3 COMPUTING
Name……………………………………… Class…………….........
In Python, tuples are almost identical to lists. So, why should we use them you ask? The one
main difference between tuples and lists are that tuples cannot be changed. That is to say you
cannot add, change, or delete elements from the tuple. Tuples might seem odd at first, but there
is a great reason behind them being immutable. As programmers, we mess up occasionally. We
change variables that we didn't want to change, and sometimes, well, we just want things to be
constant so we don't accidentally change them later. However, if we change our minds we can
also convert tuples into lists or lists into tuples. The fact is we need to make the conscious effort
to say Python,
myTuple = (1,2,3)
myList = list(myTuple)
[Link](4)
print (myList)
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
52
KS3 COMPUTING
Name……………………………………… Class…………….........
Python's dictionaries are not very common in other programming languages. At least at
first, they don't appear normal. Some super variables like lists, arrays, etc, implicitly have
an index tied to each element in them. Python's dictionary has keys, which are like these
indexes, but are somewhat different (I'll highlight this in just a second). Partnered with
these keys are the actual values or elements of the dictionary. For example:
print(myExample['otherItem'])
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
53
KS3 COMPUTING
Name……………………………………… Class…………….........
We waited a little bit to talk about formatting because it might get a little intense with how much
you can do and how easily you can do things with variables in Python. Formatting in Python is a
little bit odd at first. But, once you get accustomed to it, you'll be glad you did.
The f following the first % is short for float here because we have floating numbers and Python
has a specific way of dealing with formatting decimals. The left % tells Python where you want to
put the formatted string. The value following the right % is the value that we want to format. So,
Python reads through the string until it gets to the first % then Python stops and jumps to the
next %. Python takes the value following the second % and formats it according to the first %.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
54
KS3 COMPUTING
Name……………………………………… Class…………….........
In any programming, including Python, exceptions and error handling often becomes a necessity
when you are dealing with a considerable amount of variables. When, I say variables I do not
mean variables as a placeholder, but variables as in you are using file system processes (like
reading a file), dealing with external input, etc. Sometimes, you just do not know what will be
thrown at your code. So you being little genius, you plan ahead and use exceptions and error
handling where appropriate. For example, maybe you do not exactly know the type of the
variable, but you would definitely like to do something with it. The differences in doing things with
numbers and strings are pretty different. So, you might set up something like this:
var1 = '1'
try:
var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1
except:
print(var1, " is not a number") #so we execute this
print(var1)
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
4. Give two advantages for using Python exceptions when dealing with variables:
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
55
KS3 COMPUTING
Name……………………………………… Class…………….........
Many times, a programmer finds a reason to read content from a file. It could be that we want to
read from a text file, such as a log file, or an XML file for some serious data retrieval.
Sometimes, it is a massive task to figure out how to do it exactly. No worries, Python is smooth
like always and makes reading files a piece of cake. There are primarily 2 ways in which Python
likes to read. To keep things simple, we are just going to read from text files, feel free to explore
XML on your own later. XML is a pretty cool markup, but as you get deeper, it is kind of a
headache.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
56
KS3 COMPUTING
Name……………………………………… Class…………….........
[Link](n) - This method reads n number of characters from the file, or if n is blank it
reads the entire file.
[Link](n) - This method reads an entire line from the text file.
print([Link](1))
print([Link]())
[Link]()
First, we open the file like expected. Next, we use the read(1), and notice that we provided an
argument of 1, which just means we want to read the next character. So, Python prints out "I" for
us because that is the first character in the [Link] file. What happens next is a little funky. We
tell Python to read the entire file with read() because we did not provide any arguments.
Questions
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
57
KS3 COMPUTING
Name……………………………………… Class…………….........
Reading files is cool and all, but writing to files is a whole lot more fun. It also should instill a
sense of danger in you because you can overwrite content and lose everything in just a moment.
Despite the threat of danger, we press on. Python makes writing to files very simple. With
somewhat similar methods to reading, writing has primarily 2 methods for writing.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
58
KS3 COMPUTING
Name……………………………………… Class…………….........
If you have never had any experience with object oriented programming (OOP). Classes are
awesome because of a few reasons. First, they help you reuse code instead of duplicating the
code in other places all over your program. Classes will save your life when you realize you want
to change a function. You will only change it in one spot instead of 10 different spots with slightly
different code. Another important part of Classes is that they allow you to create more flexible
functions. An example is:
[Link](2) #use myBuddy's new add method derived from the Calculator class
Questions
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
59
KS3 COMPUTING
Name……………………………………… Class…………….........
Testing a program is very important process after the code has been written. Testing provides
the ability to check, amend and update python code once it has been completed or if the
compiler rejects some aspect of the code. Testing comes in many different types such as syntax
and functional testing which checks all aspects of the computer code.
Questions
...........................................................................................................................................................
....................................................................................................................................................... [1]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
....................................................................................................................................................... [2]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
...........................................................................................................................................................
60
KS3 COMPUTING
Name……………………………………… Class…………….........
Generally compiling is a term which is often heard by everyone who is associated with
programming, even if remotely. A compiler is a program which converts a high level language
program/code into binary instructions (machine language) that our computer can interpret,
understand and take the appropriate steps to execute the same.
A compiler will scan the entire program and translates it as a whole into machine code.
Questions
1. What is a compiler?
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Advantage 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Advantage 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
61
KS3 COMPUTING
Name……………………………………… Class…………….........
A program that executes instructions written in a high-level language. There are two ways to run
programs written in a high-level language. The most common is to compile the program; the
other method is to pass the program through an interpreter.
An interpreter translates high-level instructions into an intermediate form, which it then executes.
However, It takes less amount of time to analyze the source code but the overall execution time
is slower.
Questions
1. What is interpreter?
...........................................................................................................................................................
....................................................................................................................................................... [2]
...........................................................................................................................................................
...........................................................................................................................................................
....................................................................................................................................................... [2]
....................................................................................................................................................... [1]
Difference 1
...........................................................................................................................................................
....................................................................................................................................................... [1]
Difference 2
...........................................................................................................................................................
....................................................................................................................................................... [1]
...........................................................................................................................................................
62
KS3 COMPUTING
Python
Answers
63
KS3 COMPUTING
Python Model Assignment 1 - Answers
1. Write a Python program to print the calendar of a given month and year.
import calendar
print([Link](y, m))
f_date = date(2014, 7, 2)
print([Link])
pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
64
KS3 COMPUTING
4. Write a Python program to get the difference between a given number and 17, if the
number is greater than 17 return double the absolute difference.
def difference(n):
if n <= 17:
return 17 - n
else:
return (n - 17) * 2
print(difference(22))
print(difference(14))
5. Write a Python program to test whether a number is within 100 of 1000 or 2000.
def near_thousand(n):
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))
6. Write a Python program to calculate the sum of three given numbers, if the values
are equal then return thrice of their sum.
sum = x + y + z
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
65
KS3 COMPUTING
6. Write a Python program to calculate the sum of three given numbers, if the values
are equal then return thrice of their sum.
sum = x + y + z
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
7. Write a Python program to count the number 4 in a given list
def list_count_4(nums):
count = 0
if num == 4:
count = count + 1
return count
print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4]))
8. Write a Python program to display your details like name, age, address in three
different lines
def personal_details():
personal_details()
66
KS3 COMPUTING
9. Write a Python program to get OS name, platform and release information
import platform
import os
print([Link])
print([Link]())
print([Link]())
10. Write a Python program to find out the number of CPUs using
import multiprocessing
print(multiprocessing.cpu_count())
67
KS3 COMPUTING
Python Model Assignment 2 Answers
1. Write a Python program which accepts the user's first and last name and print them
in reverse order with a space between them
2. Write a Python program to print the calendar of a given month and year.
Answer:
import calendar
print([Link](y, m))
The function returns date object with same year, month and day. All arguments are required.
Arguments may be integers, in the following ranges:
Answer:
f_date = date(2017, 7, 2)
print([Link])
68
KS3 COMPUTING
4. Write a Python program to get the difference between a given number and 17, if the
number is greater than 17 return double the absolute difference
Answer:
def difference(n):
if n <= 17:
return 17 - n
else:
return (n - 17) * 2
print(difference(22))
print(difference(14))
5. Write a Python program which accepts a sequence of comma-separated numbers
from user and generate a list and a tuple with those numbers
list = [Link](",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)
6. Write a Python program to test whether a number is within 100 of 1000 or 2000
The function returns the absolute value of a number. The argument may be an integer or a
floating point number. If the argument is a complex number, its magnitude is returned.
def near_thousand(n):
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))
69
KS3 COMPUTING
7. Write a Python program to calculate the sum of three given numbers, if the values
are equal then return thrice of their sum.
sum = x + y + z
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))
a = 30
b = 20
a, b = b, a
print()
70
KS3 COMPUTING
10. Write a Python program to accept a filename from the user and print the extension
of that.
f_extns = [Link](".")
71