Arguments and Parameters in Python – Everything You Need to Know

Updated on October 23, 2024

Article Outline

When we define a function in Python programming, we have to feed them values. This is where we use arguments and parameters in Python.

 

In some basic terms, parameters are those placeholders in a definition of a function waiting to be replaced by values. They are the variables that are defined in the function’s parentheses. Then, arguments are the actual values we pass into the function when we call it. Those arguments fill the placeholders that are called parameters when the function runs.

 

Let’s look at an example. Think of a function as a machine, taking some inputs (arguments) and then producing some outputs based on its design (parameters).

def greet(name):  # 'name' is a parameter print(f"Hello, {name}!") user_name = input("Enter your name: ") greet(user_name)  # 'user_name' is the argument

Output:

Enter your name: Devesh Kumar Hello, Devesh Kumar!

Here, name is the parameter in the function definition. It’s waiting to accept a value when the function is called. The actual input, “Devesh Kumar,” is the argument.

 

Also Read: Python Functions

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Explain the Key Differences Between Arguments and Parameters

To simplify, parameters set the stage and arguments act on that stage. Here’s a quick comparison:

Criteria Parameters Arguments
Definition Parameters are the variables in the parentheses when we define a function. Arguments are the values we pass in when we call that function and provide it with some values.
Location Inside the parentheses in the function header. Inside the parentheses during the function call.
Role Placeholder waiting for values Actual data passed to the function
Example def add(a, b) add(5, 10)

 

Types of Arguments in Python Functions

There are a number of ways of passing arguments into functions in Python. Arguments can be categorised into four major types depending on how we use them:

  • Positional Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable-Length Arguments

Let’s break them down one by one:

1. Positional Arguments

Positional arguments are the most simple to work with in Python. Positionally, you must pass the arguments in the sequence defined by parameters. The position of each argument is important.

Example: Suppose a function has two parameters and is being called with two arguments. In that case, the first argument will go to the first parameter, and the second to the second parameter.

Now, let’s look at a code example:

def add_numbers(x, y): return x + y num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) result = add_numbers(num1, num2) print(f"The sum is: {result}")

Output:

Enter the first number: 7 Enter the second number: 10 The sum is: 17

In this example, the values that we pass in as num1 and num2 are passed into x and y in a way determined by the order in which the function is called.

 

Also Read: Python Function Overloading

2. Keyword Arguments

Keyword arguments allow us to pass arguments in by explicitly referencing the name of the parameter in the function call. This has the consequence that the order of the arguments becomes irrelevant so long as we reference the names of the parameters.

By using the keyword arguments, we can make our code pretty readable and avoid errors that could arise due to confusing the order of the arguments

Here’s how we can use keyword arguments in practice:

def add_numbers(x, y): return x + y num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) result = add_numbers(y=num2, x=num1)  # Using keyword arguments print(f"The sum is: {result}")

Output:

Enter the first number: 11 Enter the second number: 15 The sum is: 26

As you can see, we reversed the order of the arguments, but it worked fine because we used the parameter names x and y.

3. Default Arguments

The Default arguments are used to assign default values to parameters. If while calling the function no particular value is assigned for one of the arguments, Python uses the default value.

This is very useful when we wish for a function that can handle both cases: when an argument exists, and when it does not.

Let’s see this in action:

def greet(name="Guest"):  # 'Guest' is the default value print(f"Hello, {name}!") greet()  # No argument provided, uses default value greet("Sita")  # Argument provided, overrides default value

Output:

Hello, Guest! Hello, Sita!

In the first function call, we didn’t pass any arguments, so Python used the default value “Guest.” In the second call, we passed “Sita,” which replaced the default.

4. Variable-Length Arguments

We may encounter situations where we do not know in advance how many arguments a function has to accept. Python lets us handle this situation by using *args for non-keyword arguments and **kwargs for keyword arguments.

  • *args allows a function to accept any number of positional arguments.
  • **kwargs allows a function to accept any number of keyword arguments.

Here’s an example of how to use *args:

def sum_all(*numbers):  # Accepts any number of positional arguments total = sum(numbers) return total result = sum_all(1, 2, 3, 4, 5) print(f"The total sum is: {result}")

Output:

The total sum is: 15

Now, let’s look at **kwargs:

def greet_user(**info):  # Accepts any number of keyword arguments for key, value in info.items(): print(f"{key}: {value}") greet_user(name="Ravi", age=30, city="Bangalore")

Output:

name: Ravi age: 30 city: Bangalore

Importance of Argument Order and Common Pitfalls

When working with arguments and parameters in Python, it is important to know that the order matters. Have you ever passed arguments to a function only to get a really confusing error? This happens whenever the order of positional and keyword arguments gets mixed up.

