Have you noticed yourself writing the same code over and over? Functions let you package code into reusable blocks. Once defined, you can use them anywhere!
Syntax:
def function_name():
# code to run
# when the function is called
Example:
def greet():
print("Hello! Welcome to Python π")
# Call the function
greet() # Hello! Welcome to Python π
greet() # Hello! Welcome to Python π
π def keyword β function name β parentheses () β colon : β indented body.
say_hello that prints "Hi there!" three times.show_menu that prints a menu with 3 options.Syntax:
def function_name(parameter1, parameter2):
# use parameter1 and parameter2
Example:
def greet_person(name):
print(f"Hello, {name}! π")
greet_person("Alice") # Hello, Alice! π
greet_person("Bob") # Hello, Bob! π
double(n) that prints twice the number passed to it.welcome(name, subject) that prints "Welcome, [name]! Let's learn [subject]."Syntax:
def function_name():
return value
Examples:
def square(x):
return x * x
result = square(5)
print(result) # 25
def is_even(n):
return n % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # False
return vs print: return sends a value back to the caller. print displays something on screen. A function without return returns None.
add(a, b) that returns the sum of two numbers.is_positive(n) that returns True if n is greater than 0.rectangle_area(length, width) that returns the area.def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (5Β²)
print(power(2, 10)) # 1024 (2ΒΉβ°)
multiply(a, b=1) that returns a Γ b. If b is not given, return a.In IGCSE, a procedure does something but doesn't return a value. A function returns a value.
# PROCEDURE β no return
def display_menu():
print("1. Add student")
print("2. View scores")
print("3. Quit")
# FUNCTION β has return
def get_average(scores):
total = 0
for s in scores:
total += s
return total / len(scores)
# Calling them
display_menu()
avg = get_average([70, 80, 90])
print(f"Average: {avg}")
print_separator() that prints "---".celsius_to_fahrenheit(c) that returns the converted temperature.score = 10 # GLOBAL
def update_score():
score = 5 # LOCAL β different variable!
print(f"Inside: {score}") # 5
update_score()
print(f"Outside: {score}") # 10 (unchanged!)
x = 10; def change(): x = 20; change(); print(x)# MOD (%) β remainder
print(17 % 5) # 2
# DIV (//) β integer division
print(17 // 5) # 3
# ROUND
print(round(3.7)) # 4
print(round(3.14159, 2)) # 3.14
# RANDOM
import random
print(random.randint(1, 10)) # random 1-10
print(random.random()) # random 0.0-1.0
# β BAD β what does this do?
def f(a, b):
c = a
for d in range(b - 1):
c = c * a
return c
# β
GOOD β meaningful names + docstring!
def calculate_power(base, exponent):
"""Return base raised to the power of exponent."""
result = base
for i in range(exponent - 1):
result = result * base
return result
def x(a,b): return a*b/2rectangle_area function.In IGCSE Computer Science, you need to know four key string operations: length, substring, upper case, and lower case. Let's master them in Python!
len()Syntax:
len(string)
Example:
word = "Hello"
print(len(word)) # 5
sentence = "Hello World"
print(len(sentence)) # 11 (spaces count!)
Syntax β slicing:
string[start:end] # from start to end-1
string[start:] # from start to end
string[:end] # from beginning to end-1
Examples:
text = "Python Programming"
print(text[0:6]) # Python (chars 0 to 5)
print(text[7:]) # Programming (from char 7)
print(text[-3:]) # ing (last 3 chars)
print(text[:6]) # Python (first 6 chars)
MID(str, start, length) is used. Know both!
Syntax:
string.upper() # convert to uppercase
string.lower() # convert to lowercase
Examples:
msg = "Hello World"
print(msg.upper()) # HELLO WORLD
print(msg.lower()) # hello world
# Case-insensitive comparison
answer = input("Continue? (yes/no): ")
if answer.lower() == "yes":
print("Let's go! π")
# 1. Count vowels
word = "education"
vowels = 0
for ch in word:
if ch.lower() in "aeiou":
vowels += 1
print(f"Vowels: {vowels}") # 5
# 2. Check file extension
filename = "report.pdf"
if filename[-4:] == ".pdf":
print("It's a PDF!")
# 3. Extract first name
full_name = "Alice Smith"
space_pos = full_name.find(" ")
first_name = full_name[:space_pos]
print(f"First name: {first_name}") # Alice
# 4. Reverse a string
word = "Python"
reversed_word = word[::-1]
print(reversed_word) # nohtyP