How to call a function in Python
1. What is a Function?
A function is a block of reusable code designed to perform a specific task.
- Inputs: Called arguments or parameters.
- Logic: The body of the function where operations are performed.
- Output: The output given by the function.
Example:
def greet(name):
return f"Hello, {name}!"
Here:
greetis the function name.nameis the parameter.- The function processes the input and returns a greeting.
2. Defining a Function
Functions are declared by using the keyword def followed by:
- The function name.
- Parentheses
( )containing parameters (optional). - A colon
:indicating the beginning of the function’s body. - A block of indented code as the body.
Example:
def say_hello(): # No parameters
print("Hello, World!") # Function body
3. Calling a Function
Functions are invoked using their name followed by parentheses. If they need arguments, pass them inside the parentheses.
Example:
say_hello() # Calls the function
Output:
Hello, World!
4. Function Arguments
a. No Arguments
Functions without arguments perform tasks without needing external input.
Example:
def welcome_message():
print("Welcome to Python programming!")
welcome_message()
Output:
Welcome to Python programming!
b. Positional Arguments
Arguments are passed in the same order as the function parameters.
Example:
def subtract(a, b):
return a - b
result = subtract(10, 5)
print(result)
Output:
5
c. Keyword Arguments
Arguments are assigned explicitly by name, making the order irrelevant.
Example:
def subtract(a, b):
return a - b
result = subtract(b=5, a=10) # Keyword arguments
print(result)
Output:
5
d. Default Arguments
Default arguments are used if no value is provided.
Example:
def greet(name, message="Welcome!"):
return f"{message}, {name}"
print(greet("Alice")) # Uses default message
print(greet("Bob", "Good Morning")) # Overrides default
Output:
Welcome!, Alice
Good Morning, Bob
e. Variable-Length Arguments
*args: Accepts multiple positional arguments as a tuple.
Example:
def add_all(*args):
return sum(args)
print(add_all(1, 2, 3, 4)) # Adds all arguments
Output:
10
2. **kwargs: Accepts multiple keyword arguments as a dictionary.
Example:
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="New York")
Output:
name: Alice
age: 25
city: New York
5. Return Values
Functions can return a value using the return statement. If no return is specified, the function returns None.
Example 1: Returning a Value
def multiply(a, b):
return a * b
result = multiply(3, 4)
print(result)
Output:
12
Example 2: Returning None
def do_nothing():
pass
print(do_nothing())
Output:
None
6. Common Errors
a. Missing Parentheses
Calling a function without parentheses treats it as an object instead of executing it.
Example:
def greet():
return "Hello!"
print(greet) # Function object, not executed
print(greet()) # Executes and returns "Hello!"
Output:
<function greet at 0x...>
Hello!
b. Incorrect Number of Arguments
If a function is called with fewer or more arguments than required, Python raises an error.
Example:
def divide(a, b):
return a / b
# print(divide(5)) # Missing one argument
Error Output:
TypeError: divide() missing 1 required positional argument: 'b'
c. Invalid Argument Types
Passing incompatible arguments can cause errors.
Example:
def multiply(a, b):
return a * b
# print(multiply(5, "hello")) # Invalid operation
Error Output:
TypeError: can't multiply sequence by non-int of type 'str'
7. Practical Examples
a. Calculator
def calculator(a, b, operation):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b
else:
return "Invalid operation"
print(calculator(10, 5, "add")) # Output: 15
print(calculator(10, 5, "divide")) # Output: 2.0
Output:
15
2.0
b. Temperature Conversion
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
print(celsius_to_fahrenheit(0)) # Freezing point
print(celsius_to_fahrenheit(100)) # Boiling point
Output:
32.0
212.0
8. Scope and Nested Functions
Scope: Variables inside a function are local to that function.
Example:
def my_function():
x = 10 # Local variable
print(x)
# print(x) # Error: x is not defined outside the function
Output:
10
Summary Table of Key Concepts
| Concept | Description | Example (Output) |
|---|---|---|
| Function Definition | Define reusable code with def. | def greet(name): return "Hi!" |
| Calling Functions | Use function_name() to execute a function. | greet("Alice") → Hi! |
| Positional Arguments | Pass arguments in order. | add(5, 3) → 8 |
| Keyword Arguments | Explicitly assign arguments by name. | subtract(a=10, b=5) → 5 |
| Default Arguments | Provide default values for parameters. | greet("Bob") → Welcome, Bob! |
| Variable-Length Arguments | Use *args and **kwargs for flexible arguments. | add_all(1,2,3) → 6 |
| Return Values | Use return to send back results. | multiply(2, 3) → 6 |
| Errors | Handle missing arguments and type issues. | TypeError |