In Python, positional arguments always go before keyword arguments. It’s not a good practice, it’s a rule. If we try to pass a positional argument after a keyword argument, Python raises a SyntaxError.

Here’s an extremely simple example:

def student_details(name, age): print(f"Student: {name}, Age: {age}") # Correct usage student_details("Rahul", 21) # Wrong usage student_details(name="Rahul", 21)  # Raises SyntaxError

Output:

SyntaxError: positional argument follows keyword argument

In the second call, we tried to pass a positional argument (21) after a keyword argument (name=”Rahul”), and Python didn’t like it.

How to not do that:

  • Always make sure that positional arguments are passed first.
  • Use keyword arguments for flexibility if the position does not matter.

Common Mistakes:

  • Missing Required Arguments: If all required positional arguments are not provided an error of TypeError is raised.
  • Conflicting Argument Types: When combining positional and keyword arguments, in the wrong order as above, then a TypeError is raised too.

All the above are totally avoided if ordered properly

Python’s Special Argument-Passing Model: Call by Assignment

Another question developers are likely to have about Python is whether it uses call by value or call by reference. The answer? It’s neither! Python uses a method known as call by assignment.

What does this mean, exactly?

When we pass arguments to a function, Python assigns the object’s reference to the parameter. If we pass mutable objects, for example, lists, the function can actually modify the original object. If we pass immutable objects, for example, integers, a modification inside the function wouldn’t affect the value outside.

Here’s a code example to show how it works:

def modify_list(my_list): my_list.append(4) print(f"Modified inside function: {my_list}") numbers = [1, 2, 3] modify_list(numbers) print(f"Modified outside function: {numbers}")

Output:

Modified inside function: [1, 2, 3, 4] Modified outside function: [1, 2, 3, 4]

In this case, since lists are mutable, both inside and outside the function, the list was changed.

Now let’s see how it works with an immutable object like an integer:

def modify_number(num): num += 5 print(f"Modified inside function: {num}") number = 10 modify_number(number) print(f"Unchanged outside function: {number}")

Output:

Modified inside function: 15 Unchanged outside function: 10

Although the number changed inside the function, it didn’t affect the value outside because integers are immutable.

So, when working with mutable objects like lists, dictionaries, or sets, you will be careful. Modifying something inside a function has an effect outside.

Mutable vs Immutable Objects: How They Affect Argument Passing in Python

As we pass arguments in Python, we need to know whether the object that we’re passing is mutable or immutable. Why? Because it changes the way Python passes those modifications around inside that function.

Mutable Objects

Mutable objects are those that can be changed once constructed. These are:

  • Lists
  • Dictionaries
  • Sets

If we pass a mutable object into a function and alter it inside the function then changes will reflect on that original object also, outside of the function.

Here’s another example with a dictionary:

def update_student_info(info): info['marks'] = 85 print(f"Updated inside function: {info}") student = {'name': 'Ravi', 'age': 20} update_student_info(student) print(f"Updated outside function: {student}")

Output:

Updated inside function: {'name': 'Ravi', 'age': 20, 'marks': 85} Updated outside function: {'name': 'Ravi', 'age': 20, 'marks': 85}

Both inside and outside the function, the dictionary was updated.

Immutable Objects

Immutable objects, on the other hand, cannot be changed after they are created. Examples include:

  • Integers
  • Strings
  • Tuples

When we pass immutable objects to a function, any changes made inside the function won’t affect the original object.

Here’s an example with a string:

def change_name(name): name = "Vikram" print(f"Changed inside function: {name}") student_name = "Rahul" change_name(student_name) print(f"Unchanged outside function: {student_name}")

Output:

Changed inside function: Vikram Unchanged outside function: Rahul

Since strings are immutable, the change inside the function did not propagate to the original student_name variable.

Function Parameters in Python and Their Flexibility in Function Design

Python functions have a lot of flexibility in designing them because of the several types of parameters available to use. We can mix up the compulsory, optional types of parameters along with the variable-length parameters such as *args and **kwargs.

Let’s see how to apply them in practice.

Required Parameters

These are the most basic type. We must provide arguments for every required parameter.

def multiply(a, b): return a * b result = multiply(3, 4) print(f"Result: {result}")

Here, a and b are required. If we don’t provide values for both, Python will raise an error.

Optional Parameters with Default Values

Sometimes, we don’t need to pass every argument. This is where default values come in handy. We can set a default value for a parameter, and if no argument is passed, Python uses the default.

def greet(name="Guest"): print(f"Hello, {name}!") greet()  # Uses default value "Guest" greet("Sita")  # Uses provided argument "Sita"

Variable-Length Parameters (*args and **kwargs)

