Python Programming: Advanced (Leaving Cert Computer Science): Revision Notes
Python Programming: Advanced
Nested Conditionals
Nested conditionals involve placing one conditional statement inside another. This is useful when you need to check multiple conditions in a hierarchical way — where the second check only makes sense once the first has been decided.
For example, an e-commerce platform wants to determine the discount to offer different customers based on age and membership:
- If the person is under 18, or 65 and over, they get a "Senior / Child Discount."
- If the person is 18 or over but under 65:
- If they are a member, they get a "Member Discount."
- If they are not a member, they get "No Discount."
age = 45
is_member = True
if age < 18 or age >= 65:
discount = "Senior / Child Discount"
else:
if is_member:
discount = "Member Discount"
else:
discount = "No Discount"
print("Discount: " + discount)
The outer condition decides which group the customer falls into; the inner condition only runs for the 18–64 group, deciding between member and non-member. This is the essence of nesting: the inner decision depends on the outer one already being true.
Nested Loops
Nested loops involve placing one loop inside another. For each single pass of the outer loop, the inner loop runs all the way through.
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
for item1 in list1:
for item2 in list2:
print(f"({item1}, {item2})")
"""
(a, 1)
(a, 2)
(a, 3)
(b, 1)
(b, 2)
(b, 3)
(c, 1)
(c, 2)
(c, 3)
"""
- The outer loop (for item1 in list1) iterates over each element in list1.
- The inner loop (for item2 in list2) iterates over every element in list2 for each value of item1.
- Each pair (item1, item2) is printed.
The f before the string (f"({item1}, {item2})") marks an f-string, or formatted string. Any variable placed inside curly braces {} is replaced by its value. This is often cleaner than joining strings with the + operator.
Functions
Functions are a fundamental part of Python programming. They let you encapsulate code into reusable blocks, making your code more modular, readable, and easier to maintain.
We have been using functions this entire time, such as print and range. Now we will write our own. The basic syntax of a function is:
def function_name(parameters):
# Function body
# Code to execute
return result # Optional
A function is defined with the def keyword. The values it receives are called parameters, and the return statement sends a value back to whoever called the function. Let's write a function that takes in a number and returns the square of that number.
def square(x):
return x * x
print(square(5)) # Output: 25
print(square(3)) # Output: 9
print(square(2)) # Output: 4
The return statement is different from print. print displays a value on the screen, whereas return hands a value back to the code that called the function, so it can be stored or reused. A function without a return statement returns None by default.
Recursion
Recursion is a programming technique where a function calls itself in order to solve smaller instances of the same problem.
Recursion is often used for problems that can be broken down into smaller, repetitive sub-problems. It is a powerful tool, but it must be used with care to avoid infinite recursion and stack overflow errors.
A recursive function typically has two main components:
- Base case : the condition under which the function stops calling itself, preventing infinite recursion.
- Recursive case : the part where the function calls itself with a smaller or simpler input.
Every recursive function must have a base case. Without one, the function would call itself forever, and Python would eventually stop it with a stack overflow error (in Python, a RecursionError). The base case is what allows the chain of calls to end and start returning values.
For example, in mathematics the factorial of a non-negative integer is the product of all positive integers less than or equal to . For instance, . Let's look at the factorial of 5 more closely.
We can see how recursion breaks the factorial down into smaller factorials:
- is broken down into
- is broken down into , and so on.
- Eventually we reach the base case.
def factorial(n):
# Base case: if n is 0, return 1
if n == 0:
return 1
else:
# Recursive case: return n * factorial(n - 1)
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Here is a visual representation of the recursive calls for factorial(4):
factorial(4)
-> 4 * factorial(3)
-> 3 * factorial(2)
-> 2 * factorial(1)
-> 1 * factorial(0)
-> 1
Notice the two directions of a recursive call. On the way down, each call spawns a smaller call until the base case is reached. On the way back up, each call returns its result to the one above, multiplying as it goes: factorial(0) returns 1, then factorial(1) returns 1, factorial(2) returns 2, factorial(3) returns 6, and factorial(4) returns 24.
Remember!
- Nested conditionals place one if inside another; the inner decision only applies once the outer condition is met.
- Nested loops place one loop inside another — the inner loop runs fully for each single pass of the outer loop.
- Functions (defined with def) package reusable code; they take parameters and can return a value. return hands a value back, unlike print which just displays it.
- Recursion is a function calling itself on a smaller input. Every recursive function needs a base case (to stop) and a recursive case (to reduce the problem).
- Without a base case, recursion runs forever and causes a stack overflow (RecursionError in Python).
- f-strings (f"...{var}...") insert variable values directly into a string.