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 points

A 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 = 100

Although 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 spaces

Keywords - 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, is

Answer: 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 confusing

Make Names Meaningful

#  BAD - too vague:
x = 100
n = "Alex"
b = True

#  GOOD - clear purpose:
score = 100
name = "Alex"
is_playing = True

Common 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 = 3

Hungarian 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 boolean

Camel 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 = True

PascalCase (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 = 1

Answer:

  • 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).
Note for Good Variable Names
  • Make them descriptive but concise
  • Keep them easy to type and read
  • Use consistent style throughout your code
  • For special types:
    • Use is_ or has_ prefix for booleans
    • Use num_ or count_ for counting variables
  • Consider your audience:
    • Will others understand your variable names?
    • Will you understand them in a month?

Remember:

  • 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
  • Boolean: Used for storing True or False values
    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’s time or datetime library

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

Answer:

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 = "你好"           # Chinese

Input 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?

Remember:

  • 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: 20

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

  1. Run the code to get the timestamp value
  2. Calculate the number of seconds in a year:
    • Seconds in a year = 365.25 days × 24 hours × 60 minutes × 60 seconds = 31,557,600.
  3. Divide the timestamp by the number of seconds in a year:: timestamp / (365.25 * 24 * 60 * 60)

Remember:

  • 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 time module
  • 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 = True

Comparison 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
Be aware of both = 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 if name is “Admin” and assigns the result (True or False) to is_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           # True

Using 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        # False
Common Mistakes to Avoid
  • true and false are not valid (must be capitalised)
  • Using = instead of == for comparison
  • Comparing different data types

Remember:

  • Boolean values are either True or False
  • Comparisons produce boolean results
  • and, or, not combine boolean values
  • Spelling matters: True and False (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:

Common Mistake: Division always gives a float

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:

Important Notes
  • 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 decimal module
Common mistake
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.4 Comments and Code Maintenance

  • How to write effective comments
  • Code documentation (TBA)
  • Using stubs in development (TBA)
  • Maintaining code (TBA)

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:

#  This is a comment
player_name = "Alex"  #  This stores the player's name

Multi-line Comments

For longer explanations, use three quotes """ or ''':

"""
This is our first game
It has a player name and score
We will add more features later
"""
player_name = "Alex"
score = 50

Here’s the callout-note explaining the use of triple quotes for strings:

Did you know?

Triple quotes """ or ''' are not just for comments—they can also be used to create multi-line strings!

For example:

game_description = """
This is our first game.
It has a player name and score.
We will add more features later.
"""
print(game_description)

This is especially useful for storing multi-line text directly in your program.

Three Principles of Good Comments

  1. Relevant - Comments should help understand the code
#  BAD: This line uses a variable
score = 50

#  GOOD: Starting score for new players
score = 50
  1. Non-trivial - Don’t state the obvious
#  BAD: Add one to score
score = score + 1

#  GOOD: Increase score for defeating enemy
score = score + 1
Note: Using += for Incrementing

In Python, the expression score = score + 1 can be simplified using the shorthand operator +=. This makes your code more concise and easier to read, i.e. score += 1

  1. Consistent - Use similar style throughout your code
#  INCONSISTENT:
score = 100  #    initial score (extra spaces after #)
lives = 3  ##  number of lives (extra #)
points = 0    #  Bonus point (extra spaces before #)

#  CONSISTENT:
score = 100  #  Initial score
lives = 3  #  Number of lives
points = 0  #  Bonus points

Examples of Good Comments

#  Calculate final score with bonus multiplier
final_score = score * 2

#  Check if player has enough points for extra life
#  Needs 1000 points per extra life
if score >= 1000:
    lives = lives + 1

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:

# TODO: Implement player login functionality
def player_login():
    pass

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:

# This calculates the area of a rectangle
area = width * height

Ask yourself:

  • Is the comment helpful? (Relevant)
  • Does it explain something non-obvious? (Non-trivial)
  • Does it match the style of other comments? (Consistent)

Would you keep, revise, or remove this comment? Why?

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:

  1. 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.
  2. 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?
  3. Arithmetic Operations:
    • Find two different arithmetic operations in the code
    • What does the scaling_factor calculation do?
  4. Comments:
    • Why is the first comment useful?
    • If you think it’s not useful, how would you rewrite it to make it more meaningful?
  5. 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?

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

Here’s a brief explanation of those two Python features:

  1. "✓" 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 ✗
  2. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.

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:

  1. What were the most useful improvements suggested by the AI?
  2. How did the AI help you better understand coding practices and standards?
  3. How can you apply these improvements to your future projects?
  4. What challenges did you face while working with the AI, and how did you address them?
Tips for Working with AI
  • 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.