Pass parameters to function in python

Python Function Arguments

This article explains Python’s various function arguments with clear examples of how to use them. But before learning all function arguments in detail, first, understand the use of argument or parameter in the function.

Table of contents

What is a function argument?

When we define and call a Python function, the term parameter and argument is used to pass information to the function.

  • parameter: It is the variable listed inside the parentheses in the function definition.
  • argument: It is a value sent to the function when it is called. It is data on which function performs some action and returns the result.

In this example, the function sum_marks() is defined with three parameters, a , b , c , and print the sum of all three values of the arguments passed during a function call.

# a, b, c are arguments of the function def my_sum(a, b, c): s = a + b + c return s print('Total is:', my_sum(30, 40, 50))

function argument and parameter

Note: A function must be called with the correct number of arguments by default. For example, the above function expects 3 arguments, so you have to call the my_sum() function with 3 arguments; otherwise, you will get an error.

Does function need arguments?

It is not mandatory to use arguments in function definition. But if you need to process user data, you need arguments in the function definition to accept that data.

Also, we use argument in function definition when we need to perform the same task multiple times with different data.

Can a function be called without arguments?

If the function is defined with parameters, the arguments passed must match one of the arguments the function accepts when calling.

Types of function arguments

There are various ways to use arguments in a function. In Python, we have the following 4 types of function arguments.

  1. Default argument
  2. Keyword arguments (named arguments)
  3. Positional arguments
  4. Arbitrary arguments (variable-length arguments *args and **kwargs )

Types of Python function arguments explained with examples

Default Arguments

In a function, arguments can have default values. We assign default values to the argument using the ‘=’ (assignment) operator at the time of function definition. You can define a function with any number of default arguments.

The default value of an argument will be used inside a function if we do not pass a value to that argument at the time of the function call. Due to this, the default arguments become optional during the function call.

It overrides the default value if we provide a value to the default arguments during function calls.

Let us understand this with an example.

Let’s define a function student() with four arguments name , age , grade , and school . In this function, grade and school are default arguments with default values.

  • If you call a function without school and grade arguments, then the default values of grade and school are used.
  • The age and name parameters do not have default values and are required (mandatory) during a function call.
# function with 2 keyword arguments grade and school def student(name, age, grade="Five", school="ABC School"): print('Student Details:', name, age, grade, school) # without passing grade and school # Passing only the mandatory arguments student('Jon', 12) # Output: Student Details: Jon 12 Five ABC School

Passing one of the default arguments:

Читайте также:  Как установить css стим

If you pass values of the grade and school arguments while calling a function, then those values are used instead of default values.

# function with 2 keyword arguments grade and school def student(name, age, grade="Five", school="ABC School"): print('Student Details:', name, age, grade, school) # not passing a school value (default value is used) # six is assigned to grade student('Kelly', 12, 'Six') # passign all arguments student('Jessa', 12, 'Seven', 'XYZ School')
Student Details: Kelly 12 Six ABC School Student Details: Jessa 12 Seven XYZ School

Keyword Arguments

Usually, at the time of the function call, values get assigned to the arguments according to their position. So we must pass values in the same sequence defined in a function definition.

For example, when we call student(‘Jon’, 12, ‘Five’, ‘ABC School’) , the value “Jon” gets assigned to the argument name, and similarly, 12 to age and so on as per the sequence.

We can alter this behavior using a keyword argument.

Keyword arguments are those arguments where values get assigned to the arguments by their keyword (name) when the function is called. It is preceded by the variable name and an ( = ) assignment operator. The Keyword Argument is also called a named argument.

# function with 2 keyword arguments def student(name, age): print('Student Details:', name, age) # default function call student('Jessa', 14) # both keyword arguments student(name='Jon', age=12) # 1 positional and 1 keyword student('Donald', age=13)
Student Details: Jessa 14 Student Details: Jon 12 Student Details: Donald 13

Change the sequence of keyword arguments

Also, you can change the sequence of keyword arguments by using their name in function calls.

Python allows functions to be called using keyword arguments. But all the keyword arguments should match the parameters in the function definition. When we call functions in this way, the order (position) of the arguments can be changed.

# both keyword arguments by changing their order student(age=13, name='Kelly') # Output: Student Details: Kelly 13

Positional Arguments

Positional arguments are those arguments where values get assigned to the arguments by their position when the function is called. For example, the 1st positional argument must be 1st when the function is called. The 2nd positional argument needs to be 2nd when the function is called, etc.

By default, Python functions are called using the positional arguments.

Example: Program to subtract 2 numbers using positional arguments.

def add(a, b): print(a - b) add(50, 10) # Output 40 add(10, 50) # Output -40

Note: If you try to pass more arguments, you will get an error.

def add(a, b): print(a - b) add(105, 561, 4)
TypeError: add() takes 2 positional arguments but 3 were given

