2 Programming Fundamentals
2.1 Variables, Naming, and Scope
- Local variables (TBA)
- Global variables (TBA)
- Constants
- Variable naming conventions
Variables
A variable is a name that refers to a value. Think of variables as containers that store information in your program. Since the data stored in a variable can be changed, it is called a “variable.”
To create a variable, we can write an assignemt statement. In game development, you’ll use variables to keep track of things like player scores, health points, or character positions.
variable-assignment.py
# Creating and using variables
player_name = "Jimmy" # Stores player's name
player_score = 0 # Tracks player's score
is_game_over = False # Checks if game is finished
health = 100.0 # Player's health pointsA common way to represent variables in pseudocode is to write the variable name with an arrow pointing from its assigned value. Pseudocode will be introduced later.
player_name ← "Jimmy"
player_score ← 0
is_game_over ← False
health ← 100.0
See Section 2.1
Constants
What is a constant?
A constant is a variable whose value is intended to remain unchanged throughout the program.
Why use constants?
Using constants improves code readability and prevents accidental modification of critical values, ensuring consistent behaviour in your program.
Constants in Python
Python does not have a dedicated syntax for constants. Instead, constants are declared using ALL_CAPS naming convention to signal to developers that the value should not be altered.
Example:
PI = 3.14159
MAX_USERS = 100Although Python allows you to modify these values, it is best practice not to.
Variable Naming Conventions
Variable names in Python can be as long as you like and can contain both letters and numbers. The underscore character (_) is the only allowed punctuation symbol. While uppercase letters are legal, we conventionally use lowercase for variable names.
Basic Rules
# VALID variable names:
name = "Alex"
player_score = 100
level1 = 1
airspeed_of_unladen_swallow = 20 # Can be as long as needed
# INVALID variable names:
1level = 1 # Can't start with a number
player-score = 100 # Can't use hyphens
my name = "Alex" # Can't have spacesKeywords - Reserved Names
Python has special words called keywords that are used to structure your program. These words cannot be used as variable names:
# INVALID - using keywords as variables:
if = "something" # 'if' is a keyword
for = 5 # 'for' is a keyword
class = "Year 10" # 'class' is a keyword
# Common Python keywords:
# if, else, for, while, def, class, return, True, False, and, or, not, in, isAnswer: Python keywords are reserved for specific functionalities in the language, and using them as variable names would cause a syntax error.
Snake Case Naming Style
We use snake_case in Python (lowercase with underscores):
# GOOD (snake_case):
player_name = "Alex"
current_score = 100
is_game_active = True
# NOT RECOMMENDED:
PlayerName = "Alex" # Looks like a class name
currentScore = 100 # This is camelCase (used in other languages)
is_Game_Active = True # Mixed style is confusingMake Names Meaningful
# BAD - too vague:
x = 100
n = "Alex"
b = True
# GOOD - clear purpose:
score = 100
name = "Alex"
is_playing = TrueCommon Patterns
Start variable names with: - is_ or has_ for booleans - num_ or count_ for numbers that count things
is_alive = True
has_key = False
num_players = 4
count_lives = 3Hungarian Notation
This is an older naming convention where the variable name starts with the type. While not commonly used in Python, you might see it in other languages or older code:
# Hungarian notation examples:
# String
strName = "Alex" # Camel case: str for string
str_name = "Alex" # Snake case: str for string
# Integer
intAge = 15 # Camel case: int for integer
int_age = 25 # Snake case: int for integer
# Float
fltSpeed = 7.5 # Camel case: flt for float
flt_speed = 7.5 # Snake case: flt for float
# Boolean
boolIsAlive = True # Camel case: bool for boolean
bool_is_alive = True # Snake case: bool for booleanCamel Case
While Python uses snake_case, other programming languages often use camel case. There are two types:
camelCase (Lower Camel Case)
Used for variable names in languages like JavaScript and Java:
# camelCase examples:
playerName = "Alex"
currentScore = 100
isGameActive = True
# In Python, we prefer:
player_name = "Alex"
current_score = 100
is_game_active = TruePascalCase (Upper Camel Case)
Used for class names in many languages, including Python:
# PascalCase examples:
class PlayerCharacter: # Good for class names
class GameLevel: # Good for class names
# But for variables, we use snake_case:
player_character = "Alex"
game_level = 1Answer:
- int_user_number: Uses Hungarian Notation but based on the snake case. This is not standard in Python.
- CalculateArea: Uses Camel Case (Pascal variation), typically for class names in Python, not functions.
- MAX_LIMIT: Follows the convention for constants (ALL_CAPS).
- tempVal: Uses Camel Case, which is not standard in Python (should be temp_val).
- Make them descriptive but concise
- Keep them easy to type and read
- Use consistent style throughout your code
- For special types:
- Use
is_orhas_prefix for booleans - Use
num_orcount_for counting variables
- Use
- Consider your audience:
- Will others understand your variable names?
- Will you understand them in a month?
- Follow Python conventions:
- Use snake_case for variable names
- Use PascalCase for class names
- Create meaningful names that describe the purpose
- Never use Python keywords
- Avoid single letters (except in very simple loops)
2.2 Data Types
- text (character, string)
- numeric (integer, floating point, date/time)
- Boolean
Every programming language uses data types to store different kinds of information. Let’s learn about Python’s built-in data types first before exploring more complex ones.
Here are the main built-in types in Python:
Text (String): Used for storing text of any length
Examples:"A","Hello, World!",'Python'Numeric: Used for storing numbers
Two main types:- Integer: Whole numbers
Examples:42,-10,0,1000 - Float: Decimal numbers
Examples:3.14,-0.01,2.0
- Integer: Whole numbers
Boolean: Used for storing
TrueorFalsevalues
Examples:True,False
Additional types you’ll learn later:
- Date/Time: For working with dates and times
Example:2024-11-23,14:30:00
Note: This requires Python’stimeordatetimelibrary
Text (Strings)
Text in Python is handled using strings. A string can contain: - A single character: "A" - Multiple characters: "Hello" - Nothing (empty string): ""
You can create strings using either: - Single quotes: 'Hello' - Double quotes: "Hello"
# Both ways work the same
name1 = 'Alex'
name2 = "Alex"
empty_string = ""- hero: this is a varialbe, with quotation marks.
- ‘hero’: this is a string, enclosed by quotation marks.
Text Encoding
For English text, computers originally used ASCII (American Standard Code for Information Interchange):
- ‘A’ is stored as number 65
- ‘B’ is stored as number 66
- ‘C’ is stored as number 67
- ‘a’ is stored as number 97
- ‘b’ is stored as number 98
- ‘c’ is stored as number 99
See the full list of ASCII code: weblink
# You can see ASCII values using ord()
print(ord('A')) # Shows: 65
print(ord('B')) # Shows: 66
print(ord('a')) # Shows: 97Answer:
The ASCII code for each letter is a unique number stored in the computer as binary (a series of 1s and 0s). For example:
- The letter A is 65 in ASCII, stored as 01000001 in binary.
- You can “send” your name by using hand signals, clapping in patterns, or even flashing lights in binary for each ASCII value. Get creative and see if your partner can decode it!
For international text, Python uses Unicode (UTF-8), which can handle all languages:
greeting1 = "Hello" # English
greeting2 = "Bonjour" # French
greeting3 = "こんにちは" # Japanese
greeting4 = "你好" # ChineseInput and Output
When we get input from users or display output, Python handles it as text:
The IPO model stands for Input, Process, Output and describes how a program or system works. It involves taking input data, processing it, and producing an output.
In the code above:
- Which line represents the input, and how is it handled?
- Which line represents the process, and how is it performed?
- Which line represents the output, and how is it produced?
- All text in Python is stored as strings
- There is no separate character type
- User input is always received as text
- Python can handle text in any language through UTF-8
- ASCII is used for basic English text (A-Z, a-z)
Numeric Data Types
Python provides different ways to work with numbers. Let’s explore each type:
Integer (int)
Whole numbers without decimal points:
player_score = 100
lives = 3
level = -1
# Basic operations with integers
score = 10 + 5 # Addition
health = 100 - 20 # Subtraction
bonus = 2 * 5 # Multiplication
players = 10 // 3 # Integer division (result: 3)
remainder = 10 % 3 # Modulus (remainder: 1)Floating Point (float)
Numbers with decimal points:
speed = 7.5
temperature = -2.8
pi = 3.14159
# Operations with floats
distance = 5.0 * 2.5 # Result: 12.5
average = 10.0 / 3.0 # Result: 3.333...
power = 2.0 ** 3 # Power (result: 8.0)Converting Between Types
# String to number
text_number = "42"
number = int(text_number) # Convert to integer
decimal = float(text_number) # Convert to float
# Rounding numbers
price = 19.99
rounded = round(price) # Result: 20Date and Time
Python provides a simple way to handle dates and times using the time module and its ctime function. The ctime function converts a timestamp into a readable string.
Key Points:
- In some languages, like C, date and time are often treated as numbers, typically representing the number of seconds since a specific starting point (usually January 1, 1970).
- Timestamps: A timestamp is a numerical representation of time (seconds since January 1, 1970, UTC).
- Readable Time: ctime takes the timestamp and converts it into a human-readable format (e.g., day, month, year, time).
Question: The code above gets the current time as a timestamp. Can you come up with a mathematical expression or approach to verify that the timestamp represents how many years since 1970?
Answer:
To calculate the number of years since 1970:
- Run the code to get the timestamp value
- Calculate the number of seconds in a year:
- Seconds in a year = 365.25 days × 24 hours × 60 minutes × 60 seconds = 31,557,600.
- Seconds in a year = 365.25 days × 24 hours × 60 minutes × 60 seconds = 31,557,600.
- Divide the timestamp by the number of seconds in a year::
timestamp / (365.25 * 24 * 60 * 60)
- Integers are for whole numbers (no decimal point)
- Floats are for decimal numbers
- Converting text to numbers needs special functions
- Date/time operations need the
timemodule - Be careful with float calculations (they can have small rounding errors)
Boolean Data Type
Boolean values can only be True or False. They’re essential for making decisions in your code.
Basic Boolean Values
is_game_over = False
has_key = True
is_alive = TrueComparison Operations (Result in Boolean)
# Comparing numbers
score = 85
is_high_score = score > 80 # True
is_perfect = score == 100 # False
is_failing = score < 40 # False
# Comparing text
name = "Alex"
is_admin = name == "Admin" # False
is_empty = name == "" # False= and == in is_admin = name == "Admin"
=is the assignment operator. It is used to assign a value to a variable.
==is the equality operator. It checks whether two values are equal.
- Therefore,
is_admin = name == "Admin"first checks ifnameis “Admin” and assigns the result (TrueorFalse) tois_admin.
Common Comparison Operators
==Equal to!=Not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to
Logical Operators (and, or, not)
Boolean values can be combined using three logical operators:
# Using 'and' (both conditions must be True)
has_sword = True
has_shield = False
is_fully_armed = has_sword and has_shield # False
# Using 'or' (at least one condition must be True)
has_magic = True
has_weapon = False
can_fight = has_magic or has_weapon # True
# Using 'not' (reverses True/False)
is_game_over = False
is_game_active = not is_game_over # TrueUsing Booleans for Game Logic
health = 100
has_shield = True
is_powered_up = False
# Game conditions
can_play = health > 0 # True
is_invincible = has_shield and is_powered_up # False
needs_health = health < 50 # Falsetrueandfalseare not valid (must be capitalised)- Using
=instead of==for comparison - Comparing different data types
- Boolean values are either
TrueorFalse - Comparisons produce boolean results
and,or,notcombine boolean values- Spelling matters:
TrueandFalse(capital first letter)
2.3 Arithmetic Operations
Common Maths Operations
+Addition
-Subtraction
*Multiplication
/Division (result is a float)
//Integer Division
%Modulus (remainder)
**Power
Order of Operations (BIMDAS)
Python follows the BIMDAS rule for evaluating mathematical expressions:
1. Brackets: Solve anything inside brackets () first.
2. Indices: Evaluate powers or exponents (**).
3. Multiplication and Division: Solve from left to right.
4. Addition and Subtraction: Solve from left to right.
Example:
String Operations with + and *
Strings have special behavior with these operators:
# Adding strings (concatenation)
first = "Hello"
second = "World"
message = first + " " + second # Result: "Hello World"
# Multiplying strings (repetition)
star_line = "*" * 10 # Result: "**********"
wow = "wow" * 3 # Result: "wowwowwow"Rounding Behavior in Python
Python uses “round to even” rule for .5 cases.
Why? This reduces bias in statistical calculations
Floating Point Precision
Due to how computers store decimal numbers, some calculations might surprise you:
- String concatenation (+) and repetition (*) are different from numeric operations
- Be aware of Python’s “round to even” rule
- For precise decimal calculations, consider using the
decimalmodule
number = "2"
# print(number + 3) # Error! Can't add string and number
print(number + "3") # Works: "23" (string concatenation)
print(int(number) + 3) # Works: 5 (number addition)
2.5 Quick Tip List
2.6 Exercise
Fix the Variables
These variables have naming problems. Fix them:
Pancake Recipe Calculator
Use the following code for questions below:
Questions:
- Variables and Constants:
- Find one constant in the code. How can you tell it’s a constant?
- What naming convention is used for variables in this code?
- List two reasons why this naming convention is important in Python.
- Data Types:
- What data type is flour_cups?
- What data type is eggs_count?
- What data type is is_vegetarian?
- What data type is new_flour?
- What data type is “cups” in the print statement?
- Arithmetic Operations:
- Find two different arithmetic operations in the code
- What does the scaling_factor calculation do?
- Comments:
- Why is the first comment useful?
- If you think it’s not useful, how would you rewrite it to make it more meaningful?
- Output:
- Given
desired_servings = 3.75, inspect the output. Do you think the output is clear and effective? Why or why not? - What improvements could you suggest to make the output more user-friendly?
- Given
Pancake Survey
Here’s a partially completed survey program. Your tasks:
- Complete the revenue calculation (each pancake costs $3.50)
- Format the output to match the example below
Your output should look like this:
=== MONTHLY PANCAKE SURVEY ===
------------------------------
CUSTOMER PROFILE:
Regular customer? ✓
------------------------------
ORDERING HABITS:
Favorite topping: maple syrup
Monthly pancake count: 12
Monthly revenue: $ 42.0
------------------------------
SATISFACTION:
Rating: ★★★★★★★★★ (9.5/10)
Here’s a brief explanation of those two Python features:
"✓" if is_regular_customer else "✗"- This is a simple way to pick between two values
- If is_regular_customer is True, shows ✓
- If is_regular_customer is False, shows ✗
f"({rating_out_of_ten}/10)"- The f before the string means we can put variables inside {}
- It will show the value of rating_out_of_ten followed by /10
- For example: (9.5/10)
2.7 Mini-Project: Big Five Wellbeing Calculator
Goals
- Develop a calculator that performs basic arithmetic operations.
- Implement best practices for code comments and documentation.
- Understand usability and user experience in coding.
- Collaborate to analyse and improve solutions.
- Explore creative extensions to enhance functionality.
Design Brief
Design a calculator using the Big Five Check-In framework to evaluate a user’s daily wellbeing. The program should prompt users to rate themselves on a scale of 1–5 across five key areas and calculate their overall wellbeing score. The calculator will display the results in a clear and engaging format, offering users meaningful insights into their daily habits.

