Python tutorial
Python function parameters
Python function can be declared and defined without parameters. Here fun() is a function which accepts no parameters.
for ex:def fun(): print('fun() function called without/no arguments'); --calling a function fun()
Python function can be declared and defined with single or multiple parameters. each parameter should be seperated by comma, These parameters are also called as positional parameters, positions means str1 is at position1 ad str2 at position2 etc.,
for ex: concatenate stringsdef concat(str1,str2): return str1+str2Calling a function with values
concat('Sports','Car')**Incompatible types may throw an exception. for ex: concat('NINE',9) unsupported operand type(s) for +: 'int' and 'str'
In other Programming Languages its called as "Named Parameters". But in Python it's called as keyword Parameters, in the sense , while calling a functions, name is assigned to a value, one advantage over positional parameters is, it can be in any order.
>>>def email(name,domain): return name+'@'+domain;
>>>email(name='sam',domain='google.com') sam@google.com >>>email(domain='rediffmail.com',name='swathi') swathi@rediffmail.com
Parameter(s) can have default values,i.e a value assigned in the function declaration. caller can pass/ignore default parameters.
for ex: creating a email addressdef email(name,domain='@domain.com') return name+domain email('sam') sam@domain.com email('preeth') preeth@domain.com email('james','@yahoo.com') james@yahoo.com above 2 cases uses default value in the domain variable 3rd case uses domain @yahoo.com, While calling email function in first 2 cases ignored/didnt supply domain variable value.Note:Default arguments should be specified at the end of function parameter list. otherwise following error occurs:SyntaxError: non-default argument follows default argument
Variable Number of positional Parameters can be specified using *
varargs collecting:collect arbitrarily many positional arguments. variable number of arguments are stored as a tuple
for ex: variable number of arguments function definitiondef fun(*args): print(args)Calling variable number of arguments function
fun() # empty tuple () fun(1) # tuple has one element (1) fun(1,2,3,4,5,6) # tuple has 6 elements (1,2,3,4,5,6)Note: Output displayed as a tuple.
def fun(*args): a,b,c = args print(a,b,c) fun(1,2,3) # 1 2 3unpacking tuple indo individual variables, passing as many values as possible.
def fun(*args): a,b,*c = args print(a,b,c) fun(1,2,3,4,5) # 1 2 [3, 4, 5] #Now a is 1 , b=2 and c holds remaining values as a list
Variable Number of keyword Parameters/arguments using **
def fun(**kargs): print(kargs)Calling a keyword arguments function
fun() # {} fun(name='sam') # {'name':'sam'} fun(city='New York', country='USA') # {'city':'New York', 'country':'USA'}
One Advantage of Calling a function with keyword arguments, code is readble and unlike positional parameters, keywords arguments can be used in any order,because param name always associated with a value.
A function can be passed as an argument to other function.
def fun(fn): fn(); def fn(): print('Hello World') //Calling main function fun(fn) prints 'Hello World'
In above case if you pass function as param, it calls that function and executes it. in case if you pass any other type as a param, it checks for that object implemented callable method or not, if so, it executes it,otheriwse prints error message TypeError: 'int' object is not callable because int object doesnt implement call method,so for other built-in types.
In order to avoid such error, you need to check whether param is callable or not. as shown belowdef fun(fn): if callbale(fn) : fn(); fun(fn) # prints 'hello world' fun(1), fun(2.5), fun("abc") // all these doesnt implemente call method, code doent execute.
Python functions supports Typed Parameters, i.e Type can be specified for parameters in the declaration of a function. This types can be any built-in types or user defined types classes. Encorcing a type at the declaration itself can reduce compile and runtime errors. This can lead to better readability and maintainability.
Synatx:def function_name(var1 : type, var2 : type, var3 : type):Function returns a max value between 2 numbers.
def max(num1: int, num2 : int): return num1 if num1 > num2 else num2;
The above function max takes 2 formal parameters num1 & num2 of Type int,
fun(num2=10,20) ^ SyntaxError: positional argument follows keyword argument fun(num2=10,num2=20) File "", line 1 SyntaxError: keyword argument repeated: num2
ADS