0% found this document useful (0 votes)
3 views72 pages

ks3python

The KS3 Resource Pack is designed to support teaching Python programming for students in Key Stage 3, containing worksheets, model assignments, and practice activities. It emphasizes the importance of responsible use and self-judgment in applying the content for educational purposes. The resource includes various Python programming tasks and activities to enhance learning and engagement in coding.

Uploaded by

ratmouse233
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views72 pages

ks3python

The KS3 Resource Pack is designed to support teaching Python programming for students in Key Stage 3, containing worksheets, model assignments, and practice activities. It emphasizes the importance of responsible use and self-judgment in applying the content for educational purposes. The resource includes various Python programming tasks and activities to enhance learning and engagement in coding.

Uploaded by

ratmouse233
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

KS3 RESOURCE PACK

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

This resource has been created for educational purposes only .

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.

Python is a trademark/name/logo of Python Softw are Foundation at [Link]

Copyright © ICT Interactive


KS3 COMPUTING
Content

Thank you for purchasing this resource 4


About the Resource Pack 4
General Comments on using the Resource Pack 4
Summary Disclaimer 4
Feedback 4
Request a Resource 4
Register your Email 4
Suggested Resource 5
This Resource 6
What is Python 6
How to use 6
Python Model Assignment

Model Assignment 1 - Python Programs 8


Model Assignment 2 - Python Programs 9

Python Practise Activities

Activity 1 - Hello World 11


Activity 2 - Twinkle 12
Activity 3 - Performing Calculations 13
Activity 4 - More Calculations 14
Activity 5 - Adding Numbers 15
Activity 6 - Odd and Even Numbers 16
Activity 7 - Number Checker 17
Activity 8 - What’s your Name? 18
Activity 9 - Hello World/What’s your Name 19
Activity 10 - What’s your Age? 20
Activity 11 - Find the Square Root 21
Activity 12 - Guess the Number 22
Activity 13 - Division Number 23
Activity 14 - Rock, Paper, Scissors 24
Activity 15 - Hangman 25

Chapter 1 Python Basics

1.1 What is Python? 27


1.2 Python Environment 28
1.3 How does python differ from other languages? 29
1.4 Python Interface 30
1.5 Python Reserve Words 31
1.6 Python Types of Reserve Words 32
1.7 Defining Reserved words 33
1.8 Using Python 34

Chatper 2 Python Commands

2.1 Python Line Structure 36


2.2 Python Comments 37
2.3 Python Joining two lines 38
2.4 Python Indentation 40

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

Model Assignment 1 - Answers 64


Model Assignment 2 - Answers 68

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.

About the Resource Pack

This resource pack has been designed to help students learn and support teachers
in delivery of Python at KS3-5

General Comments on using the Resource Pack

The resource pack can be used as a comprehensive teaching tool to support


existing schemes or resources from the purchasing institute. The resource pack
covers all of the learning and assessment objectives of the qualification and unit
covered. Teachers can use the resource pack as introduction to the qualification,
either as starter, main, plenary activities or as homework sheets to extend the
learning in the [Link] Worksheets have been designed to incorporate
differentiation and cater for learners of all abilities.

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

Please provide us feedback by visiting our website or sending an email to


sales@[Link].

Request a Resource

If you have any suggestions or recommendations for a new resource, please do


not hesitate in contacting us. We will be very happy to produce resources based
on your request. Please send all requests to sales@[Link]

Register your email

Register your email to receive free future updates and other resources from I CT
Interactive

4
KS3 COMPUTING
Suggested Resources

KS4 Resource Pack

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.

This resource pack contains:

4 model assignments which potentially match the NEA program assignment


15 practise activities for students to learn Python programs differentiation to allow
students to progress at their own pace.
110+ Worksheets activities for students completed which cover ALL aspects of
Python coding: from Python Dictionary/Datet, time modules, Numbers, Data types,
Operators, Strings, Variables, Lists, Tuples, Functions/Modules, File I/O and
exceptions etc

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.

This resource has been developed for Python Version 3

Students will learn:

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]

All logos/trademarks are Python Software Foundation

