Functions

Functions

  • A function is a block of code which only runs when it is called
  • It helps in reusability of code
  • It aslo helps to reducing errors in code
  • It make code managable and organized

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 -

  • A function call ends when return statement is executed
  • It retrun the expression back to the function
  • The code after retrun statement are not executed
  • If there are no return value then function retrun none

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 --

  • There are two scope of variable -1) Global 2) Local
  • Global varibale can be used anywhere in program
  • Local variable can be used locally inside program(function)

#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 --

  • A lambda function is a small anonymous function.
  • A lambda function can take any number of arguments, but can only have one expression
  • These are mainly used when we need nameless function for short period of time
  • Syntax - lambda arguments : expression

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 -

  • Giving Default values to the parameters,
  • Default arguments become optional during the function calls,
  • The assignment operator = is used to assign a default value to the argument

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 -

  • when number of arguments you want pass is not known
  • These arguments will be wrapped up in a tuple
  • add a * before the parameter name in the function definition.

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 -

  • You can also send arguments with the key = value syntax.
  • This way the order of the arguments does not matter.
  • it stores the data in dictionary format

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        


要查看或添加评论,请登录

社区洞察

其他会员也浏览了