Functions
Rushikesh J.
Software Test Engineer @Vinz Global | Robot Framework | Manual Testing, Automation Testing | Python | Selenium | GIT | JIRA | Immediate Joiner | API Testing Using Postman | Jenkins
Functions are of two types -
1) Built in -- Ex . print(),range()
2) User Defined
Defining Function -
In Python a function is defined using the def keyword
#We can define functions using def keyword and name of the function with parenthesis
def greet():
#Body Of The Function
print("Hi ! Have a Good Day")
How to call a function --
def greet():
print("Hi ! Have a Good Day")
#We can call a function using function name and parenthesis
greet()
#output
Hi ! Have a Good Day
Python Docstring -
Python docstrings are the string literals that appear right after the definition of a function
In Any IDE when we enter ctrl+Q on built-in function it will show some text like what this function will do but this is available for bulit - in function
We can add this type of docstring to user defined keyword
as we can see in below image
#In starting of the body of function we can declare docstring using """Docstring"""
def greet():
"""When we call this function it will greet"""
print("Hi ! Have a Good Day")
greet()
Parameter And Arguments --
Parameter -A parameter is the variable listed inside the parentheses in the function definition
Arguments - An argument is the value that is sent to the function when it is called.
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
def greet(name): # name is parameter
print("Hi " + name +" Have a Good Day ")
greet("Rushikesh") # Rushikesh is an argument
greet("Sagar")
#output
Hi Rushikesh Have a Good Day
Hi Sagar Have a Good Day
Return Statement in Python -
def add(a,b):
c = a + b
return c
c = add(10,20)
print(c,type(c))
#Output
30 <class 'int'>
def add1(a,b):
c = a + b
print(c)
d = add1(2,4)
print(d,type(d))
#Output
6
None <class 'NoneType'>
def func():
return
e = func()
print(type(e))
#Output
<class 'NoneType'>
def func():
print("Before Return")
return "rushikesh"
print("After return")
e = func()
print(e)
#Output
Before Return
rushikesh
领英推荐
Returning Multiple Values--
# We can use multiple variable
def intro(name ,age,hobby):
return name,age,hobby
c,d,e = intro("Rushikesh",25,"Reading")
print(c,d,e)
#Output
Rushikesh 25 Reading
#Or we can use one variable it will return as a tuple
def intro(name ,age,hobby):
return name,age,hobby
c = intro("Rushikesh",25,"Reading")
print(c,type(c))
#Output
('Rushikesh', 25, 'Reading') <class 'tuple'>
Scope Of Variable --
#Global Variable
a = 5 # a is global variable it can be used anywhere in program
def func():
print(a)
func()
#Output
5
********************************
#Local Variable
def func():
x = 3 # x is local variable the scope of the x is only func function , we can use x outside of the function
print(x)
func()
print(x)
#Output
3
Traceback (most recent call last):
File "C:\Users\Rushi Reddy\OneDrive\文档\Desktop\Python\Practice\variablescope.py", line 12, in <module>
print(x)
^
NameError: name 'x' is not defined
***********************************
# Local And Global with same name
a = 5
def func():
a =20
print(a)
print(a) # It will print 5
func()
print(a)
#Output
5
20
5
*************************************
a = 5
def func():
global a
a = 20
print(a)
print(a) # we didn't call the function yet so the value of a still not updated hencce it will print 5
func()
print(a)
#Output
5
20
20
Lambda Function --
x = lambda a : a+10
print(x(10))
y = lambda a,b: a*b
print(y(3,4))
#Output
20
12
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number
def func(n):
return lambda a : a*n
double = func(3)
print(double(10))
#Output
30
Types of Arguments --
1) Positional Arguments - During a function call, values passed through arguments should be in the order of parameters in the function definition. This is called positional arguments.
def intro(name ,hobby):
print("My Name is",name)
print("And My Hooby is",hobby)
intro("Rushikesh","Cycling")
#Output
My Name is Rushikesh
And My Hooby is Cycling
**************************
def intro(name ,hobby):
print("My Name is",name)
print("And My Hooby is",hobby)
intro("sagar")
#Output
Traceback (most recent call last):
File "C:\Users\Rushi Reddy\OneDrive\文档\Desktop\Python\Practice\lambdafunc.py", line 26, in <module>
intro("sagar")
TypeError: intro() missing 1 required positional argument: 'hobby'
2) Default Arguments -
Note - The Position Of default argument and non default argument
Default arguments should follow non-default arguments i.e we have to pass first non default arguments and then default argument else it will throw an error
def intro(hobby = "Reading",name): # Here we define the default value for hobby
print("My Name is",name)
print("And My Hooby is",hobby)
intro("sagar") # here we didnt pass the argument for hobby,it will take reading the hobby
#output
File "C:\Users\Rushi Reddy\OneDrive\文档\Desktop\Python\Practice\lambdafunc.py", line 28
def intro(hobby = "Reading",name): # Here we define the default value for hobby
^^^^
SyntaxError: non-default argument follows default argument
def intro(name ,hobby = "Reading"): # Here we define the default value for hobby
print("My Name is",name)
print("And My Hooby is",hobby)
intro("sagar") # here we didnt pass the argument for hobby,it will take reading the hobby
#Output
My Name is sagar
And My Hooby is Reading
3) Arbitrary Arguments -
def func(*args):
print(args)
print(type(args))
for i in args:
print(i)
func(2,3,4)
#Output
(2, 3, 4)
<class 'tuple'>
2
3
4
4) Keyword Arguments -
def func2(a,b,c):
d = a*(b+c)
print(d)
func2(c = 2 ,b = 3 ,a =5)
#Output
25
***********************************
def func(**kwargs):
print(kwargs)
print(type(kwargs))
for i in kwargs:
print(i)
func(a= 1, b= 3, c = 5)
#Output
{'a': 1, 'b': 3, 'c': 5}
<class 'dict'>
a
b
c