Output

						

Python Procedural Programming Reference Guide for Beginners

Welcome to this beginner-friendly guide on procedural programming in Python! This guide will walk you through the fundamental constructs of Python programming, including simple outputs, variables, inputs, selection, iteration, string handling, error handling, and functions with parameter passing. Each section includes explanations and examples to help you grasp the concepts easily.


Table of Contents

  1. Simple Outputs
  2. Variables
  3. Inputs
  4. Selection
  5. Iteration
  6. String Handling
  7. Error Handling
  8. Functions with Parameter Passing
  9. Reading and Writing to Files

1. Simple Outputs

The print() Function

The print() function is used to display information to the console.

Syntax:

print(object, ..., sep=' ', end='\n')
  • object: The value or expression to display.
  • sep: Separator between objects (default is a space).
  • end: What to print at the end (default is a newline).

Example

# Simple output
print("Hello, World!")

# Outputting multiple objects
print("The sum of 2 and 3 is", 2 + 3)

Output:

Hello, World!
The sum of 2 and 3 is 5

2. Variables

Variables store data that can be used and manipulated in your program.

Variable Assignment

Assign values to variables using the = operator.

Example:

# Assigning variables
name = "Alice"
age = 25
height = 5.6

Data Types

  • Integer (int): Whole numbers (e.g., 1, 42)
  • Floating-point (float): Decimal numbers (e.g., 3.14, 0.001)
  • String (str): Text data (e.g., "hello", 'world')
  • Boolean (bool): Logical values (True or False)

Example:

# Different data types
is_student = True
score = 3.75

# Printing variable values
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
print("Score:", score)

Output:

Name: Alice
Age: 25
Height: 5.6
Is Student: True
Score: 3.75

3. Inputs

Collect input from the user using the input() function.

The input() Function

Syntax:

variable = input(prompt)
  • prompt: The message displayed to the user.

Example

# Getting user input
name = input("Enter your name: ")
print("Hello,", name)

Output:

Enter your name: Bob
Hello, Bob

Casting Input

By default, input() returns a string. To work with other data types, cast the input.

Example:

age = int(input("Enter your age: "))
print("You are", age, "years old.")

Output:

Enter your age: 30
You are 30 years old.

4. Selection

Control the flow of your program using conditional statements.

if Statements

Execute code only if a condition is true.

Syntax:

if condition:
	# code block

if-else Statements

Provide an alternative when the condition is false.

Syntax:

if condition:
	# code block if condition is true
else:
	# code block if condition is false

if-elif-else Statements

Check multiple conditions.

Syntax:

if condition1:
	# code block
elif condition2:
	# code block
else:
	# code block

Example

age = int(input("Enter your age: "))

if age >= 18:
	print("You are an adult.")
elif age >= 13:
	print("You are a teenager.")
else:
	print("You are a child.")

Output:

Enter your age: 16
You are a teenager.

5. Iteration

Repeat code using loops.

for Loops

Iterate over a sequence.

Syntax:

for variable in sequence:
	# code block

Example

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
	print(fruit)

Output:

apple
banana
cherry

while Loops

Repeat as long as a condition is true.

Syntax:

while condition:
	# code block

Example

# Counting down from 5
count = 5
while count > 0:
	print(count)
	count -= 1
print("Blast off!")

Output:

5
4
3
2
1
Blast off!

6. String Handling

Manipulate and work with text data.

String Literals

