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.
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
print("Hello,", name, "!")
greet("Alice")
greet("Bob")
You can give a function inputs (called parameters) to make it more flexible
Functions that return values
return a + b
result = add(5, 3)
print("Result:", result)
Functions can also return results using the return keyword
📋 Key Points
- Use
defto define a function. - Use parentheses
()to call a function. - Functions can take parameters (inputs).
- Functions can return a value.
Say Hello
print("Hello, everyone!")
say_hello()
💡 Try changing the message inside print().
Say Your Name
print("Hello, " + name)
greet("Anna")
💡 Try greeting yourself by changing the name.
Add Two Numbers
return a + b
print(add_numbers(2, 3))
💡 Try adding bigger numbers.
Double a Number
return x * 2
print(double(6))
💡 Try doubling your age!
Make a Sentence
return name + " likes " + food
print(make_sentence("Sam", "pizza"))
💡 Try your own name and favorite food.
Find the Bigger Number
if a > b:
return a
else:
return b
print(bigger(8, 3))
💡 Try two different numbers.
Repeat a Word
return word * times
print(repeat_word("Hi ", 3))
💡 Try repeating your name 5 times.
Multiply Three Numbers
return a * b * c
print(multiply(2, 3, 4))
💡 Try three different numbers.
Check Even or Odd
if n % 2 == 0:
print("Even")
else:
print("Odd")
check_number(7)
💡 Try with your favorite number.
Make a Birthday Song
print("Happy Birthday to you!")
print("Happy Birthday dear " + name)
birthday_song("Liam")
💡 Try singing the song for your friend!