Year 9 Digital Technologies · Creating Digital Solutions · 18m read
Programming — Python Fundamentals
Ever wondered how Netflix recommends shows or how apps automate tasks? That's Python at work. In this topic, you'll learn to write and test your own Python programs using variables (containers for data), control structures (if-statements and loops), functions (reusable chunks of code), and lists (organised data collections). Mastering these fundamentals opens doors to data science, artificial intelligence, and real-world problem-solving—skills that employers actively seek.
Learning objective: Write and test Python programs using variables, control structures, functions and lists.
By the end of this lesson you can:
- I can write Python programs with variables, if/else and loops.
- I can create and call functions.
- I can work with lists and basic data structures.
Python is a polite, literal assistant. It does exactly what you say — line by line — so clear instructions get great results.
Python fundamentals
VARIABLES AND DATA TYPES:
name = "Alice" # string
age = 15 # integer
gpa = 3.8 # float
is_enrolled = True # boolean
INPUT / OUTPUT:
name = input("Enter your name: ")
print("Hello, " + name)
SELECTION (if/elif/else):
if score >= 90:
print("A")
elif score >= 75:
print("B")
else:
print("C or below")
LOOPS:
# For loop
for i in range(5):
print(i) # prints 0,1,2,3,4
# While loop
count = 0
while count < 3:
print(count)
count += 1
FUNCTIONS:
def greet(name):
return "Hello, " + name
print(greet("Alice")) # Hello, Alice
LISTS:
scores = [85, 72, 90, 61]
print(scores[0]) # 85
scores.append(78) # add to end
print(len(scores)) # 5
LIST METHODS: .append(), .remove(), .sort(), .reverse(), len()
DEBUGGING:
• SyntaxError: code doesn't follow Python rules.
• NameError: variable used before assignment.
• IndexError: list index out of range.
• Read the error message — it tells you where to look.
AARI TIP: Ask Aari to explain any Python error message you receive or help debug your code.
Python rules
- Indentation matters: Python uses indentation (4 spaces) to define blocks — no braces.
- Types matter: "5" + 5 causes a TypeError — can't add string + int.
- Functions return values: Use "return" to send a value back from a function.
Quick reference
| Concept | Python |
|---|---|
| Variable | age = 14 |
| Input | name = input("Name? ") |
| If | if age >= 13: |
| Loop | for i in range(5): |
| Function | def area(w, h): return w * h |
| List | items = [1, 2, 3] |
Worked example (Medium)
Write a Python function that takes a list of test scores and returns the average.
- Plan. Sum all scores, divide by the count.
- Code. def calculate_average(scores): total = 0 for score in scores: total += score average = total / len(scores) return average results = [72, 85, 61, 90, 78] print(calculate_average(results)) # 77.2
- Test. (72+85+61+90+78) = 386; 386/5 = 77.2 ✓
- Edge case. What if scores is empty? Division by zero! Add: if len(scores) == 0: return 0
Answer: A correct function iterates through the list, sums values, divides by count — and handles the empty list edge case.
Common mistakes
- Using = instead of == in comparisons = assigns a value; == tests equality. Writing "if score = 90:" is a syntax error in Python (unlike some other languages) Fix: Always use == for comparison: "if score == 90:" — remember: single = assigns, double == compares
- Off-by-one errors with range() range(5) generates 0,1,2,3,4 — NOT 1,2,3,4,5. range(1, 6) generates 1,2,3,4,5 Fix: Check: range(n) gives n values starting at 0; range(a, b) gives values from a up to but not including b
- Forgetting to convert input() to the right type input() always returns a string. "5" + 3 causes a TypeError — you must convert first Fix: Use int(input(...)) for integers, float(input(...)) for decimals
Worked example (Hard)
Write a Python program that reads a list of student names and scores from the user, then prints a sorted leaderboard and the class average.
- Plan. Collect name+score pairs, compute average, sort by score descending, print leaderboard.
- Data structure choice. Use a list of dictionaries: each student = {"name": "Alice", "score": 85}. This groups related data together cleanly.
- Code. students = [] n = int(input("How many students? ")) for i in range(n): name = input("Name: ") score = int(input("Score: ")) students.append({"name": name, "score": score}) # Calculate average total = 0 for s in students: total += s["score"] average = total / len(students) # Sort by score descending students.sort(key=lambda s: s["score"], reverse=True) # Print leaderboard print("\n--- LEADERBOARD ---") for rank, s in enumerate(students, 1): print(f"{rank}. {s['name']}: {s['score']}") print(f"\nClass average: {average:.1f}")
- Trace. Input: Alice 85, Bob 72, Carol 91, Dan 65. total = 85+72+91+65 = 313; average = 313/4 = 78.25 Sorted: Carol 91, Alice 85, Bob 72, Dan 65. Output: 1. Carol: 91, 2. Alice: 85, 3. Bob: 72, 4. Dan: 65, Average: 78.3
- Extension. Could add: highest/lowest, grade bands (A/B/C), export to a file. Each is a small decomposed sub-problem.
Answer: This program demonstrates variables, loops, lists, dictionaries, sorting with a lambda key, f-strings, and formatted output — core Python foundations.
Practice questions
In Python, what does len([1, 2, 3, 4]) return?
- 3
- 4
- 1
- [1,2,3,4]
(1 marks)
Write a Python program that reads 5 numbers from the user and prints how many are above 50.
(3 marks)
What error will this Python code produce?
score = input("Enter score: ")
if score > 50:
print("Pass")- SyntaxError
- TypeError
- NameError
- No error — it works correctly
(1 marks)
Write a Python function is_palindrome(word) that returns True if the word is a palindrome (reads the same forwards and backwards), False otherwise. Test with "racecar", "hello" and "level".
(4 marks)
Explain the difference between a function that prints a result and a function that returns a result. Why does it matter?
(2 marks)
Deeper Understanding: Python in the Real World
Python has become the dominant language in data science, AI, scientific computing and automation for good reasons: its readable syntax reduces cognitive load, its vast ecosystem of libraries (NumPy, pandas, scikit-learn, TensorFlow, Django, Flask) means you rarely start from scratch, and it has strong community support. In Australia, Python is used extensively at organisations like the CSIRO for scientific data analysis, at the Bureau of Meteorology for weather modelling, and at Atlassian and Canva (Australian tech companies) for backend services.
Under the hood, Python is an interpreted, dynamically-typed language. Variables don't need type declarations because Python determines types at runtime — convenient but also a source of runtime errors that statically typed languages (like Java, TypeScript) would catch at compile time. This is why professional Python code typically uses type hints and automated testing frameworks like pytest to catch errors early.
Python's memory management uses garbage collection — objects are automatically removed from memory when no longer referenced, saving developers from manual memory management (a common source of security vulnerabilities in C/C++). However, Python's Global Interpreter Lock (GIL) limits true parallelism in CPU-bound tasks — which is why data scientists often use NumPy (which runs C code internally) for heavy computation.
For Year 9 and beyond, developing "Pythonic" habits — list comprehensions, proper function decomposition, meaningful variable names, docstrings and unit tests — is more important than learning exotic language features. These habits will transfer to any language you learn later.
Summary
- Python: indentation defines blocks; input() returns strings; int() and float() convert types.
- Control structures: if/elif/else for selection; for/while for iteration.
- Functions defined with def, called by name, return values with return.
- Lists: ordered, mutable; methods include .append(), .sort(), .remove(); indexing starts at 0.
- Common errors: SyntaxError, TypeError, NameError, IndexError — read the error message.
- Always trace through code with test values before submitting; handle edge cases.