How to Pass Arguments to Function in Python: Simple Guide
In Python, you pass arguments to a function by placing values inside parentheses after the function name, like
function_name(argument1, argument2). These values are received by the function's parameters, which act like placeholders for the input data.Syntax
To pass arguments to a function, write the function name followed by parentheses containing the arguments separated by commas. Inside the function, parameters receive these values.
- function_name: The name of the function you want to call.
- argument1, argument2, ...: The values you pass to the function.
- parameters: Variables in the function definition that hold the passed arguments.
python
def greet(name): print(f"Hello, {name}!") greet("Alice")
Output
Hello, Alice!
Example
This example shows how to define a function with parameters and call it by passing arguments. The function prints a greeting message using the passed name.
python
def greet(name): print(f"Hello, {name}!") greet("Bob") greet("Eve")
Output
Hello, Bob!
Hello, Eve!
Common Pitfalls
Common mistakes include:
- Not passing the correct number of arguments (too few or too many).
- Mixing up the order of arguments when the function expects positional arguments.
- Forgetting to include parentheses when calling the function.
Always check the function definition to know how many and what kind of arguments it expects.
python
def add(a, b): return a + b # Wrong: missing one argument # result = add(5) # This will cause an error # Correct: result = add(5, 3) print(result)
Output
8
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Positional Arguments | Arguments passed in order matching parameters | def f(x, y): ...; f(1, 2) |
| Keyword Arguments | Arguments passed by name, order doesn't matter | def f(x, y): ...; f(y=2, x=1) |
| Default Arguments | Parameters with default values if no argument passed | def f(x=0): ...; f() |
| Variable-length Arguments | Functions accepting any number of arguments | def f(*args): ...; f(1,2,3) |
Key Takeaways
Pass arguments inside parentheses when calling a function to provide input values.
Function parameters receive the passed arguments and act as placeholders inside the function.
Match the number and order of arguments to the function's parameters to avoid errors.
Use keyword arguments to pass values by name and improve clarity.
Default and variable-length arguments offer flexibility in function calls.