Calling Functions by Name
๐ท๏ธ Functions / Defining and Calling Functions
๐ฑ Context Introduction
When you write Python code, you often create reusable blocks of logic called functions. But once a function is defined, how do you actually use it? You call it by its name. Calling a function by name is the most fundamental way to execute the code inside it. Think of it like giving a command: you say the function's name, and Python runs the instructions you stored inside it.
โ๏ธ What Does "Calling a Function by Name" Mean?
- A function is defined with the def keyword followed by a name, parentheses, and a colon.
- To run that function, you simply write its name followed by parentheses.
- This action is called a function call or invocation.
- When Python sees the function name with parentheses, it jumps to the function definition, executes the code inside, and then returns to where it was called.
๐ ๏ธ Basic Syntax for Calling a Function
- Write the function name exactly as it was defined (case-sensitive).
- Add a pair of parentheses right after the name.
- If the function expects inputs (arguments), place them inside the parentheses.
- End the line without a colon (that is only for the definition).
Example: - Define a function: def greet(): - Call it: greet()
๐ Simple Example: Defining and Calling
Here is a step-by-step breakdown:
- Step 1: Define a function named say_hello that prints a message.
- def say_hello():
- Inside the function: print("Hello, welcome to Python!")
- Step 2: Call the function by its name.
- say_hello()
- Expected output: Hello, welcome to Python!
๐ต๏ธ What Happens When You Call a Function?
- Python looks up the function name in memory.
- It finds the block of code associated with that name.
- It executes every line inside the function body, from top to bottom.
- After the last line, Python returns control to the line right after the function call.
๐ Calling a Function Multiple Times
- You can call the same function as many times as you need.
- Each call runs the entire function body again.
- This avoids repeating the same code over and over.
Example: - def show_status(): - print("System is running") - show_status() - show_status() - show_status() - Expected output: System is running (printed three times)
๐ Calling Functions with Arguments
- Many functions need information to work with. This information is passed inside the parentheses.
- The values you pass are called arguments.
- The function definition must have matching parameters to receive them.
Example: - Define: def welcome_user(username): - print(f"Welcome, {username}!") - Call: welcome_user("Alice") - Expected output: Welcome, Alice!
๐งฉ Calling Functions That Return Values
- Some functions send back a result using the return statement.
- When you call such a function, you can store the returned value in a variable.
- The function name with parentheses acts like a placeholder for the returned value.
Example: - Define: def add_ten(number): - return number + 10 - Call and store: result = add_ten(5) - Print the result: print(result) - Expected output: 15
โ ๏ธ Common Mistakes When Calling Functions
- Forgetting parentheses: Writing greet instead of greet() does not call the function. It just references the function object.
- Misspelling the name: Python is case-sensitive. Greet() is different from greet().
- Passing wrong number of arguments: If a function expects two arguments, passing one or three will cause an error.
- Calling before defining: You must define a function before you call it, unless the call is inside another function that is called later.
๐ Comparison: Defining vs. Calling a Function
| Aspect | Defining a Function | Calling a Function |
|---|---|---|
| Keyword used | def | None (just the name) |
| Syntax | def function_name(): | function_name() |
| When it runs | Only when called | Immediately when executed |
| Purpose | Create the reusable code | Execute the reusable code |
| Indentation | Body is indented | No indentation needed |
| Colon | Required after the parentheses | Not used |
๐งช Practical Example: A Simple Workflow
Imagine you are checking system health:
- Define a function: def check_disk():
- print("Checking disk space...")
- print("Disk space is sufficient.")
- Define another function: def check_memory():
- print("Checking memory usage...")
- print("Memory usage is normal.")
- Call both functions in order:
- check_disk()
- check_memory()
- Expected output:
- Checking disk space...
- Disk space is sufficient.
- Checking memory usage...
- Memory usage is normal.
โ Key Takeaways
- Calling a function by name is how you execute the code you have defined.
- Always include parentheses after the function name.
- Pass arguments inside the parentheses if the function expects them.
- You can call a function as many times as you like from anywhere in your code.
- A function must be defined before it is called (with some exceptions for functions defined inside other functions).
๐ Quick Reference
- Call a function with no arguments: function_name()
- Call a function with one argument: function_name(value)
- Call a function with multiple arguments: function_name(value1, value2)
- Store the return value: variable = function_name()
- Call a function inside another function: def outer(): inner()
Calling a function by name means executing the code inside a function by writing its name followed by parentheses.
๐ข Example 1: Calling a simple function with no arguments
This example shows how to define and call a function that prints a fixed message.
def greet():
print("Hello, engineer!")
greet()
๐ค Output: Hello, engineer!
๐ข Example 2: Calling a function with one argument
This example passes a single value into a function and uses it inside.
def show_number(num):
print("The number is:", num)
show_number(42)
๐ค Output: The number is: 42
๐ข Example 3: Calling a function that returns a value
This example shows a function that calculates a result and sends it back to the caller.
def double(value):
result = value * 2
return result
output = double(5)
print(output)
๐ค Output: 10
๐ข Example 4: Calling a function multiple times with different arguments
This example demonstrates reusing the same function with different inputs each time.
def add(a, b):
total = a + b
return total
sum1 = add(3, 4)
sum2 = add(10, 20)
sum3 = add(-5, 8)
print(sum1)
print(sum2)
print(sum3)
๐ค Output: 7
๐ค Output: 30
๐ค Output: 3
๐ข Example 5: Calling a function that uses another function
This example shows how one function can call another function by name.
def square(x):
return x * x
def print_square(n):
result = square(n)
print("Square of", n, "is", result)
print_square(4)
print_square(7)
๐ค Output: Square of 4 is 16
๐ค Output: Square of 7 is 49
๐ Quick Reference: Calling Functions by Name
| Concept | What It Does | Example |
|---|---|---|
| Call with no arguments | Runs function without input | greet() |
| Call with arguments | Passes data into function | show_number(42) |
| Call and capture return | Stores result from function | output = double(5) |
| Call multiple times | Reuses same function with different values | add(3,4) then add(10,20) |
| Call inside another function | One function triggers another | square(n) inside print_square() |
๐ฑ Context Introduction
When you write Python code, you often create reusable blocks of logic called functions. But once a function is defined, how do you actually use it? You call it by its name. Calling a function by name is the most fundamental way to execute the code inside it. Think of it like giving a command: you say the function's name, and Python runs the instructions you stored inside it.
โ๏ธ What Does "Calling a Function by Name" Mean?
- A function is defined with the def keyword followed by a name, parentheses, and a colon.
- To run that function, you simply write its name followed by parentheses.
- This action is called a function call or invocation.
- When Python sees the function name with parentheses, it jumps to the function definition, executes the code inside, and then returns to where it was called.
๐ ๏ธ Basic Syntax for Calling a Function
- Write the function name exactly as it was defined (case-sensitive).
- Add a pair of parentheses right after the name.
- If the function expects inputs (arguments), place them inside the parentheses.
- End the line without a colon (that is only for the definition).
Example: - Define a function: def greet(): - Call it: greet()
๐ Simple Example: Defining and Calling
Here is a step-by-step breakdown:
- Step 1: Define a function named say_hello that prints a message.
- def say_hello():
- Inside the function: print("Hello, welcome to Python!")
- Step 2: Call the function by its name.
- say_hello()
- Expected output: Hello, welcome to Python!
๐ต๏ธ What Happens When You Call a Function?
- Python looks up the function name in memory.
- It finds the block of code associated with that name.
- It executes every line inside the function body, from top to bottom.
- After the last line, Python returns control to the line right after the function call.
๐ Calling a Function Multiple Times
- You can call the same function as many times as you need.
- Each call runs the entire function body again.
- This avoids repeating the same code over and over.
Example: - def show_status(): - print("System is running") - show_status() - show_status() - show_status() - Expected output: System is running (printed three times)
๐ Calling Functions with Arguments
- Many functions need information to work with. This information is passed inside the parentheses.
- The values you pass are called arguments.
- The function definition must have matching parameters to receive them.
Example: - Define: def welcome_user(username): - print(f"Welcome, {username}!") - Call: welcome_user("Alice") - Expected output: Welcome, Alice!
๐งฉ Calling Functions That Return Values
- Some functions send back a result using the return statement.
- When you call such a function, you can store the returned value in a variable.
- The function name with parentheses acts like a placeholder for the returned value.
Example: - Define: def add_ten(number): - return number + 10 - Call and store: result = add_ten(5) - Print the result: print(result) - Expected output: 15
โ ๏ธ Common Mistakes When Calling Functions
- Forgetting parentheses: Writing greet instead of greet() does not call the function. It just references the function object.
- Misspelling the name: Python is case-sensitive. Greet() is different from greet().
- Passing wrong number of arguments: If a function expects two arguments, passing one or three will cause an error.
- Calling before defining: You must define a function before you call it, unless the call is inside another function that is called later.
๐ Comparison: Defining vs. Calling a Function
| Aspect | Defining a Function | Calling a Function |
|---|---|---|
| Keyword used | def | None (just the name) |
| Syntax | def function_name(): | function_name() |
| When it runs | Only when called | Immediately when executed |
| Purpose | Create the reusable code | Execute the reusable code |
| Indentation | Body is indented | No indentation needed |
| Colon | Required after the parentheses | Not used |
๐งช Practical Example: A Simple Workflow
Imagine you are checking system health:
- Define a function: def check_disk():
- print("Checking disk space...")
- print("Disk space is sufficient.")
- Define another function: def check_memory():
- print("Checking memory usage...")
- print("Memory usage is normal.")
- Call both functions in order:
- check_disk()
- check_memory()
- Expected output:
- Checking disk space...
- Disk space is sufficient.
- Checking memory usage...
- Memory usage is normal.
โ Key Takeaways
- Calling a function by name is how you execute the code you have defined.
- Always include parentheses after the function name.
- Pass arguments inside the parentheses if the function expects them.
- You can call a function as many times as you like from anywhere in your code.
- A function must be defined before it is called (with some exceptions for functions defined inside other functions).
๐ Quick Reference
- Call a function with no arguments: function_name()
- Call a function with one argument: function_name(value)
- Call a function with multiple arguments: function_name(value1, value2)
- Store the return value: variable = function_name()
- Call a function inside another function: def outer(): inner()
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
Calling a function by name means executing the code inside a function by writing its name followed by parentheses.
๐ข Example 1: Calling a simple function with no arguments
This example shows how to define and call a function that prints a fixed message.
def greet():
print("Hello, engineer!")
greet()
๐ค Output: Hello, engineer!
๐ข Example 2: Calling a function with one argument
This example passes a single value into a function and uses it inside.
def show_number(num):
print("The number is:", num)
show_number(42)
๐ค Output: The number is: 42
๐ข Example 3: Calling a function that returns a value
This example shows a function that calculates a result and sends it back to the caller.
def double(value):
result = value * 2
return result
output = double(5)
print(output)
๐ค Output: 10
๐ข Example 4: Calling a function multiple times with different arguments
This example demonstrates reusing the same function with different inputs each time.
def add(a, b):
total = a + b
return total
sum1 = add(3, 4)
sum2 = add(10, 20)
sum3 = add(-5, 8)
print(sum1)
print(sum2)
print(sum3)
๐ค Output: 7
๐ค Output: 30
๐ค Output: 3
๐ข Example 5: Calling a function that uses another function
This example shows how one function can call another function by name.
def square(x):
return x * x
def print_square(n):
result = square(n)
print("Square of", n, "is", result)
print_square(4)
print_square(7)
๐ค Output: Square of 4 is 16
๐ค Output: Square of 7 is 49
๐ Quick Reference: Calling Functions by Name
| Concept | What It Does | Example |
|---|---|---|
| Call with no arguments | Runs function without input | greet() |
| Call with arguments | Passes data into function | show_number(42) |
| Call and capture return | Stores result from function | output = double(5) |
| Call multiple times | Reuses same function with different values | add(3,4) then add(10,20) |
| Call inside another function | One function triggers another | square(n) inside print_square() |