Lesson 10: Functions
Topics Covered:
- What is a function?
- Defining and calling functions
- Function parameters (arguments)
- Return values from functions
What is a Function?
A function is a reusable block of code that performs a specific task.
Defining a Function
def greet():
print("Hello, friend!")
Calling a Function
greet() # Output: Hello, friend!
Functions with Parameters
Functions can take inputs called parameters:
def greet(name):
print("Hello,", name)
greet("Alice") # Output: Hello, Alice
Functions with Return Values
Functions can send back a result using return
:
def add(a, b):
return a + b
result = add(3, 4)
print("Sum is", result) # Output: Sum is 7
Activity: Write a Function
- Create a function
square
that takes a number and returns its square. - Call the function with different numbers and print the results.
def square(x):
return x * x
print(square(5)) # 25
print(square(10)) # 100
Challenge
- Write a function
is_even
that returnsTrue
if a number is even,False
otherwise. - Test it with several numbers.
def is_even(num):
return num % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False