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
- Simple Outputs
- Variables
- Inputs
- Selection
- Iteration
- String Handling
- Error Handling
- Functions with Parameter Passing
- 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 (TrueorFalse)
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
- Getting Started
- Windows and the Main Loop
- Displaying Text with Labels
- Buttons and User Interaction
- User Input with Entry Widgets
- Placing Widgets on the Screen
- Events and User Actions
- Using Variables (IntVar, StringVar)
- Drawing Graphics with Canvas
- Animation and Timers
- Menus and Menu Bars
- 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
- What Is a Database?
- Getting Started with CSUK SQLite
- Connecting to a Database
- Creating Tables
- Inserting Data
- Selecting (Reading) Data
- Understanding Cursors
- Saving Changes with commit()
- Mini Project: School Database
- 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– textage– 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
- Getting Started
- The Game Loop
- The Screen
- Drawing Shapes
- Keyboard Input
- Working with Images
- Sprites and Sprite Groups
- Collision Detection
- Structuring Games
- 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
- Getting Started
- Understanding the Music Timeline
- Playing Notes
- Using Drums
- Playing Multiple Instruments Together
- Structuring Music with Bars
- Building Songs with Loops
- Adding Effects
- Loading and Playing Samples
- Creating Your Own Synths
- 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:
- Switch instrument
- Play notes
- 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
reverbdelaydistortion
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 🎶