Quite often, however, we do not know how many arguments we need to pass. *args lets us specify a variable number of positional arguments; **kwargs handles keyword arguments

def print_grades(*grades): for grade in grades: print(f"Grade: {grade}") print_grades(85, 90, 78)

Output:

def print_grades(*grades): for grade in grades: print(f"Grade: {grade}") print_grades(85, 90, 78)

In the above example, we passed a variable number of grades to the function, and it handled them smoothly.

Python gives us the flexibility to design functions based on our needs:

  • Required parameters for strict control.
  • Optional parameters for flexibility.
  • Variable-length parameters when we don’t know how many arguments we’ll get.

 

Enroll Now: Free Python Course

Common Mistakes When Using Arguments and Parameters in Python

When working with arguments and parameters in Python, we can easily run into mistakes that can break our code. Even the best programmers have these problems sometimes. Let’s discuss the most common mistakes and how you avoid them.

Forgetting to Provide Required Arguments

If a function has parameters that don’t have default values, Python expects us to provide them. Forgetting to pass a required argument results in a TypeError.

def add_numbers(a, b): return a + b # Forgot to pass the second argument result = add_numbers(5)  # Raises TypeError

Solution: Always check that you’ve provided values for all required parameters.

Mixing Positional and Keyword Arguments Incorrectly

As we discussed earlier, the order of arguments matters. Positional arguments must come before keyword arguments. Mixing them up leads to a SyntaxError.

def student_info(name, age): print(f"Name: {name}, Age: {age}") # Incorrect order: positional argument after keyword argument student_info(name="Arun", 25)  # Raises SyntaxError

Solution: Keep keyword arguments at the end when calling a function.

Modifying Mutable Default Arguments

The consequence of using mutable objects, such as lists or dictionaries, as default arguments is that you might get some unexpected behaviour. Changes made in the first call will be observed in the next because the object used is shared across all function calls.

def append_to_list(val, my_list=[]): my_list.append(val) return my_list print(append_to_list(1))  # Output: [1] print(append_to_list(2))  # Output: [1, 2] (unexpected)

Solution: Use None as the default value for mutable objects and initialise them inside the function.

Passing Too Many or Too Few Arguments

When there are more arguments than expected or fewer arguments than expected, a TypeError is raised. A function expects to take the same amount of arguments as parameters unless we’re using *args or **kwargs.

def greet(name, age): print(f"Hello, {name}, you are {age} years old.") # Too many arguments greet("Ravi", 25, "extra")  # Raises TypeError

Solution: Double-check the number of arguments passed and make sure it matches the function definition.

Misusing *args and **kwargs

Sometimes, developers get confused about how *args and **kwargs work, especially when used with other arguments. The key is to understand their placement: *args collects extra positional arguments, and **kwargs collects extra keyword arguments.

def display_info(name, *args, **kwargs): print(f"Name: {name}") print(f"Additional positional args: {args}") print(f"Additional keyword args: {kwargs}") display_info("Ravi", 25, "Engineer", city="Delhi", age=25)

Solution: Remember that *args and **kwargs should always come after regular parameters in the function definition.

 

Also Read: Python Interview Questions and Answers

Conclusion

A Programmer must know the difference between arguments and parameters in Python to write clean, effective code. With the ability to pass arguments of various kinds, including positional, keyword, default and variable-length, flexibility in function design is greatly added.

 

Knowing how Python behaves when passing arguments via call by assignment prevents people from stumbling over common pitfalls, especially involving both mutable and immutable objects. Avoid wasting time and getting frustrated over common errors involving either a mix-up of positional and keyword arguments or the use of mutable objects for default parameters.

 

Mastering these concepts helps us design flexible functions that can easily make their way through a wide array of inputs and sidestep common pitfalls for efficient coding in Python.

 

Want to dive deeper into Python and beyond? Then you must check out the Integrated Program in Data Science, Artificial Intelligence & Machine Learning by Hero Vired. This will prove beneficial in advancing your knowledge and being ready for future technology.

FAQs
Positional arguments must be passed in exactly the same order as the parameters of the function, whereas keyword arguments are passed by explicitly naming the parameter, and therefore the order doesn't matter.
Yes, but positional arguments have to go first. If we mix them, though, we'll get a SyntaxError.
Mutable objects like lists and dictionaries are passed around from function to function. If modified, the modifications persist from call to call, creating surprises about what your program is actually doing. Use None as default and initialise inside the function.
*args collects extra positional arguments and **kwargs collects extra keyword arguments. These are used when the number of arguments is unknown.
Python uses call by assignment. Mutable objects like lists get passed around by reference, and immutable objects like integers act as if they're passed by value.

Updated on October 23, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved