Lesson 7 - Function

Functions in Python

A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you can put it inside a function and call it whenever needed.

def say_hello():
  print("Hello!")

# Call (use) the function
say_hello()
❓Why use functions?
  • They make code organized and readable.
  • You can reuse the same code multiple times.
  • They allow you to break problems into smaller parts.
Functions with parameters
def greet(name):
  print("Hello,", name, "!")

greet("Alice")
greet("Bob")

You can give a function inputs (called parameters) to make it more flexible

Functions that return values
def add(a, b):
  return a + b

result = add(5, 3)
print("Result:", result)

Functions can also return results using the return keyword

📋 Key Points
  • Use def to define a function.
  • Use parentheses () to call a function.
  • Functions can take parameters (inputs).
  • Functions can return a value.

Say Hello

def say_hello():
  print("Hello, everyone!")

say_hello()

💡 Try changing the message inside print().

Say Your Name

def greet(name):
  print("Hello, " + name)

greet("Anna")

💡 Try greeting yourself by changing the name.

Add Two Numbers

def add_numbers(a, b):
  return a + b

print(add_numbers(2, 3))

💡 Try adding bigger numbers.

Double a Number

def double(x):
  return x * 2

print(double(6))

💡 Try doubling your age!

Make a Sentence

def make_sentence(name, food):
  return name + " likes " + food

print(make_sentence("Sam", "pizza"))

💡 Try your own name and favorite food.

Find the Bigger Number

def bigger(a, b):
  if a > b:
    return a
  else:
    return b

print(bigger(8, 3))

💡 Try two different numbers.

Repeat a Word

def repeat_word(word, times):
  return word * times

print(repeat_word("Hi ", 3))

💡 Try repeating your name 5 times.

Multiply Three Numbers

def multiply(a, b, c):
  return a * b * c

print(multiply(2, 3, 4))

💡 Try three different numbers.

Check Even or Odd

def check_number(n):
  if n % 2 == 0:
    print("Even")
  else:
    print("Odd")

check_number(7)

💡 Try with your favorite number.

Make a Birthday Song

def birthday_song(name):
  print("Happy Birthday to you!")
  print("Happy Birthday dear " + name)

birthday_song("Liam")

💡 Try singing the song for your friend!