Calling functions ¶
After you define a function, you can use (or "call") it by writing its name followed by parentheses. If the function needs inputs, you provide them inside the parentheses.
In [ ]:
Copied!
# Defining the functions
def say_hello():
print("Hello!")
def greet(name):
print(f"Hello, {name}!")
# Calling the functions
say_hello() # Prints: Hello!
greet("Alice") # Prints: Hello, Alice!
# Defining the functions
def say_hello():
print("Hello!")
def greet(name):
print(f"Hello, {name}!")
# Calling the functions
say_hello() # Prints: Hello!
greet("Alice") # Prints: Hello, Alice!
Working with Return Values ¶
When a function returns a value, you can:
- Store it in a variable
- Use it directly in calculations
- Pass it to other functions
In [9]:
Copied!
def double(number):
return number * 2
# Store the result
result = double(5)
# Use in calculation
total = double(3) + double(4)
# Pass to another function
print(double(6))
def double(number):
return number * 2
# Store the result
result = double(5)
# Use in calculation
total = double(3) + double(4)
# Pass to another function
print(double(6))
12
Providing Arguments ¶
When calling a function, you need to provide the right number of arguments (inputs):
def calculate_area(length, width):
return length * width
# ✅ Correct: Two arguments for two parameters
area = calculate_area(5, 3) # area = 15
# ❌ Wrong: Too few arguments
area = calculate_area(5) # Error!
# ❌ Wrong: Too many arguments
area = calculate_area(5, 3, 2) # Error!
Using Variables as Arguments ¶
You can pass variables as arguments:
room_length = 10
room_width = 8
area = calculate_area(room_length, room_width) # area = 80
Function Calls Inside Other Calls ¶
Functions can be nested:
def add_one(x):
return x + 1
def multiply_by_two(x):
return x * 2
# Nested function calls are evaluated from inside out
result = multiply_by_two(add_one(5)) # First 5+1=6, then 6*2=12