What are parameters and arguments in python functions?
We use parameters and arguments in functions to make our code reusable and flexible.
Parameter:
This is a variable that defines when we declare the function. It acts as a placeholder for the value that will be given when calling the function.
For Example:
def function_name(perameter1, perameter2):
#your code
Argument:
Arguments are the values that are passing when we call that function which hold parameters.
For Example:
function_name(first_values, second_value)
How to use parameters and arguments?
Example: Let's create a simple function that adds two numbers together.
def sum_these(perameter1, perameter2):
result = perameter1 + perameter2
print(result)
sum_these(100, 200)
sum_these(40, 30)
Output:
300
70
Explanation:
Types of Parameters and Arguments in Python Functions:
There are 4 types of parameters and arguments in python function:
- Positional Parameters:
- Keyword Parameters:
- Default Parameters
- Variable-length Parameters
- Arbitrary Positional Arguments (*args)
- Arbitrary Keyword Arguments (**kwargs)
1) Positional Parameters:
In positional parameters, the order or sequence is important. The order you define the parameters in the function must match the order in which you pass the arguments when calling the function.
Syntax:
def sum_these(perameter1, perameter2):
#your codee
sum_these(first_value, second_value)
Example:
def hey_buddy(name, age):
print(f"My name is {name} and my age is {age}")
hey_buddy("Kriss Moris", 22)
Output:
My name is Kriss Moris and my age is 22
2) Keyword Parameters:
Keyword arguments allow you to pass arguments by assigning them with the parameter names.
In this way, you specify which argument gosed to which parameter, meaning the order of the arguments does not matter.
Syntax:
def fun_name(perameter1, perameter2):
#your codee
sum_these(perameter2 = value, perameter1 = value)
Example:
def hey_buddy(name, age, number):
print(f"My name is {name} and my age is {age} and Number is {number}")
hey_buddy(age = 22, number = 9284632483, name = "Kriss Moris")
Output:
My name is Kriss Moris and my age is 22 and Number is 9284632483
3) Default Parameters:
You can set default values for parameters. If no argument is passed, the default value is used, or if the user pass a value for that parameter then the pass value of used by the parameter.
In this way, you specify which argument gosed to which parameter, meaning the order of the arguments does not matter.
Syntax:
def fun_name(perameter1, perameter2 = "some value"):
#your codee
sum_these(value1)
Example:
def hey_buddy(name, wish = "Good Morning!"):
print(wish, name)
hey_buddy("kriss")
Output:
Good Morning! kriss
If we pass argument for default Parameters,
def hey_buddy(name, wish = "Good Morning!"):
print(wish, name)
hey_buddy("kriss", "Good Night")
Output:
Good Night kriss
4) Variable-length Parameters:
These are used when you do not know how many values or arguments the user pass, then we are going with Variable-length Parameters.
i) Arbitrary Positional Arguments (*args):
Collects multiple positional arguments as a tuple.
Syntax:
def fun_name(*args):
# your code
fun_name(value1, value2, value3, ........)
Example:
def students(*args):
print(args)
students("kriss moris", "dishu", "jarves", "stark")
Output:
('kriss moris', 'dishu', 'jarves', 'stark')
#now the data is in a tuple with name args, you can use this tuple in many way.
ii) AArbitrary Keyword Arguments (**kwargs):
Collects extra keyword arguments as a dictionary.
Syntax:
def fun_name(**kwargs):
# your code
fun_name(key1 = value1, key2 = value2, key3 = value3, ........)
Example:
def UserInfo(**kwargs):
print(kwargs)
UserInfo(Name = "Kriss", Age = 20, Email = "[email protected]")
Output:
{'Name': 'Kriss', 'Age': 20, 'Email': '[email protected]'}
#now the data is in a dict with name kwargs, you can use this dict in many way.
Common interview questions related to parameters and arguments in Python
Question 1. What is the difference between parameters and arguments in Python?
Answer:
Parameters are variables defined in the function signature that accept values when the function is called.
Arguments are the actual values you pass to the function when calling it.
Example:
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")
greet("Alice")
Output:
Hello, Alice!
Question 2. How do default parameters work in Python?
Answer: Default parameters allow you to set a default value for a parameter. If no argument is provided for that parameter when the function is called, the default value is used.
Example:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Bob")
greet("Alice", "Hi")
Output:
Hello, Bob!
Hi, Alice!
Question 3. Can you explain what *args and **kwargs are?
Answer:
*args allows a function to accept any number of positional arguments, which are collected as a tuple.
**kwargs allows a function to accept any number of keyword arguments, which are collected as a dictionary.
Example:
def display_info(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
display_info(1, 2, 3, name="Alice", age=25)
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 25}
Question 4. What is the importance of keyword arguments in function calls?
Answer: Keyword arguments enhance code readability and flexibility by allowing you to specify which argument corresponds to which parameter, irrespective of the order.
Example:
def order(food, drink):
print(f"Food: {food}, Drink: {drink}")
order(drink="Coffee", food="Sandwich")
Output:
Food: Sandwich, Drink: Coffee
Question 5. What happens if you pass the wrong number of arguments to a function?
Answer: If you pass fewer arguments than required, Python raises a TypeError, indicating that the function is missing required positional arguments. If you pass more arguments than expected, Python raises a TypeError, indicating that the function takes a specific number of arguments.
Example:
def multiply(a, b):
return a * b
# Calling with fewer arguments
multiply(5) # Raises TypeError: missing 1 required positional argument: 'b'
# Calling with more arguments
# multiply(5, 3, 2) # Raises TypeError: multiply() takes 2 positional arguments but 3 were given
Output:
TypeError: multiply() missing 1 required positional argument: 'b'
Question 6. How do you handle variable-length arguments in a function?
Answer: You can handle variable-length arguments using *args for positional arguments and **kwargs for keyword arguments. This allows the function to accept any number of arguments.
Example:
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3))
print(sum_all(5, 10, 15, 20))
Output:
6
50
Tags:
Leave a comment
You must be logged in to post a comment.