6
KS3 COMPUTING

Python
Model Assignments

7
KS3 COMPUTING
Model Assignment 1: Python Programs

Activity

In this assignment, you are required to complete a series of small projects to


demonstrate your skills and understanding of Python. Within this task, there are mini
python projects to complete. After you have completed the first task, save and move
onto the next task.

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.

2. Write a Python program to calculate number of days between two dates.

3. Write a Python program to get the volume of a sphere with radius 6.

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.

7. Write a Python program to count the number 4 in a given list

8. Write a Python program to display your details like name, age, address in three different lines

9. Write a Python program to get OS name, platform and release information

10. Write a Python program to find out the number of CPUs using

Notes:

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................
...........................................................................................................................................................

8
KS3 COMPUTING
Model Assignment 2: Python Programs

Activity

In this assignment, you will be given 10 mini projects to complete in Python.


These mini projects will ask you to write code in Python which produces
a specific output.

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.

3. Write a Python program to calculate number of days between two dates.


Sample dates : (2017, 7, 2), (2017, 7, 11)

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.

8. Write a Python program to convert all units of time into seconds

9. Write a Python program to swap two variables.

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.

This program functions in Python 3. Type the following code:

print('Hello, world!')

and now type

print('Hello, my school!')

and now type

print('Hello, how are you today!')

Tasks

1. Create a simple program that types your name

2. Add to the program by including the name of your school

3. Add to the program by adding your class, tutor name and your best friend’s name

4. What other print command can you use?

Questions:

[Link] did you notice when you typed in the command?

...........................................................................................................................................................

...........................................................................................................................................................

2. Think of a method of storing the type command? (If you can)

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

11
KS3 COMPUTING
Activity 2: Twinkle

Activity

In this task you are going to create simply calculation using Python.

This program functions in Python 3. Type the following code:

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

1. Create the above code/

2. Create your own rhyme based.

3. What command can you use to type on a new line/

4. Improve the code to ask a user for their preferred nursery rhyme.

Questions:

1. What did you notice when you typed in the command?

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3.

Type in the following code into terminal:

2+5

11+12

1+6

234+890

Now type this:

a=2

b=3

sum = a + b

print(sum)

Tasks

1. Do the calculations function? - Add the print () command


2. Create more simply calculations
3. Complete the rest of the code by adding different types of arithmetic operators

Questions:

1. What do the A + B command contain?

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 2 and 3. Type the following code:

a=2 b=7 c=6 d=3 e=4

sum = a + b + c + d + e

print(sum)

Now type this:

num1 = 3

num2 = 5

sum = num1+num2

print(sum)

Tasks

1. Create a more simply calculation by using other arithmetic operators

Questions:

1. What does the sum command actually do?

...........................................................................................................................................................

...........................................................................................................................................................

2. Decide method is the most appropriate and justify your answer:

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

# Store input numbers

num1 = input('Enter first number: ')

num2 = input('Enter second number: ')

# Add two numbers

sum = float(num1) + float(num2)

# Display the sum

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Tasks

1. Create the above program

Questions:

1. What did you notice when you typed in the command?

...........................................................................................................................................................

...........................................................................................................................................................

2. How is the float command used?

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

num = input("Enter a number: ")

mod = num % 2

if mod > 0:

print("You picked an odd number.")

else:

print("You picked an even number.")

Tasks

1. Create the above program

Questions:

1. Explain how this program functions:

...........................................................................................................................................................

...........................................................................................................................................................

2. How is the IF command used?

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

num = int(input("give me a number to check: "))


check = int(input("give me a number to divide by: "))

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

1. Create the above program

Questions:

1. Explain the type of statements used in the above program:

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

print('What is your name?')


myName = input()
print('It is good to meet you, ' + myName)

and now type in the following code:

print('What is your name?')


myName = input()
print('Hello, ' +myName)
print('It is good to meet you, ' + myName)

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:

1. What did you notice when you typed in the command?

...........................................................................................................................................................

...........................................................................................................................................................

2. Think of a method of storing the type command?

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

print('Hello, world!')

print('What is your name?')