Example Soltuion Output:
Output of Solution
Welcome to the Big Five Wellbeing Calculator!
Rate yourself from 1 to 5 for each of the following areas:
1 = Not at all, 2 = A little, 3 = Neutral, 4 = Quite a bit, 5 = Very much
What is your name? Jimmy
How old are you? 17
1. Did you feel positive today? 4
2. Did you exercise today? 1
3. Did you eat healthy today? 3
4. Did you drink enough water today? 4
5. Did you sleep deeply last night? 4
Jimmy's Wellbeing Report Card (Age: 17)
Feel Positive: ⭐⭐⭐⭐
Exercise Daily: ⭐
Eat Healthy: ⭐⭐⭐
Drink Water: ⭐⭐⭐⭐
Sleep Deeply: ⭐⭐⭐⭐
Overall Wellbeing Score: ⭐⭐⭐ (3.2/5)
Group Activity Steps
- Inspect the Example Solution Output
- Examine the provided output carefully.
- What aspects do you like, and what could be improved?
- Focus on elements such as clarity, usability, and completeness of the solution.
- Examine the provided output carefully.
- Plan Your Solution
- Decide what your code will do.
- Will it replicate the existing features or include additional ones (e.g., personalised messages, better formatting, enhanced feedback)?
- Comments should be used to explain the purpose of each part of your code, making it easier for others to understand and maintain.
- Decide what your code will do.
- Consider Usability
- How can your program make it easier for users to interact with?
- Discuss ways to provide clear instructions, helpful error messages, or a more engaging output design.
- How can your program make it easier for users to interact with?
- Write a Report
- Document your group’s project log as you develop the calculator.
- Include specific details about the changes you plan to make and why they are important.
- Document your group’s project log as you develop the calculator.
- Present Your Solution
- Share your solution with the class in a method you choose.
- Use the scoring card to gather feedback, document suggestions for improvement, and evaluate your performance.
- Share your solution with the class in a method you choose.
- Discuss Possible Extensions (Optional)
- Consider how the calculator could be enhanced if developed for a client.
- What additional features or extensions might the client request?
- Examples include tracking scores over time, integrating health tips, or visualising results with graphs.
- Consider how the calculator could be enhanced if developed for a client.
Partial Code
big-five-check-in.py
# Big Five Wellbeing Calculator
print("Welcome to the Big Five Wellbeing Calculator!")
...
# Collect user details
name = input("What is your name? ")
...
# Collect ratings
feel_positive = int(input("1. Did you feel positive today? "))
...
# Calculate average score
wellbeing_score = ...
# Create a wellbeing report card with emojis
print("\n" + name + "'s Wellbeing Report Card (Age: " + age + ")")
...2.8 AI Task: Code Review and Enhancement
In this task, you will use AI to review and improve your Big Five Wellbeing Calculator code, focusing on the concepts covered in this chapter: data types, naming conventions, and comments.
You can choose an AI tool such as ChatGPT, Claude, Gemini, or another approved LLM.
Here’s a reviewed version for improved clarity and engagement:
Part 1: Initial Code Review
Use ChatGPT to review your code with the following prompts:
Please review my wellbeing calculator code and suggest improvements for:
1. Variable naming (following Python conventions)
2. Selecting appropriate data types for variables
3. Improving the clarity and usefulness of comments
4. Enhancing code organisation for readability
Here’s my code: [paste your code]
After receiving the feedback, copy and save the AI-suggested code for reference and future use.
Part 2: Specific Improvements
Identify a specific area of your code that you want to improve, such as comments or documentation.
You can also create and use your own prompts for the selected area.
Comments and Documentation
Please help me enhance the comments in my code to:
- Clearly explain the purpose of each section
- Document any assumptions made
- Clarify complex calculations
- Avoid obvious or redundant comments
Once you receive the AI-suggested improvements, copy and save the updated code for reference and future use.
Part 3: Reflection
After completing the AI initial code review and specific improvements, reflect on the following:
- What were the most useful improvements suggested by the AI?
- How did the AI help you better understand coding practices and standards?
- How can you apply these improvements to your future projects?
- What challenges did you face while working with the AI, and how did you address them?
- Ask for detailed explanations, not just solutions.
- Compare multiple suggestions to determine the best approach.
- Focus on understanding why changes improve your code.
- Ensure all suggestions align with your project requirements.
- Test and validate AI recommendations before implementation.
2.4 Comments and Code Maintenance
Writing Comments in Python
Comments are notes we write in our code to explain what it does. They are ignored by Python when running the programme.
Single Line Comments
Use
#for single line comments:Multi-line Comments
For longer explanations, use three quotes
"""or''':Here’s the callout-note explaining the use of triple quotes for strings:
Triple quotes
"""or'''are not just for comments—they can also be used to create multi-line strings!For example:
This is especially useful for storing multi-line text directly in your program.
Three Principles of Good Comments
+=for IncrementingIn Python, the expression
score = score + 1can be simplified using the shorthand operator+=. This makes your code more concise and easier to read, i.e.score += 1Examples of Good Comments
Using Stubs in Comments
Stubs are placeholder comments used to indicate where functionality will be added in the future. They help outline the structure of your code and remind you or other developers to implement specific features later. For example:
Stubs are especially useful during the planning stage or when breaking down complex projects into smaller, manageable tasks.
Remember: - Comments help others understand your code - Write comments that add useful information - Keep the same style throughout your code - Don’t write comments for obvious things
Consider the following code and its comment:
Ask yourself:
Would you keep, revise, or remove this comment? Why?