KS2 Python: 50 Introductory codes
What is Python?
Python is a high-level, interpreted programming language that is widely used for a variety of
applications. It was first released in 1991 and has since become one of the most popular
programming languages in use today.
Python is known for its simplicity and ease of use, making it a popular choice for beginners
learning to program. It features a clear syntax and an extensive library of built-in functions
and modules that make it useful for a wide range of tasks, from web development to
scientific computing and artificial intelligence.
Python is an interpreted language, meaning that the code is executed line by line, as opposed
to compiled languages like C++ and Java. This allows for quicker development and testing, and
makes it easy to write scripts and prototypes.
Python is also an open-source language, which means that its source code is freely available
and can be modified and redistributed by anyone. This has contributed to the growth of a
large and supportive community of developers and users, who have created many useful
libraries and tools that are freely available for use by anyone.
Why should we teach students to code in 2023?
Future job opportunities
As technology continues to advance, many jobs are becoming increasingly reliant on coding
and computer literacy. Learning to code at a young age can prepare children for future job
opportunities and help them develop the skills they need to succeed in the workforce.
Problem-solving skills
Coding involves breaking down complex problems into smaller, more manageable tasks. By
learning to code, children can develop their problem-solving skills and learn how to approach
challenges in a logical and systematic way.
Creativity and innovation
Coding also allows for creativity and innovation. By learning to code, children can create their
own digital art, games, and apps, and bring their own unique ideas to life.
Understanding technology
In today's digital world, it's important for children to understand how technology works and
how it affects their lives. Learning to code can help children better understand the technology
around them and how it can be used to solve problems and make a positive impact.
Trial and error
Programming is an iterative process, where children try different solutions to see what works
and what doesn't. Through this trial-and-error approach, children can learn to persist through
failure and develop the resilience to keep trying until they find a solution that works.
Debugging
Debugging is a key skill in programming, as it requires children to identify and fix errors in
their code. This can be frustrating at times, but it also teaches children to be patient and
persistent as they work through problems.
Project completion
Learning Python can help children see a project through from start to finish, which can be a
valuable lesson in resilience. By working on a project over time and overcoming obstacles
along the way, children can learn the importance of perseverance and dedication.
Transferable skills
The skills children learn from coding, such as logical thinking, problem-solving, and attention
to detail, are transferable to other subjects and areas of life. These skills can help children
succeed in school, work, and everyday life.
Using these Python codes
For these activities there is a free IDE (integrated development environment available online,
which can be found here:
https://trinket.io/features/python3
For codes that use turtle and other graphics, use:
https://trinket.io/features/pygame
You can also download Python to use offline, here:
https://www.python.org/downloads/
Hello World
print("Hello, World!")
This code simply prints the text "Hello, World!" to the console.
Next: Experiment with other sentences using the print function.
Print a greeting with the user's name
name = input("What is your name? ")
print("Hello, " + name + “!”)
Next: Change the question and response.
Emojis
print("\U0001F600")
Unicode escape sequences are a way to represent Unicode characters in a string using a
backslash followed by the Unicode code point in hexadecimal. The Unicode code point for an
emoji depends on the specific emoji.
Here are some commonly used emojis and their corresponding Unicode code points in
Python:
Smiling face: \U0001F600
Thumbs up: \U0001F44D
Heart: \U00002764
Crying face: \U0001F622
Face with tears of joy: \U0001F602
Fire: \U0001F525
Clapping hands: \U0001F44F
Party popper: \U0001F389
Thinking face: \U0001F914
Rocket: \U0001F680
To use these Unicode escape sequences, simply include them in a string with a print
statement or use them in any other string manipulation as needed.
Next: Print an emoji with a text message.
Print the calendar month
import calendar
year = 2023
month = 2
print(calendar.month(year,month))
Next: Ask the user for the year and month they would like printing.
Getting the current time
import time
current_time = time.time()
print(current_time)
This code imports the time library and uses the time() function to get the current time in
seconds since Unix time started, and then prints it to the console. Unix time is a
representation used widely in computing. It measures time by the number of seconds that
have elapsed since 00:00:00 UTC on 1st January, 1970.
Next: Print the current time with a message, such as ‘The Unix time is…’.
Formatting the current time
import time
current_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
print(formatted_time)
This code imports the time library and uses the localtime() function to get the current time as
a struct_time object, and then uses the strftime() function to format the time as a string and
prints it to the console.
Next: Combine this script with the Hello World script at the beginning.
Converting a string to a time object
import time
date_string = "2023-02-24 09:00:00"
time_object = time.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(time_object)
This code imports the time library and uses the strptime() function to convert a date string in
the format of "YYYY-MM-DD HH:MM:SS" to a time object, and then prints it to the console.
Next: Include a string of text with the time when printed.
Sum of two numbers
num1 = 5
num2 = 7
sum = num1 + num2
print("The sum of", num1, "and", num2, "is", sum)
Next: Find the sum of three numbers.
Add two numbers together
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 + num2
print("The sum is: " + str(result))
Next: Ask the user for three numbers.
Subtract two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 - num2
print("The difference is: " + str(result))
Next: Change the return text so that it quotes the two numbers entered by the user.
Multiply two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 * num2
print("The product is: " + str(result))
Next: Print the full times tables along with the answer. The algorithm to be used is below.
Generate the multiplication table for a number
num = int(input("Enter a number: "))
for i in range(1, 11):
print(str(num) + " x " + str(i) + " = " + str(num*i))
Next: Change the range for the tables so that it prints beyond 1 – 11.
Divide two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("The quotient is: " + str(result))
This code defines two variables num1 and num2, assigns them the values 5 and 7,
respectively, adds them together, and then prints out the result in a sentence.
Next: Add a welcome message before asking for the two numbers.
Calculate the remainder of two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 % num2
print("The remainder is: " + str(result))
Next: Add another calculation that is processed using the user’s numbers. Print the answer to
this alongside the answer to the division.
Generate a random number
import random
print(random.randint(1, 10))
Next: Label the random number num1 before printing.
Check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.”)
Next: Change the text that the user sees at the start and end of the script.
Generate a list of even numbers
even_numbers = []
for i in range(1, 11):
if i % 2 == 0:
even_numbers.append(i)
print(even_numbers)
Next: Because the even number are also in the two times tables, also print this.
Generate a list of odd numbers
odd_numbers = []
for i in range(1, 11):
if i % 2 != 0:
odd_numbers.append(i)
print(odd_numbers)
Next: Add a message before printing the odd numbers.
Sort a list of numbers in ascending order
numbers = [5, 2, 8, 1, 7]
numbers.sort()
print(numbers)
Next: Add more numbers to this list.
Sort a list of numbers in descending order
numbers = [5, 2, 8, 1, 7]
numbers.sort(reverse=True)
print(numbers)
Next: Add a message when printing the numbers at the end of the script.
Check if a number is prime
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print("The number is not prime.")
break
else:
print("The number is prime.")
else:
print("The number is not prime.")
Next: At the end of the script, print an explanation of what a prime number is. Perhaps
starting, ‘Did you know…’.
Find the largest number in a list
numbers = [1, 5, 2, 7, 3]
max_number = max(numbers)
print("The largest number is: " + str(max_number))
Next: Add more numbers to the list.
Find the smallest number in a list
numbers = [1, 5, 2, 7, 3]
min_number = min(numbers)
print("The smallest number is: " + str(min_number))
Next: Ask the user to input numbers.
Checking if a number is positive or negative
num = -3
if num > 0:
print(num, "is positive")
else:
print(num, "is negative”)
This code assigns the value -3 to the variable num, then checks if num is greater than 0. If it is,
it prints out a message saying that num is positive. Otherwise, it prints out a message saying
that num is negative. In this case, since num is negative, the output would be: -3 is negative.
Next: Ask the user to input one or more numbers
Calculating the area of a rectangle
length = 5
width = 3
area = length * width
print("The area of the rectangle is:", area)
This code calculates the area of a rectangle with length 5 and width 3, and then prints out the
result.
Next: Ask the user to input the length and width.
Converting Celsius to Fahrenheit
celsius = 20
fahrenheit = (celsius * 9/5) + 32
print(celsius, "degrees Celsius is equal to", fahrenheit, "degrees
Fahrenheit”)
This code converts a temperature in Celsius (in this case, 20 degrees Celsius) to Fahrenheit,
and then prints out the result.
Next: Convert different units of measure, such as kilometres and metres.
Generating a random number
import random
num = random.randint(1, 10)
print("Random number:", num)
This code generates a random integer between 1 and 10 (inclusive) using the random module,
and then prints out the result.
Next: Create two random numbers and perform a calulation
Checking if a number is even or odd
num = 7
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd”)
This code checks if a number (in this case, 7) is even or odd using the modulo operator (%),
and then prints out a message accordingly.
Next: Ask the user to input
Counting the number of characters in a string
string = "Hello, World!"
num_chars = len(string)
print("Number of characters in string:", num_chars)
This code counts the number of characters in the string "Hello, World!" using the len()
function, and then prints out the result.
Next: Ask for user input and rename the output as ‘word count’.
Reversing a string
string = "Hello, World!"
reversed_string = string[::-1]
print("Reversed string:", reversed_string)
This code reverses the string "Hello, World!" using slicing, and then prints out the result.
Next: Ask for user input and rename the user output as ‘mirror words’.
Swapping two variables
a = 5
b = 7
a, b = b, a
print("a:", a)
print("b:", b)
This code swaps the values of two variables (a and b) using tuple unpacking, and then prints
out the new values of a and b.
Next: Swap three variables around.
Checking if a number is a multiple of another number
num1 = 10
num2 = 5
if num1 % num2 == 0:
print(num1, "is a multiple of", num2)
else:
print(num1, "is not a multiple of", num2)
This code checks if num1 is a multiple of num2 using the modulo operator, and then prints
out a message accordingly.
Next: As well as printing the above, print all multiples of num2.
Finding the length of the hypotenuse of a right triangle
import math
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print("Length of hypotenuse:", c)
This code uses the Pythagorean theorem to find the length of the hypotenuse of a right
triangle with legs of length 3 and 4, and then prints out the result using the math.sqrt()
function.
Next: Ask for the user to input values a and b.
Reversing a list
nums = [1, 2, 3, 4, 5]
reversed_nums = nums[::-1]
print("Reversed list:", reversed_nums)
This code reverses a list [1, 2, 3, 4, 5] using slicing, and then prints out the result.
Next: Ask the user if they want the list reverse to it’s original order and then execute the
command.
Checking if a list contains a specific element
fruits = ["apple", "banana", "orange"]
if "banana" in fruits:
print("Fruits list contains banana")
else:
print("Fruits list does not contain banana”)
This code checks if the list fruits contains the element "banana", and then prints out a
message accordingly.
Next: Add more fruit to the list; check if the list contains more than one fruit.
Counting the number of elements in a list
nums = [1, 2, 3, 4, 5]
num_elements = len(nums)
print("Number of elements in list:", num_elements)
This code counts the number of elements in a list [1, 2, 3, 4, 5]
Next: Change the list of numbers for a list of names.
Asking for the user's age and printing a message based on their age
age = int(input("How old are you? "))
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.”)
This code asks the user for their age using the input() function, converts the input to an
integer using int(), and then prints out a message based on the user's age.
Next: Include the users name in the response at the end.
Asking for a password and checking if it is correct
password = input("Enter the password: ")
if password == "password123":
print("Access granted.”)
else:
print("Access denied.”)
This code asks the user for a password using the input() function, and then checks if the
password is correct. If the password is correct, it prints out "Access granted." If the password
is not correct, it prints out "Access denied."
Next: Ask the user to choose a password at the start of the script.
Asking the user to enter a sentence and printing its length
sentence = input("Enter a sentence: ")
length = len(sentence)
print("Length of the sentence:", length)
This code asks the user to enter a sentence using the input() function, counts the number of
characters in the sentence using the len() function, and then prints out the length of the
sentence.
Next: Include a maximum and minimum length for the sentence. Produce an error message if
the length is outside of the parameters set.
Drawing a square
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.done()
This code imports the turtle library, moves the turtle forward and turns it right four times to
draw a square.
Next: Change the dimensions of the square.
Drawing a circle
import turtle
turtle.circle(50)
turtle.done()
This code imports the turtle library and uses the circle() function to draw a circle with a radius
of 50.
Next: Change the size of the circle.
Drawing a triangle
import turtle
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.done()
This code imports the turtle library, moves the turtle forward and turns it left three times to
draw a triangle.
Next: Observe the angles in the script and change these in order to alter the appearance of
the triangle.
Drawing a spiral
import turtle
for i in range(50):
turtle.forward(i * 5)
turtle.right(90)
turtle.done()
This code imports the turtle library, uses a for loop to draw a spiral by moving the turtle
forward and turning it right with increasing distance and angle.
Next: Change the variables to alter the appearance of the spiral pattern.
Drawing a star
import turtle
for i in range(5):
turtle.forward(100)
turtle.right(144)
turtle.done()
This code imports the turtle library and uses a for loop to draw a star with 5 points by moving
the turtle forward and turning it right by 144 degrees.
Next: Alter the variables to make a different size star.
Drawing a rectangle
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(50)
turtle.done()
This code imports the turtle library, moves the turtle forward and turns it right twice to draw
a rectangle.
Next: Change the dimensions of the rectangle.
Drawing a hexagon
import turtle
for i in range(6):
turtle.forward(100)
turtle.right(60)
turtle.done()
This code imports the turtle library, uses a for loop to draw a hexagon by moving the turtle
forward and turning it right by 60 degrees.
Next: Can you make a pentagon based on what you know about a hexagon?
Drawing a smiley face
import turtle
turtle.circle(50)
turtle.penup()
turtle.goto(-20, 60)
turtle.pendown()
turtle.circle(10)
turtle.penup()
turtle.goto(20, 60)
turtle.pendown()
turtle.circle(10)
turtle.penup()
turtle.goto(0, 40)
turtle.pendown()
turtle.right(90)
turtle.circle(20, 180)
turtle.done()
This code imports the turtle library and draws a smiley face by using the circle() function to
draw the head and eyes, and then drawing a smile with circle() and right() functions.
Next: Using turtle.penup() and turtle.pendown(), give the smiley face a body.
Drawing a snowflake
import turtle
for i in range(8):
turtle.forward(50)
turtle.backward(50)
turtle.right(45)
turtle.right(90)
turtle.forward(50)
turtle.backward(50)
turtle.left(45)
for i in range(8):
turtle.forward(50)
turtle.backward(50)
turtle.left(45)
turtle.right(45)
turtle.forward(50)
turtle.backward(50)
turtle.right(90)
turtle.forward(50)
turtle.backward(50)
turtle.left(45)
for i in range(8):
turtle.forward(50)
turtle.backward(50)
turtle.right(45)
turtle.done()
This code imports the turtle library and uses a series of forward(), backward(), right(), and
left() functions to draw a snowflake.
Next: Can you develop the snowflake so that it has more detail?
Delaying for a certain number of seconds
import time
print("Hello")
time.sleep(2)
print(“World!")
This code imports the time library and uses the sleep() function to delay the program for 2
seconds after printing "Hello", and then prints "World!".
Next: Write a quiz where the answer is revealed after 10 seconds.
Number guessing game with tips
import random
number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
while guess != number:
if guess < number:
print("Too low")
else:
print("Too high")
guess = int(input("Guess again: "))
print("Congratulations, you guessed the number!”)
This code is a simple number guessing game where the user has to guess a random number
between 1 and 10. It uses a while loop to keep asking the user to guess until they get it right.
Next: Alter the game so that it is a random number between 1 and 20.
Guess the number game with loop
import random
number = random.randint(1, 10)
while True:
guess = int(input("Guess a number between 1 and 10: "))
if guess == number:
print("Congratulations! You guessed the number.")
break
else:
print("Sorry, you guessed the wrong number. Please try
again.")
print("Thanks for playing!”)
This code uses a while loop to keep prompting the user for guesses until they get the correct
answer. If the user guesses correctly, the code congratulates them and exits the loop using
the break statement. If the user guesses incorrectly, the loop continues and the user is
prompted to guess again. Once the loop exits, the code prints a final message to thank the
user for playing.
Rock, Paper, Scissors game
import random
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
player_choice = input("Choose rock, paper, or scissors: ")
print("Computer chose", computer_choice)
if player_choice == computer_choice:
print("Tie!")
elif player_choice == "rock" and computer_choice == "scissors":
print("You win!")
elif player_choice == "paper" and computer_choice == "rock":
print("You win!")
elif player_choice == "scissors" and computer_choice == "paper":
print("You win!")
else:
print("Computer wins!”)
This code is a simple rock, paper, scissors game where the user plays against the computer. It
uses a series of if-else statements to determine the winner based on the choices made.
Next: Make the game futuristic – turn it into ‘Hammer, Mirror, Laser!’
Hangman game
import random
words = ["apple", "banana", "cherry", "orange", "pear"]
word = random.choice(words)
letters = set(word)
alphabet = set("abcdefghijklmnopqrstuvwxyz")
used_letters = set()
while len(letters) > 0:
print("Word:", " ".join([letter if letter in used_letters else
"_" for letter in word]))
guess = input("Guess a letter: ").lower()
if guess in alphabet - used_letters:
used_letters.add(guess)
if guess in letters:
letters.remove(guess)
else:
print("Letter not in word")
elif guess in used_letters:
print("You already used that letter")
else:
print("Invalid character")
print("Congratulations, you guessed the word", word)
This code is a simple Hangman game where the user has to guess a randomly chosen word by
guessing letters one at a time. It uses a while loop and sets to keep track of the guessed
letters and the letters in the word.
Next: Add more words to the game so that it is harder for the player.
Password generator
import random
import string
def generate_password(length):
letters = string.ascii_letters + string.digits +
string.punctuation
return ''.join(random.choice(letters) for i in range(length))
password_length = int(input("Enter password length: "))
password = generate_password(password_length)
print("Your password is:", password)
This code uses the random and string libraries to generate a string of letters, digits, and
punctuation marks, and then selects a random character from that string for the specified
length. You can customize the set of characters used for generating the password by
modifying the letters variable.
Next: Provide the user with two password options.
A code that checks if a password is valid
password = input("Enter a password: ")
if len(password) < 8:
print("Password is too short")
else:
print("Password is valid”)
Next: Change the required length for the password.
A code that determines if a student passed or failed an exam
score = int(input("Enter the exam score: "))
if score >= 60:
print("Student passed")
else:
print("Student failed”)
Next: When the student finds out they have failed, inform them how many more marks they
need to reach the pass mark.
A code that checks if a year is a leap year
year = int(input("Enter a year: "))
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print("The year is a leap year")
else:
print("The year is not a leap year")
Next: Change the message at the end of the script.
A really simple chatbot code in Python
print("Hi, I'm a chatbot. What's your name?")
name = input()
print("Nice to meet you, " + name + ". How are you doing today?")
response = input()
print("Glad to hear that. What can I help you with?")
question = input()
print("Sorry, I'm not sure how to answer that.”)
This code simply greets the user, asks them how they're doing, and then asks if there's
anything it can help them with. The chatbot currently doesn't have any knowledge or
understanding, so it just responds with a generic message. You can add more functionality to
the chatbot by creating a more complex set of if-else statements.
Next: Add more responses to the chatbot and explore the use of if-else statements.