myName = input()
print('It is good to meet you, ' + myName)

Tasks

1. Create a simple program that types your name on the screen

2. Include the a message that asks “how are you today” and replies “I am fine”

Questions

1. How does python store your respond to the question?

...........................................................................................................................................................

...........................................................................................................................................................

2. Which command is used to store the response and enter the name?

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

3. Name the variables used and explain the “Input” command:

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

name = input("What is your name: ")

age = int(input("How old are you: "))

year = str((2017 - age)+100)

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:

1. What did you notice when you typed in the command?

...........................................................................................................................................................

...........................................................................................................................................................

2. Explain the INT and STR command:

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

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 to save and then run the program

Remember appropriate indentations and to save with py extension, then run your program.

This program functions in Python 3. Type the following code:

# Python Program to calculate the square root

# Note: change this value for a different result

num = 8

# uncomment to take the input from the user

#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5

print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Tasks

1. Create the above program


2. Change the values of num and see what results you get.

Questions:

1. What did you notice when you typed in the command?

............................................................................................................................................................

............................................................................................................................................................

2. Explain the num_sqrt command:

............................................................................................................................................................

............................................................................................................................................................

............................................................................................................................................................

............................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

# Plays the guessing game higher or lower

number = 7
guess = -1

print("Guess the number!")


while guess != number:
guess = int(input("Is it... "))

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

1. Change the number and number of guess


2. Create the same program which asks for the users name first.
3. Include their name with every guess message.

Questions:

1. Name and explain the command used for a loop in the above code?

...........................................................................................................................................................

...........................................................................................................................................................

2. What is the difference between an IF and an Elif?

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

...........................................................................................................................................................

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.

This program functions in Python 3. Type the following code:

num = int(input("Please choose a number to divide: "))

listRange = list(range(1,num+1))

divisorList = [ ]

for number in listRange:

if num % number == 0:

[Link](number)

print(divisorList)

Tasks

1. Change the number and number of guess


2. Create the same program which asks for the users name first.
3. Include their name with every guess message.

Questions:

1. Name and explain the command used for a loop in the above code?

............................................................................................................................................................

............................................................................................................................................................

2. Explain “for number in listRange:” 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.

This program functions in Python 3. Type the following code:

import sys

user1 = input("What's your name?")


user2 = input("And your name?")
user1_answer = input("%s, do yo want to choose rock, paper or scissors?" % user1)
user2_answer = input("%s, do you want to choose rock, paper or scissors?" % user2)

def compare(u1, u2):


if u1 == u2:
return("It's a tie!")
elif u1 == 'rock':
if u2 == 'scissors':
return("Rock wins!")
else:
return("Paper wins!")
elif u1 == 'scissors':
if u2 == 'paper':
return("Scissors win!")
else:
return("Rock wins!")
elif u1 == 'paper':
if u2 == 'rock':
return("Paper wins!")
else:
return("Scissors win!")
else:
return("Invalid input! You have not entered rock, paper or scissors, try again.")
[Link]()

print(compare(user1_answer, user2_answer))

Tasks

1. Change the number and number of guesses


2. Create the same program which asks for the users name first.
3. Include their name with every guess message.

24
KS3 COMPUTING
Activity 15: Hangman

Activity

In this activity you are going to create a python program which is the
hangman game.

This program functions in Python 3. Type the following code:

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

1. Create the program

25
KS3 COMPUTING

1. Python: Basics
Activities and Worksheets

26
KS3 COMPUTING
Name……………………………… Class…………….........

1.1 What is Python?


Python is a general-purpose programming language, which is another way to
say that it can be used for nearly everything. Most importantly, it is an
interpreted language, which means that the written code is not actually
translated to a computer-readable format at runtime. Whereas, most
programming languages do this conversion before the program is even run. This
type of language is also referred to as a "scripting language" because it was initially
meant to be used for trivial projects. A large majority of web applications and platforms rely on
Python, including Google's search engine, YouTube, and the web-oriented transaction system of
the New York Stock Exchange (NYSE). You know the language must be pretty serious when it's
powering a stock exchange system.
QUESTIONS

1. What is python?

............................................................................................................................................................

........................................................................................................................................................[2]

2. What type of programming language is Python?

........................................................................................................................................................[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…………….........

1.2 Python Environment

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]

2. What is the Python Shell?

....................................................................................................................................................... [1]

3. Explain the term “Bang line”:

...........................................................................................................................................................

....................................................................................................................................................... [1]

4. Explain the Python Interpreter?

...........................................................................................................................................................

....................................................................................................................................................... [1]

5. Give two advantages for the use of Python Environment:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

28
KS3 COMPUTING
Name……………………………… Class…………….........

1.3 How does python differ from other languages?


Python stands out because it is easy to learn and easy to understand. Many
consider Ruby a great place to start, like Python, yet the latter has a four-
year head start. This means that it has a big foothold in the enterprise world,
and it's much more popular with C developers. This is because it's easy to
crossover between the two languages.

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. Explain how Python differs from other Languages:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [1]

2. Name one other programming language:

....................................................................................................................................................... [1]

3. What type of programming language is Python?

...........................................................................................................................................................

....................................................................................................................................................... [1]

4. What other programming languages does Python follow?

....................................................................................................................................................... [1]

5. Give two advantages for Python programming language:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

29
KS3 COMPUTING
Name……………………………… Class…………….........

1.4 Python Interface

QUESTIONS

1. Explain the Python Interface:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain the difference between an online Interface and Desktop version:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Give two advantages for the using an Online Python Interface:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

30
KS3 COMPUTING
Name……………………………… Class…………….........

1.5 Python Reserve Words

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. Explain the Print command:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain how the IF and Elif commands are interlinked:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

31
KS3 COMPUTING
Name……………………………… Class…………….........

1.6 Python Types of Reserve Words

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)

Print

32
KS3 COMPUTING
Name……………………………………… Class…………….........

1.7 Defining Reserved words


Activity

1. Explain how the following reserved words in Python; give an example of use [4]

Type Explanation Example

Print

Elif

Import

Pass

33
KS3 COMPUTING
Name……………………………………… Class…………….........

1.8 Using Python


Activity

Complete the following sentences: [1]

1. Python is a

...........................................................................................................................................................

1. Python has many reserved words, three are

...........................................................................................................................................................

1. An example of a Python operator is

...........................................................................................................................................................

4. Loops are

...........................................................................................................................................................

5. The IF statement will

...........................................................................................................................................................

6. Using numbers in python will

...........................................................................................................................................................

7. Print “Hello” will

...........................................................................................................................................................

8. An example of a variable is

...........................................................................................................................................................

9. Print “What’s your age” will

...........................................................................................................................................................

10. An example of a string is

...........................................................................................................................................................

11. The Python dictionary is

...........................................................................................................................................................

34
KS3 COMPUTING

2. Python: Commands
Activities and Worksheets

Name……………………………………… Class…………….........

1.1 Python Operators


Activity
Read the following and answer the questions:

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…………….........

2.1 Python Line Structure


Activity

Read the following and answer the questions:

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.

Here are naming conventions for Python identifiers:

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

1. Explain how Python indentifies are used:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain why Python code is case sensitive:


...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain how Classes are indentified in Python:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

4. Explain why Python does not allow punctuation:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

36
KS3 COMPUTING
Name……………………………………… Class…………….........

2.2 Python Comments


Activity

Read the following and answer the questions:

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

1. Explain the purpose of comments in Python:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Name the two comments in the above code:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. What symbol defines how a comment is inserted?

....................................................................................................................................................... [1]

4. Give two advantages for inserting comments:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

37
KS3 COMPUTING
Name……………………………………… Class…………….........

2.3 Python Joining two lines


Activity

Read the following and answer the questions:

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.

import sys; x = 'foo'; [Link](x + '\n')

Questions

1. Explain the purpose of joining two lines in Python Code:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain what symbol ends a physical line in Python:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain the /n command:

....................................................................................................................................................... [4]

4. Give two advantages for joining lines in Python:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

38
KS3 COMPUTING
Name……………………………………… Class…………….........

2.4 Python Indentation


Activity

Read the following and answer the questions:

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

1. Explain the importance of proper indentation in Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain what will happen if identifications are not properly used:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. What symbols are used to define blocks of classes or functions?

....................................................................................................................................................... [4]

4. Give two advantages’ for using indentation in Python:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

39
KS3 COMPUTING
Name……………………………………… Class…………….........

2.5 Python Variables


Activity

Read the following and answer the questions:

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

1. Explain how variables are using in Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. How does Python interpret variables?

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Name the variable from the above code:

....................................................................................................................................................... [1]

4. State two advantages for using variables in Python:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

40
KS3 COMPUTING
Name……………………………………… Class…………….........

2.6 Python Variable Types


Activity

Read the following and answer the questions:

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:

int(variable) - casts variable to integer


str(variable) - casts variable to string
float(variable) - casts variable to float (number with decimal)

a = "0"

b=2
print(int(a) + b)

Questions

1. Explain how Python uses different types of variables:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain the INT and STR variable

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. How is the float variable used to define a number?

....................................................................................................................................................... [1]

4. Explain two advantages for using INT variable:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

[2]

41
KS3 COMPUTING
Name……………………………………… Class…………….........

2.7 Python IF Statement


Activity

Read the following and answer the questions:

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")

elif a >= 21:


print("elif")

else:
print("else")

Questions

1. What are IF statements in Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how thee IF and Elif Statements are used in Python:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Give two advantages for using IF statement in programming code:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

42
KS3 COMPUTING
Name……………………………………… Class…………….........

2.8 Python Functions


Activity

Read the following and answer the questions:

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

1. What are functions in Python?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how functions are used in Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Give two advantages for using the functions in Python:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

43
KS3 COMPUTING
Name……………………………………… Class…………….........

2.9 Python Functions with Arguments


Activity

Read the following and answer the questions:

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.

def someFunction(a, b):

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

1. What are functions with arguments?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain the someFunction from the above code:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

4. Give two advantages for functions with arguments:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

44
KS3 COMPUTING
Name……………………………………… Class…………….........

2.10 Python For Loops


Activity

Read the following and answer the questions:

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

1. What is a FOR loop?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how the FOR loop is used in Python:

...........................................................................................................................................................

...........................................................................................................................................................

3. Fine the range command in the Loop:

....................................................................................................................................................... [4]

4. Give two advantages for using the FOR loop:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

45
KS3 COMPUTING
Name……………………………………… Class…………….........

2.11 Python While Loops


Activity

Read the following and answer the questions:

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

1. What is a WHILE loops?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how the WHILE loop is used in Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain the <10 condition in the loops:

....................................................................................................................................................... [1]

4. Give two advantages for using the WHILE loop in Python:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

[2]

46
KS3 COMPUTING
Name……………………………………… Class…………….........

2.12 Python Strings


Activity

Read the following and answer the questions:

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

1. What are Strings in Python?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how Strings are used in my Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Define the type() command:

....................................................................................................................................................... [1]

4. Give two advantages for using Python Strings:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

47
KS3 COMPUTING
Name……………………………………… Class…………….........

2.13 Python Common Strings Methods


Activity

Read the following and answer the questions:

 [Link]('x') - counts the number of occurrences of 'x' in stringVar


 [Link]('x') - returns the position of character 'x'
 [Link]() - returns the stringVar in lowercase (this is temporary)
 [Link]() - returns the stringVar in uppercase (this is temporary)
 [Link]('a', 'b') - replaces all occurrences of a with b in the string
 [Link]() - removes leading/trailing white space from string

Questions

1. What are string methods?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain which strings return values in upper and lowercase:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain which string removes whites spaces:

....................................................................................................................................................... [1]

4. Give two advantages for Python having different Strings methods:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

48
KS3 COMPUTING
Name……………………………………… Class…………….........

2.14 Python String Indexes


Activity

Read the following and answer the questions:

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

1. What are Indexes and Strings?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how indexes are define and used in Python:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Give two advantages for Python indexes:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

49
KS3 COMPUTING
Name……………………………………… Class…………….........

2.15 Python Lists


Activity

Read the following and answer the questions:

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

1. What are Python Lists?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how Python lists are used:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Give two advantages for using Python lists:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

50
KS3 COMPUTING
Name……………………………………… Class…………….........

2.16 Python Common Lists Methods


Activity

Read the following and answer the questions:

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.

 .append(value) - appends element to end of the list


 .count('x') - counts the number of occurrences of 'x' in the list
 .index('x') - returns the index of 'x' in the list
 .insert('y','x') - inserts 'x' at location 'y'
 .pop() - returns last element then removes it from the list
 .remove('x') - finds and removes first 'x' from list
 .reverse() - reverses the elements in the list
 .sort() - sorts the list alphabetically in ascending order, or numerical in ascending order

Questions

1. Define why python has a number of lists methods:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain which list methods allows ascending and numerical orders:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Which command adds an element to the end of list?

....................................................................................................................................................... [1]

4. Give two advantages for python list methods

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

51
KS3 COMPUTING
Name……………………………………… Class…………….........

2.17 Python Tuples


Activity

Read the following and answer the questions:

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

1. What are Python Tuples?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how Tuples are used instead of lists:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Give two advantages for using Tuples:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

52
KS3 COMPUTING
Name……………………………………… Class…………….........

2.18 Python Dictionary


Activity

Read the following and answer the questions:

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:

myExample = {'someItem': 2, 'otherItem': 20}

print(myExample['otherItem'])

Questions

1. What is the Python Dictionary?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how the Python dictionary is used?

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain the myExample code:

....................................................................................................................................................... [1]

4. Explain two advantages for using the Python Dictionary:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

53
KS3 COMPUTING
Name……………………………………… Class…………….........

2.19 Python Formatting


Activity

Read the following and answer the questions:

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.

print('The order total comes to %f' % 123.44)

print('The order total comes to %.2f' % 123.444)

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

1. Explain the purpose of Python formatting

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how python formatting is used from the above example:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Give two advantages for Python formatting:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

54
KS3 COMPUTING
Name……………………………………… Class…………….........

2.20 Python Exceptions


Activity

Read the following and answer the questions:

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

1. What are Python exceptions?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how Python exceptions are used in programming:

...........................................................................................................................................................

....................................................................................................................................................... [2]

4. Give two advantages for using Python exceptions when dealing with variables:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

55
KS3 COMPUTING
Name……………………………………… Class…………….........

2.21 Python Reading to a File


Activity

Read the following and answer the questions:

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.

f = open("[Link]", "r") #opens file with name of "[Link]"

Questions

1. Why is it important to read from a file?

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how Python allows reading from a file:

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain the F= open code:

....................................................................................................................................................... [1]

4. Give two advantages for reading from a file:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

56
KS3 COMPUTING
Name……………………………………… Class…………….........

2.22 Python File Reading Methods


Activity

Read the following and answer the questions:

There are two distinctive methods of Python reading to a file.

 [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.

f = open("[Link]","r") #opens file with name of "[Link]"

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

1. Define the two methods for reading from a file:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain F=open and [Link] commands:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Explain the [Link] command:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

57
KS3 COMPUTING
Name……………………………………… Class…………….........

2.23 Python Writing to a File


Activity

Read the following and answer the questions:

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.

= open("[Link]","w") #opens file with name of "[Link]"


[Link]("I am a test file.")
[Link]("Maybe someday, he will promote me to a real file.")
[Link]("Man, I long to be a real file")
[Link]("and hang out with all my new real file friends.")
[Link]()

Questions

1. Why is it important to write to file in programming:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Explain how Python writes to a file:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Define the [Link] command:

....................................................................................................................................................... [1]

4. Give two advantages for writing to file:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

58
KS3 COMPUTING
Name……………………………………… Class…………….........

2.24 Python Classes


Activity

Read the following and answer the questions:

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:

from ClassOne import * #get classes from ClassOne file

myBuddy = Calculator() # make myBuddy into a Calculator object

[Link](2) #use myBuddy's new add method derived from the Calculator class

print([Link]()) #print myBuddy's current instance variable

Questions

1. Explain how classes are used in Python:

...........................................................................................................................................................

....................................................................................................................................................... [2]

2. Define classes in Python:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. What does OOP stand for?

....................................................................................................................................................... [1]

4. Explain the mybuddy class:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

59
KS3 COMPUTING
Name……………………………………… Class…………….........

2.25 Python Testing


Activity

Read the following and answer the questions:

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. Explain the importance of testing a python program:

...........................................................................................................................................................

....................................................................................................................................................... [1]

2. Give two examples of testing a Python program:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Name and explain two types of testing you could do on a program:

...........................................................................................................................................................

....................................................................................................................................................... [2]

4. Give two advantages for testing a program:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

...........................................................................................................................................................

60
KS3 COMPUTING
Name……………………………………… Class…………….........

2.26 Python Complier


Activity

Read the following and answer the questions:

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. Explain the importance of a compiler:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Define machine code:

....................................................................................................................................................... [1]

4. Explain two advantages for using a compiler:

Advantage 1

...........................................................................................................................................................

....................................................................................................................................................... [1]

Advantage 2

...........................................................................................................................................................

....................................................................................................................................................... [1]

61
KS3 COMPUTING
Name……………………………………… Class…………….........

2.27 Python Interpreter


Activity

Read the following and answer the questions:

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. Explain how an interpreter is used to execute a program:

...........................................................................................................................................................

...........................................................................................................................................................

....................................................................................................................................................... [2]

3. Define intermediate form:

....................................................................................................................................................... [1]

4. Explain the difference between a compiler and interpreter:

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.

Note : Use 'calendar' module.

import calendar

y = int(input("Input the year : "))

m = int(input("Input the month : "))

print([Link](y, m))

2. Write a Python program to calculate number of days between two dates.

Sample dates : (2014, 7, 2), (2014, 7, 11)

Expected output : 9 days

from datetime import date

f_date = date(2014, 7, 2)

l_date = date(2014, 7, 11)

delta = l_date - f_date

print([Link])

3. Write a Python program to get the volume of a sphere with radius 6.

pi = 3.1415926535897931

r= 6.0

V= 4.0/3.0*pi* r**3

print('The volume of the sphere is: ',V)

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):

return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))

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.

def sum_thrice(x, y, z):

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.

def sum_thrice(x, y, z):

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

for num in nums:

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():

name, age = "Simon", 19

address = "Bangalore, Karnataka, India"

print("Name: {}\nAge: {}\nAddress: {}".format(name, age, address))

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

fname = input("Input your First Name : ")

lname = input("Input your Last Name : ")

print ("Hello " + lname + " " + fname)

2. Write a Python program to print the calendar of a given month and year.

Answer:

import calendar

y = int(input("Input the year : "))

m = int(input("Input the month : "))

print([Link](y, m))

3. Write a Python program to calculate number of days between two dates.

Sample dates : (2017, 7, 2), (2017, 7, 11)

The function returns date object with same year, month and day. All arguments are required.
Arguments may be integers, in the following ranges:

Answer:

from datetime import date

f_date = date(2017, 7, 2)

l_date = date(2017, 7, 11)

delta = l_date - f_date

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

values = input("Input some comma seprated 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):

return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))

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.

def sum_thrice(x, y, z):

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))

8. Write a Python program to convert all units of time into seconds

days = int(input("Input days: ")) * 3600 * 24

hours = int(input("Input hours: ")) * 3600

minutes = int(input("Input minutes: ")) * 60

seconds = int(input("Input seconds: "))

time = days + hours + minutes + seconds

print("The amounts of seconds", time)

9. Write a Python program to swap two variables.

a = 30

b = 20

print("\nBefore swap a = %d and b = %d" %(a, b))

a, b = b, a

print("\nAfter swaping a = %d and b = %d" %(a, b))

print()

70
KS3 COMPUTING
10. Write a Python program to accept a filename from the user and print the extension
of that.

filename = input("Input the Filename: ")

f_extns = [Link](".")

print ("The extension of the file is : " + repr(f_extns[-1]))

71

You might also like