Strings can be enclosed in single ('), double ("), or triple quotes (''' or """).

Concatenation

Combine strings using the + operator.

Example:

greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)

Output:

Hello, Alice!

String Methods

Common methods to manipulate strings:

  • .upper() - Converts to uppercase
  • .lower() - Converts to lowercase
  • .strip() - Removes leading/trailing whitespace
  • .replace(old, new) - Replaces substrings
  • .split(separator) - Splits the string

Example:

text = "  Hello World!  "
print(text.strip())
print(text.upper())
print(text.replace("World", "Python"))

Output:

Hello World!
HELLO WORLD!
Hello Python!

Slicing Strings

Extract substrings using indexing.

Syntax:

substring = string[start:end]
  • start: Starting index (inclusive)
  • end: Ending index (exclusive)

Example:

text = "Hello, World!"
print(text[7:12])

Output:

World

7. Error Handling

Manage errors gracefully using try and except blocks.

try and except Blocks

Syntax:

try:
	# code that might raise an exception
except ExceptionType:
	# code to handle the exception

Example

try:
	numerator = int(input("Enter numerator: "))
	denominator = int(input("Enter denominator: "))
	result = numerator / denominator
	print("Result:", result)
except ValueError:
	print("Please enter valid integers.")
except ZeroDivisionError:
	print("Cannot divide by zero.")

Output:

Enter numerator: 10
Enter denominator: 0
Cannot divide by zero.

8. Functions with Parameter Passing

Organize code into reusable blocks using functions.

Defining Functions

Syntax:

def function_name(parameters):
	# code block
	return value

Parameters and Arguments

  • Parameters: Variables listed in the function definition.
  • Arguments: Values passed to the function when called.

Example

def greet(name):
	return "Hello, " + name + "!"

message = greet("Bob")
print(message)

Output:

Hello, Bob!

Return Values

Functions can return values using the return statement.

Example:

def add(a, b):
	return a + b

sum = add(5, 7)
print("Sum:", sum)

Output:

Sum: 12

9. Reading and Writing to Files

Python allows you to read from and write to text files using built-in functions. This is especially useful for saving data, loading configurations, or processing information from external sources. In your Python editor, any text file you read or write will automatically create a new tab, where you can view and edit the contents of the file.

Opening Files

Syntax:

file = open('filename.txt', mode)
  • filename.txt: The name of the file you want to open. Make sure the file name matches the name of the tab in your IDE.
  • mode: Specifies the purpose of opening the file. Common modes include:
    • 'r': Read
    • 'w': Write
    • 'a': Append
    • 'r+': Read and write

Reading from a File

file = open('example.txt', 'r')
content = file.read()
file.close()
print(content)

Writing to a File

file = open('example.txt', 'w')
file.write("This is an example of writing to a file.\n")
file.close()

Using with Statement

with open('example.txt', 'r') as file:
	content = file.read()

print(content)

Conclusion

Congratulations! You've covered the fundamental constructs of procedural programming in Python. By understanding simple outputs, variables, inputs, selection, iteration, string handling, error handling, functions with parameter passing, and reading/writing to files, you're well on your way to becoming proficient in Python programming. Keep practicing and experimenting with these concepts to strengthen your skills.

Python Turtle Graphics Basics Reference Guide

1. Introduction to Turtle Graphics

The Python turtle module allows you to create pictures and shapes by providing a virtual canvas. It's an excellent way to learn programming and create graphics. In Skulpt, you can use turtle graphics directly in the browser.

2. Setting Up the Turtle Environment

Before you start drawing, you need to import the turtle module and create a turtle object:

import turtle
t = turtle.Turtle()

3. Basic Movement Commands

The turtle can move forward, backward, and turn left or right.

Forward and Backward

t.forward(100)  # Moves the turtle forward by 100 units
t.backward(50)  # Moves the turtle backward by 50 units

Turning Left and Right

t.left(90)   # Turns the turtle left by 90 degrees
t.right(45)  # Turns the turtle right by 45 degrees

[Add image of the turtle's path here]

4. Pen Control

You can control the pen to change its color, size, or lift it up and down.

Changing Pen Color

t.pencolor("red")       # Sets the pen color to red

Changing Pen Size

t.pensize(5)  # Sets the pen thickness to 5 units

Pen Up and Pen Down

t.penup()   # Lifts the pen; turtle moves without drawing
t.pendown() # Puts the pen down; turtle draws when moving

5. Drawing Basic Shapes

Drawing a Square

for _ in range(4):
    t.forward(100)
    t.right(90)

[Add image of the square here]

Drawing a Circle

t.circle(50)  # Draws a circle with radius 50 units

[Add image of the circle here]

6. Using Loops for Patterns

You can create complex patterns by combining loops with turtle commands.

Spiral Pattern Example

for i in range(36):
    t.forward(i * 5)
    t.right(144)

[Add image of the spiral pattern here]

7. Setting the Screen

The screen can be customized by setting its background color or size.

screen = turtle.Screen()
screen.bgcolor("lightblue")  # Sets the background color

8. Functions in Turtle Graphics

You can define functions to reuse drawing code.

Example: Drawing a Star

def draw_star(size):
    for _ in range(5):
        t.forward(size)
        t.right(144)

draw_star(100)

[Add image of the star here]

9. Changing Turtle Speed

Adjust the speed at which the turtle moves.

t.speed(1)   # Slowest speed
t.speed(10)  # Fastest speed

10. Hiding and Showing the Turtle

You can hide the turtle icon to see only the drawing.

t.hideturtle()  # Hides the turtle icon
t.showturtle()   # Shows the turtle icon again

Congratulations! You've covered the fundamentals of programming the Python Turtle module.

CSUK Tkinter – Python GUI Programming Guide

Welcome to CSUK Tkinter – a beginner-friendly Python library that lets you build real graphical applications using code.

With CSUK Tkinter, you can create windows, buttons, labels, input boxes, menus, graphics, and interactive programs – all using Python.

No previous GUI experience is required. If you know basic Python, you’re ready to begin.


Table of Contents

  1. Getting Started
  2. Windows and the Main Loop
  3. Displaying Text with Labels
  4. Buttons and User Interaction
  5. User Input with Entry Widgets
  6. Placing Widgets on the Screen
  7. Events and User Actions
  8. Using Variables (IntVar, StringVar)
  9. Drawing Graphics with Canvas
  10. Animation and Timers
  11. Menus and Menu Bars
  12. Best Practice for Student Programmers

1. Getting Started

To use CSUK Tkinter, import the library and create a window.

import tkinter as tk

root = tk.Tk()
root.mainloop()

This creates an empty window and starts the program.

Important: Your program will not run correctly without mainloop().

2. Windows and the Main Loop

The window you create is called the root window.

root = tk.Tk()
root.title("My First App")
root.geometry("400x300")
root.mainloop()

What is mainloop()?

mainloop() keeps your program running and listens for:

  • Mouse movement
  • Button clicks
  • Keyboard presses
  • Window events

Without it, your window would open and immediately close.


3. Displaying Text with Labels

A Label displays text on the screen.

label = tk.Label(root, text="Hello, World!")
label.pack()

Changing Colours and Fonts

label = tk.Label(
    root,
    text="Welcome!",
    bg="black",
    fg="white",
    font="16px sans-serif"
)
label.pack()

Labels are used for titles, instructions, and messages.


4. Buttons and User Interaction

Buttons let the user do something.

def say_hi():
    print("Hello!")

btn = tk.Button(root, text="Click Me", command=say_hi)
btn.pack()

When the button is clicked, the function runs.

Why Functions Matter

Buttons don’t run code immediately — they store a function and run it later.


5. User Input with Entry Widgets

An Entry widget lets the user type text.

entry = tk.Entry(root)
entry.pack()

def read_input():
    print(entry.get())

btn = tk.Button(root, text="Read", command=read_input)
btn.pack()

This is how you make forms, logins, and search boxes.


6. Placing Widgets on the Screen

Tkinter has three layout systems:

  • pack() – simple stacking
  • grid() – table layout
  • place() – exact positions

Using pack()

label.pack()
button.pack()

Using grid()

label.grid(row=0, column=0)
button.grid(row=1, column=0)

Using place()

label.place(x=50, y=100)
Rule: Never mix layout systems inside the same container.

7. Events and User Actions

Events let your program react to the keyboard and mouse.

def on_click(event):
    print(event.x, event.y)

root.bind("<Button-1>", on_click)

Common Events

  • <Button-1> – left click
  • <Motion> – mouse move
  • <KeyPress> – key pressed

8. Using Variables (IntVar, StringVar)

Tkinter variables keep your UI and code in sync.

count = tk.IntVar(0)

def add():
    count.set(count.get() + 1)

label = tk.Label(root, textvariable=count)
label.pack()

btn = tk.Button(root, text="Add", command=add)
btn.pack()

When the value changes, the screen updates automatically.


9. Drawing Graphics with Canvas

The Canvas lets you draw shapes, text, and animations.

canvas = tk.Canvas(root, width=300, height=200, bg="white")
canvas.pack()

ball = canvas.create_oval(50, 50, 100, 100, fill="red")

Moving Shapes

canvas.move(ball, 5, 0)

Canvas is used for games, simulations, and visualisations.


10. Animation and Timers

Tkinter uses after() for animation.

def move():
    canvas.move(ball, 2, 0)
    root.after(30, move)

move()

This creates smooth motion without freezing the program.


11. Menus and Menu Bars

Menus are used in real applications.

menu = tk.Menu(root)
root.config(menu=menu)

file_menu = tk.Menu(menu)
menu.add_cascade(label="File", menu=file_menu)

file_menu.add_command(label="Exit", command=root.destroy)

12. Best Practice for Student Programmers

  • Use functions to organise your code
  • Name widgets clearly
  • Start simple, then add features
  • Test after every change
  • Experiment and explore

GUI programming is where logic meets creativity.

Have fun building real apps 🖥️✨

CSUK SQLite – Python Databases Made Simple

Welcome to CSUK SQLite – a beginner-friendly version of Python’s sqlite3 library, designed to help you learn how real programs store, organise, and retrieve data.

This guide will take you from “What is a database?” to building and querying your own database, step by step.

No previous database knowledge is required – just basic Python.


Table of Contents

  1. What Is a Database?
  2. Getting Started with CSUK SQLite
  3. Connecting to a Database
  4. Creating Tables
  5. Inserting Data
  6. Selecting (Reading) Data
  7. Understanding Cursors
  8. Saving Changes with commit()
  9. Mini Project: School Database
  10. Best Practice for Students

1. What Is a Database?

A database is a structured way of storing data so that:

  • It can be saved permanently
  • It can be searched quickly
  • It can be organised into tables

Think of a database like a digital spreadsheet:

  • A database is the spreadsheet file
  • A table is one sheet
  • A row is one record
  • A column is one piece of information
Databases are used everywhere: schools, games, websites, apps, shops, and social media.

2. Getting Started with CSUK SQLite

To use CSUK SQLite, import the library exactly like normal Python:

import sqlite3

Behind the scenes, this uses csuk_sqlite3, but you don’t need to worry about that.


3. Connecting to a Database

The first step is to connect to a database file.

db = sqlite3.connect("school.db")
  • If the file exists, it is opened
  • If it does not exist, it is created

You can think of this as:

“Open the filing cabinet called school.db

4. Creating Tables

Data in a database is stored in tables.

Each table has:

  • A name
  • Column headings

Example: Creating a Table

cur = db.cursor()

cur.execute(
    "CREATE TABLE pupils (name TEXT, age INTEGER)"
)

This creates a table called pupils with two columns:

  • name – text
  • age – whole numbers

5. Inserting Data

To add data, we use INSERT INTO.

Example

cur.execute("INSERT INTO pupils VALUES ('Alice', 14)")
cur.execute("INSERT INTO pupils VALUES ('Bob', 15)")

Each line adds one row to the table.


6. Selecting (Reading) Data

To read data, we use SELECT.

Select All Rows

cur.execute("SELECT * FROM pupils")
rows = cur.fetchall()

print(rows)

This might output:

[['Alice', '14'], ['Bob', '15']]

Each row is a list of values.


7. Understanding Cursors

A cursor is like a pointer that:

  • Sends instructions to the database
  • Receives results back

You almost always use this pattern:

db = sqlite3.connect("data.db")
cur = db.cursor()

cur.execute("SQL COMMAND HERE")
Rule: Database = storage, Cursor = control

8. Saving Changes with commit()

Changes are NOT saved automatically.

You must call:

db.commit()

If you forget this:

  • Your data may disappear
  • Your table may not be saved

9. Mini Project: School Database

Complete Example

import sqlite3

db = sqlite3.connect("school.db")
cur = db.cursor()

cur.execute("CREATE TABLE pupils (name TEXT, age INTEGER)")
cur.execute("INSERT INTO pupils VALUES ('Alice', 14)")
cur.execute("INSERT INTO pupils VALUES ('Bob', 15)")

db.commit()

cur.execute("SELECT * FROM pupils")
rows = cur.fetchall()

for row in rows:
    print("Name:", row[0], "Age:", row[1])

This program:

  • Creates a database
  • Creates a table
  • Adds data
  • Reads and displays it

10. Best Practice for Students

  • Create tables before inserting data
  • Always use commit() after changes
  • Use meaningful table and column names
  • Print results to understand what’s happening
  • Think of databases as long-term memory

Databases turn programs from toys into real systems.

Have fun building with data 🗄️🐍

CSUK Pygame – Python Game Programming Guide

Welcome to CSUK Pygame – a Python game programming library that lets you build real-time games using code.

With CSUK Pygame, you can:

  • Draw shapes and images
  • Move objects with the keyboard and mouse
  • Create animated sprites
  • Detect collisions
  • Build full games using loops and logic

No previous game development experience is needed – just Python basics and curiosity.


Table of Contents

  1. Getting Started
  2. The Game Loop
  3. The Screen
  4. Drawing Shapes
  5. Keyboard Input
  6. Working with Images
  7. Sprites and Sprite Groups
  8. Collision Detection
  9. Structuring Games
  10. Best Practice for Student Game Developers

1. Getting Started

To use CSUK Pygame, start by importing pygame and creating a window.

import pygame

pygame.init()

screen = pygame.display.set_mode((400, 300))

This creates a game window that is 400 pixels wide and 300 pixels tall.


2. The Game Loop

Games are different from normal programs.

Instead of running once, a game:

  • Checks for input
  • Updates game objects
  • Draws everything
  • Repeats

This repetition is called the game loop.

Basic Game Loop

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

This loop keeps the game alive until the window is closed.


3. The Screen

Everything you draw appears on the screen surface.

Before drawing each frame, you should clear the screen.

Clearing the Screen

screen.fill((0, 0, 0))  # black background

Colors are written as RGB values:

  • (255, 0, 0) = red
  • (0, 255, 0) = green
  • (0, 0, 255) = blue

4. Drawing Shapes

You can draw basic shapes using pygame.draw.

Rectangle

pygame.draw.rect(
    screen,
    (255, 0, 0),
    (50, 100, 60, 40)
)

Circle

pygame.draw.circle(
    screen,
    (0, 255, 0),
    (200, 150),
    20
)

Shapes are useful for:

  • Prototypes
  • Hitboxes
  • Simple games

5. Keyboard Input

To move things, games need input.

CSUK Pygame lets you check which keys are being held down.

Checking Keys

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT]:
    print("Left arrow held")

Moving an Object

x = 100

if keys[pygame.K_RIGHT]:
    x += 5

This checks input every frame, which allows smooth movement.


6. Working with Images

Games usually use images instead of shapes.

Loading an Image

player_img = pygame.image.load(
    "https://example.com/player.png"
)

Images load automatically in the background.

Drawing an Image

screen.blit(player_img, (100, 200))

Images can also be resized:

player_img = pygame.transform.scale(
    player_img,
    (40, 40)
)

7. Sprites and Sprite Groups

Sprites combine:

  • An image
  • A position (rect)
  • Update logic

Sprites are the best way to build real games.

Creating a Sprite

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("player.png")
        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = 200

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= 5
        if keys[pygame.K_RIGHT]:
            self.rect.x += 5

Using Sprite Groups

player = Player()
players = pygame.sprite.Group(player)

players.update()
players.draw(screen)

Groups let you update and draw many sprites at once.


8. Collision Detection

Sprites use rectangles for collisions.

Checking Collisions

if player.rect.colliderect(enemy.rect):
    print("Collision!")

This is how games detect:

  • Hits
  • Damage
  • Pickups

9. Structuring Games

As games grow, structure matters.

Use Functions

def handle_events():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return False
    return True

Use Classes

  • Player
  • Enemy
  • Bullet

Each object should manage itself.


10. Best Practice for Student Game Developers

  • Think in frames
  • Update before drawing
  • Use sprites for moving objects
  • Keep one job per class
  • Start simple, then add features
  • Test often

Game development is problem solving, creativity, and logic combined.

Have fun building games 🎮

CSUK Sounds – Python Music Programming Guide

Welcome to CSUK Sounds – a beginner-friendly Python library that lets you create music using code. This guide will teach you how to structure music, play instruments together, add effects, load samples, and even create your own synth sounds.

No previous music theory is required – just curiosity and creativity!


Table of Contents

  1. Getting Started
  2. Understanding the Music Timeline
  3. Playing Notes
  4. Using Drums
  5. Playing Multiple Instruments Together
  6. Structuring Music with Bars
  7. Building Songs with Loops
  8. Adding Effects
  9. Loading and Playing Samples
  10. Creating Your Own Synths
  11. Best Practice for Student Composers

1. Getting Started

To use CSUK Sounds, import the library and set a tempo.

import csukSounds as sound

sound.set_tempo(120)

Tempo is measured in beats per minute (BPM).


2. Understanding the Music Timeline

CSUK Sounds uses a simple but powerful idea:

All sounds played before sleep() happen at the same time.

The sleep() function moves time forward.

Example

sound.kick()
sound.play("C2", 1)
sound.sleep(1)

This means:

  • The kick drum and bass note start together
  • The program waits for 1 beat before continuing

This is how real music sequencers work!


3. Playing Notes

The sound.play() Function

Plays a musical note using the current instrument.

Syntax:

sound.play(note, beats)
  • note: A note name like "C4", "E3", "G5"
  • beats: How long the note lasts (in beats)

Example

sound.use_instrument("piano")
sound.play("C4", 1)
sound.sleep(1)

4. Using Drums

CSUK Sounds includes built-in drum sounds.

  • sound.kick()
  • sound.snare()
  • sound.hihat()

Example

sound.kick()
sound.hihat()
sound.sleep(1)

sound.snare()
sound.sleep(1)

5. Playing Multiple Instruments Together

To play multiple instruments at the same time:

  1. Switch instrument
  2. Play notes
  3. Sleep after all sounds are queued

Example

sound.kick()

sound.use_instrument("bass")
sound.play("C2", 1)

sound.use_instrument("lead")
sound.play("E4", 1)

sound.sleep(1)

All three sounds start together.


6. Structuring Music with Bars

The best way to write music in code is to think in bars.

A bar is usually 4 beats.

One Bar as a Function

def bar():
    sound.kick()
    sound.use_instrument("bass")
    sound.play("C2", 1)
    sound.sleep(1)

    sound.snare()
    sound.use_instrument("bass")
    sound.play("G1", 1)
    sound.sleep(1)

    sound.kick()
    sound.sleep(1)

    sound.snare()
    sound.sleep(1)

This makes music:

  • Easier to read
  • Easier to repeat
  • Easier to remix

7. Building Songs with Loops

Once you have bars, you can loop them to create songs.

Example

while True:
    bar()

You can also create sections:

def chorus():
    for i in range(4):
        bar()

def intro():
    for i in range(2):
        bar()

intro()
chorus()

8. Adding Effects

Effects change how the sound feels.

Available Effects

  • reverb
  • delay
  • distortion

Example

sound.add_effect("reverb", decay=4, wet=0.5)
sound.add_effect("delay", time=0.25, feedback=0.4)

To remove all effects:

sound.clear_effects()

9. Loading and Playing Samples

Samples are recorded sounds loaded from a URL.

Loading a Sample

sound.load_sample(
    "clap",
    "https://example.com/clap.wav"
)

The program will wait until the sample is loaded.

Playing a Sample

sound.play_sample("clap")
sound.sleep(1)

10. Creating Your Own Synths

You can design your own instruments using code.

Basic Synth

sound.create_synth(
    "mySynth",
    oscillator={"type": "sawtooth"},
    envelope={
        "attack": 0.05,
        "decay": 0.2,
        "sustain": 0.6,
        "release": 0.4
    }
)

sound.use_instrument("mySynth")
sound.play("C4", 1)
sound.sleep(1)

FM Synth

sound.create_synth(
    "fmLead",
    type="fm",
    harmonicity=3,
    modulationIndex=10
)

11. Best Practice for Student Composers

  • Think in beats and bars
  • Queue sounds first, then sleep
  • Use functions to organise music
  • Start simple, then layer sounds
  • Experiment!

Music + code = creativity with logic.

Have fun composing 🎶

×

Unlock More with CSUK:Teacher!

Teachers, would you like solutions, a student workbook and tracking tool to accompany these challenges? Become a CSUK:Teacher member and get:

  • A Student Workbook to track and submit challenge progress.
  • A Teacher Tracking and Solutions Spreadsheet with coded solutions and tracking tools.

Join now to take your CS teaching to the next level!

CSUK's 101 Python Coding Challenges for Beginners

  1. Hello, World!
    Write a program that prints "Hello, World!" to the console.

  2. Input and Output
    Write a program that asks the user for their name and greets them.

  3. Simple Addition
    Write a program that adds two numbers provided by the user.

  4. Odd or Even
    Write a program that determines if a number is odd or even.

  5. Generate Multiplication Table
    Generate the multiplication table for a given number.

  6. Find ASCII Value of a Character
    Write a program that prints the ASCII value of a character.

  7. Simple Interest Calculator
    Calculate simple interest given principal, rate, and time.

  8. Area of a Circle
    Write a program to calculate the area of a circle given its radius.

  9. Area of a Triangle
    Calculate the area of a triangle given its base and height.

  10. Swap Two Variables
    Write a program to swap two variables without using a temporary variable.

  11. Random Number Generator
    Write a program that generates a random number between 1 and 100.

  12. Calculate the Sum of a List
    Write a program to calculate the sum of all numbers in a list.

  13. Generate a List of Even Numbers
    Write a program to generate a list of even numbers from 1 to 100.

  14. Calculate the Average of Numbers in a List
    Write a program to calculate the average of numbers in a list.

  15. Convert Celsius to Fahrenheit
    Write a program to convert temperature from Celsius to Fahrenheit.

  16. Simulate a Dice Roll
    Write a program to simulate rolling a dice.

  17. Leap Year Checker
    Write a program to check if a year is a leap year.

  18. Simple Calculator
    Create a calculator that can add, subtract, multiply, and divide two numbers.

  19. Factorial Calculator
    Write a program to calculate the factorial of a number.

  20. Fibonacci Sequence
    Generate the Fibonacci sequence up to a certain number of terms.

  21. ⭐⭐ Prime Number Checker
    Write a program to check if a number is prime.

  22. ⭐⭐ Largest of Three Numbers
    Write a program to find the largest among three numbers input by the user.

  23. ⭐⭐ Reverse a String
    Write a program that reverses a string input by the user.

  24. ⭐⭐ Palindrome Checker
    Write a program to check if a string is a palindrome.

  25. ⭐⭐ Count Vowels in a String
    Write a program that counts the number of vowels in a string.

  26. ⭐⭐ Sum of Digits
    Write a program to calculate the sum of digits of a number.

  27. ⭐⭐ Compound Interest Calculator
    Calculate compound interest given principal, rate, and time.

  28. ⭐⭐ Calculate the Length of a String
    Write a program to find the length of a string without using len().

  29. ⭐⭐ Count Words in a String
    Write a program that counts the number of words in a string.

  30. ⭐⭐ Sort a List
    Write a program to sort a list of numbers in ascending order.

  31. ⭐⭐ Remove Duplicates from a List
    Write a program to remove duplicates from a list.

  32. ⭐⭐ Count the Number of Uppercase and Lowercase Letters
    Write a program that counts uppercase and lowercase letters in a string.

  33. ⭐⭐ Calculate the Power of a Number
    Write a program to calculate the power of a number without using the ** operator.

  34. ⭐⭐ Check if a String is a Substring of Another String
    Write a program to check if one string is a substring of another.

  35. ⭐⭐ Find the Sum of a Series 1 + 1/2 + 1/3 + ... + 1/n
    Write a program to calculate the sum of the series up to n terms.

  36. ⭐⭐ Count the Occurrences of an Element in a List
    Write a program to count how many times an element occurs in a list.

  37. ⭐⭐ Merge Two Dictionaries
    Write a program to merge two dictionaries into one.

  38. ⭐⭐ Generate a Random OTP (One-Time Password)
    Write a program to generate a random 6-digit OTP.

  39. ⭐⭐ Convert a List into a Comma-Separated String
    Write a program to convert a list of numbers into a comma-separated string.

  40. ⭐⭐ Find the Longest Word in a Sentence
    Write a program to find the longest word in a given sentence.

  41. ⭐⭐ Find All Factors of a Number
    Write a program to find and display all the factors of a given positive integer. A factor is a number that divides another number completely without leaving any remainder.

  42. ⭐⭐ Check if a Number is a Perfect Square
    Write a program to check if a given number is a perfect square. A perfect square is a number that is the square of an integer.

  43. ⭐⭐ Reverse the Words in a Sentence
    Write a program that takes a sentence as input and reverses the order of words in the sentence.

  44. ⭐⭐ Check if Two Lists are Equal
    Write a program to check if two lists have the same elements in the same order.

  45. ⭐⭐ Calculate the Distance Between Two Points
    Write a program to calculate the Euclidean distance between two points in 2D space.

  46. ⭐⭐ Find the Intersection of Two Lists
    Write a program to find the elements common to two lists.

  47. ⭐⭐ Find the Union of Two Lists
    Write a program to find all unique elements from two lists.

  48. ⭐⭐ Find the Difference Between Two Lists
    Write a program to find elements present in one list but not the other.

  49. ⭐⭐ Calculate the Sum of Squares of First n Natural Numbers
    Write a program to calculate the sum of squares of first n natural numbers.

  50. ⭐⭐ Create a Mad Libs Game
    Write a program that asks the user for inputs and generates a funny story (Mad Libs).

  51. ⭐⭐⭐ Armstrong Number Checker
    Write a program to check if a number is an Armstrong number.

  52. ⭐⭐⭐ Quadratic Equation Solver
    Write a program to solve quadratic equations.

  53. ⭐⭐⭐ Rock, Paper, Scissors Game
    Create a simple rock, paper, scissors game against the computer.

  54. ⭐⭐⭐ Guess the Number Game
    Write a program where the computer chooses a number, and the user tries to guess it.

  55. ⭐⭐⭐ Remove Punctuation from a String
    Write a program that removes punctuation from a given string.

  56. ⭐⭐⭐ Merge Two Lists
    Write a program to merge two lists into a dictionary.

  57. ⭐⭐⭐ Find the Second Largest Number in a List
    Write a program to find the second largest number in a list.

  58. ⭐⭐⭐ Check for Anagrams
    Write a program to check if two strings are anagrams.

  59. ⭐⭐⭐ Find Common Elements in Two Lists
    Write a program to find common elements between two lists.

  60. ⭐⭐⭐ Fibonacci Series Using Recursion
    Write a recursive function to generate the Fibonacci series.

  61. ⭐⭐⭐ Factorial Using Recursion
    Write a recursive function to calculate the factorial of a number.

  62. ⭐⭐⭐ Calculate GCD of Two Numbers
    Write a program to find the greatest common divisor (GCD) of two numbers.

  63. ⭐⭐⭐ Calculate LCM of Two Numbers
    Write a program to find the least common multiple (LCM) of two numbers.

  64. ⭐⭐⭐ Check for Armstrong Numbers in an Interval
    Find all Armstrong numbers between two given numbers.

  65. ⭐⭐⭐ Check for Prime Numbers in an Interval
    Find all prime numbers between two given numbers.

  66. ⭐⭐⭐ Check if a String is a Pangram
    Write a program to check if a string contains all letters of the alphabet.

  67. ⭐⭐⭐ Count the Frequency of Words in a String
    Write a program to count the frequency of each word in a string.

  68. ⭐⭐⭐ Print the Following Pattern
    						*
    						**
    						***
    						****
    						*****
    								

  69. ⭐⭐⭐ Print the Reverse of the Above Pattern
    						*****
    						****
    						***
    						**
    						*
    								

  70. ⭐⭐⭐ Print a Pyramid Pattern
    						   *
    						  ***
    						 *****
    						*******
    								

  71. ⭐⭐⭐ Simple Number Guessing Game
    Create a game where the user has limited attempts to guess a number.

  72. ⭐⭐⭐ Convert Decimal to Binary
    Write a program to convert a decimal number to binary.

  73. ⭐⭐⭐ Convert Binary to Decimal
    Write a program to convert an integer binary number to decimal.

  74. ⭐⭐⭐ Check if a Number is a Perfect Number
    Write a program to check if a number is perfect (sum of its proper divisors equals the number).

  75. ⭐⭐⭐ Check if a Number is a Strong Number
    Write a program to check if a number is a strong number (sum of factorial of its digits equals the number).

  76. ⭐⭐⭐ Check if a Number is a Happy Number
    Write a program to check if a number is a happy number.

  77. ⭐⭐⭐ Find the HCF and LCM of Multiple Numbers
    Write a program to find the HCF and LCM of a list of numbers.

  78. ⭐⭐⭐ Generate a Random Password
    Write a program to generate a random password containing letters and numbers.

  79. ⭐⭐⭐ Implement Binary Search
    Write a program to perform binary search on a sorted list.

  80. ⭐⭐⭐ Implement Bubble Sort
    Write a program to sort a list using bubble sort algorithm.

  81. ⭐⭐⭐ Implement Selection Sort
    Write a program to sort a list using selection sort algorithm.

  82. ⭐⭐⭐ Implement Insertion Sort
    Write a program to sort a list using insertion sort algorithm.

  83. ⭐⭐⭐ Transpose a Matrix
    Write a program to transpose a 2D matrix.

  84. ⭐⭐⭐ Calculate the Sum of Diagonals in a Matrix
    Write a program to calculate the sum of the main and secondary diagonals in a square matrix.

  85. ⭐⭐⭐ Check if a String is a Palindrome Using Recursion
    Write a recursive function to check if a string is a palindrome.

  86. ⭐⭐⭐ Find the Max and Min in a List Without Using Built-in Functions
    Write a program to find the maximum and minimum numbers in a list without using built-in functions.

  87. ⭐⭐⭐ Check if a String is a Valid Email Address
    Write a program to validate an email address.

  88. ⭐⭐⭐ Find the Most Frequent Element in a List
    Write a program to find the most frequent element in a list.

  89. ⭐⭐⭐ Implement a Stack Using a List
    Write a program to implement a stack using a list.

  90. ⭐⭐⭐ Implement a Queue Using a List
    Write a program to implement a queue using a list.

  91. ⭐⭐⭐ Flatten a Nested List
    Write a program to flatten a list that contains nested lists.

  92. ⭐⭐⭐ Generate a Deck of Cards
    Write a program to generate a standard deck of 52 cards.

  93. ⭐⭐⭐ Implement Caesar Cipher Encryption
    Write a program to encrypt a message using Caesar cipher.

  94. ⭐⭐⭐ Implement Caesar Cipher Decryption
    Write a program to decrypt a message encrypted with Caesar cipher.

  95. ⭐⭐⭐ Check if a String is a Valid Palindrome Ignoring Spaces
    Write a program to check if a string is a palindrome, ignoring spaces and punctuation.

  96. ⭐⭐⭐ Check if All Characters in a String are Unique
    Write a program to determine if a string has all unique characters.

  97. ⭐⭐⭐ Implement a Simple Calculator Using Functions
    Write a program to create a simple calculator using functions for each operation.

  98. ⭐⭐⭐ Check if a Number is a Fibonacci Number
    Write a program to check if a given number is in the Fibonacci sequence.

  99. ⭐⭐⭐ Print the First n Prime Numbers
    Write a program to print the first n prime numbers.

  100. ⭐⭐⭐ Find the Smallest Missing Positive Integer
    Write a program to find the smallest positive integer missing from a list.

  101. ⭐⭐⭐ Generate All Permutations of a String
    Write a program to generate all permutations of a given string.
Scroll to Top