🔍 Quick Lesson
Once you've defined a function in Python, you need to call it in order for it to run. Calling a function executes the code inside it. It's like summoning a spell from your spellbook!
1. Calling a Simple Function
def say_hello():
print("Hello, wizard!")
say_hello()
The function say_hello()
is called at the bottom, which prints the greeting.
2. Calling Functions with Arguments
If your function requires inputs (parameters), provide them inside the parentheses when you call it:
def greet(name):
print(f"Hello, {name}!")
greet("Merlin")
This will output: Hello, Merlin!
3. Using Return Values
You can call a function and capture its return value in a variable:
def add(a, b):
return a + b
result = add(5, 7)
print(result) # Outputs 12
4. Calling Functions in Other Functions
Functions can be called inside other functions:
def add(a, b):
return a + b
def multiply_and_add(x, y, z):
return x * add(y, z)
print(multiply_and_add(2, 3, 4)) # Outputs 14
This calls add(3, 4)
first (which returns 7), and then multiplies it by 2.
5. Calling Built-in Functions
Python provides many built-in functions you can call without defining them:
print("Hello")
– displays outputlen("magic")
– returns the length of a stringtype(10)
– returns the data type
6. Function Call Order
You must define a function before you call it. Otherwise, Python will raise an error:
say_hello() # ❌ NameError: name 'say_hello' is not defined
def say_hello():
print("Hello")
Fix this by defining the function before calling it.