Note: In the positional argument number and position of arguments must be matched. If we change the order, then the result may change. Also, If we change the number of arguments, we will get an error.

Читайте также:  Python list index with lambda

Important points to remember about function argument

Point 1: Default arguments should follow non-default arguments

def get_student(name, grade='Five', age): print(name, age, grade) # output: SyntaxError: non-default argument follows default argument

Point: Default arguments must follow the default argument in a function definition

Default arguments must follow the default argument. For example, When you use the default argument in a definition, all the arguments to their right must also have default values. Otherwise, you’ll get an error.

def student(name, grade="Five", age): print('Student Details:', name, grade, age) student('Jon', 'Six', 12) # Output: SyntaxError: non-default argument follows default argument

Point 2: keyword arguments should follow positional arguments only.

we can mix positional arguments with keyword arguments during a function call. But, a keyword argument must always be after a non-keyword argument (positional argument). Else, you’ll get an error.

I.e., avoid using keyword argument before positional argument.

def get_student(name, age, grade): print(name, age, grade) get_student(name='Jessa', 12, 'Six') # Output: SyntaxError: positional argument follows keyword argument

Point 3: The order of keyword arguments is not important, but All the keyword arguments passed must match one of the arguments accepted by the function.

def get_student(name, age, grade): print(name, age, grade) get_student(grade='Six', name='Jessa', age=12) # Output: Jessa 12 Six get_student(name='Jessa', age=12, standard='Six') # Output: TypeError: get_student() got an unexpected keyword argument 'standard'

Point 4: No argument should receive a value more than once

def student(name, age, grade): print('Student Details:', name, grade, age) student(name='Jon', age=12, grade='Six', age=12) # Output: SyntaxError: keyword argument repeated

Variable-length arguments

In Python, sometimes, there is a situation where we need to pass multiple arguments to the function. Such types of arguments are called arbitrary arguments or variable-length arguments.

We use variable-length arguments if we don’t know the number of arguments needed for the function in advance.

Types of Arbitrary Arguments:

The *args and **kwargs allow you to pass multiple positional arguments or keyword arguments to a function.

Arbitrary positional arguments ( *args )

We can declare a variable-length argument with the * (asterisk) symbol. Place an asterisk ( * ) before a parameter in the function definition to define an arbitrary positional argument.

we can pass multiple arguments to the function. Internally all these values are represented in the form of a tuple. Let’s understand the use of variable-length arguments with an example.

This is a simple function that takes three arguments and returns their average:

def percentage(sub1, sub2, sub3): avg = (sub1 + sub2 + sub3) / 3 print('Average', avg) percentage(56, 61, 73)

This function works, but it’s limited to only three arguments. What if you need to calculate the average marks of more than three subjects or the number of subjects is determined only at runtime? In such cases, it is advisable to use the variable-length of positional arguments to write a function that could calculate the average of all subjects no matter how many there are.

# function with variable-length arguments def percentage(*args): sum = 0 for i in args: # get total sum = sum + i # calculate average avg = sum / len(args) print('Average =', avg) percentage(56, 61, 73)

Note: args is just a name. You can choose any name that you prefer, such as *subjects.

def percentage(*subjects): sum = 0 for i in subjects: # get total sum = sum + i # calculate average avg = sum / len(subjects) print('Average =', avg) percentage(56, 61, 73)

Arbitrary keyword arguments (**kwargs)

We saw how to use *args . Now let’s see how to use the **kwargs argument. The **kwargs allow you to pass multiple keyword arguments to a function. Use the **kwargs if you want to handle named arguments in a function.

Читайте также:  Html нажатие клавиш код

Use the unpacking operator( ** ) to define variable-length keyword arguments. Keyword arguments passed to a kwargs are accessed using key-value pair (same as accessing a dictionary in Python).

# function with variable-length keyword arguments def percentage(**kwargs): sum = 0 for sub in kwargs: # get argument name sub_name = sub # get argument value sub_marks = kwargs[sub] print(sub_name, " wp-block-preformatted">math = 56 english = 61 science = 73

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

How to pass a parameter to a function in Python

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Overview

A function is a container for a few lines of code that perform a simple task. Defining a function in Python means that we are creating a function.

Functions in Python are created and denoted with the def keyword followed by a function name. For example, greet_customer followed by a set of parentheses () . The parameters of the function are stored in the parentheses.

Parameters

A parameter is a variable listed inside the parentheses in the function definition. For example greet_customer(name) is a function that has (name) as its parameter.

How to pass a parameter to a function

The purpose of function parameters in Python is to allow a programmer using the function to define variables dynamically within the function.

It’s important to note that after passing a parameter to a function, an argument should be passed to the parameter of the function whenever you call the key function in your program.

Note: An argument is a value that is supplied to the parameter whenever the function is called.

Now, let’s pass a parameter to a function that will help us store the name of our customers by returning the argument (real name) we pass to that function.

Источник

Оцените статью