Just Python Part 6— Functions

Syntax of Function

def func_name( parameters ):
"function_docstring"
function_suite
return [expression]

Defining a Function

  • Function blocks begin with the keyword def followed by the function name and parentheses “ ( ) “.
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The first statement of a function can be an optional statement — the documentation string of the function or docstring.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Rules for naming python function (identifier)

  1. It can begin with either of the following: A-Z, a-z, and underscore(_).
  2. The rest of it can contain either of the following: A-Z, a-z, digits(0–9), and underscore(_).
  3. A reserved keyword may not be chosen as an identifier.
def hello():
print("Hello")
def func1():
"""
This is docstring
"""
print("Hello")
func1.__doc__
>> func1.__doc__
'\n\tThis is the docstring\n\t'

Calling a Function

def my_function():
print("Hello from a function")

my_function()
>>> def my_function():
pass

>>> my_function()

Python Function Argument

  1. Default argument
  2. Keyword argument
  3. Arbitrary argument

Default argument

# Function definition is here
def info( name, age = 35 ):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return;
# Now you can call info function
info( age=50, name="miki" )
info( name="miki" )
Name:  miki
Age 50
Name: miki
Age 35
def sum(a=1,b):
return a+b

Keyword Arguments

def my_function(child3, child2):
print("The youngest child is " + child3)

my_function(child2 = "Tobias", child3 = "Linus")def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments, *args

def my_function(*kids):
print("The youngest child is {kids}")

my_function("Emil", "Tobias", "Linus")

Arbitrary Keyword Arguments, **kwargs

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Passing a List as an Argument

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Python return statement

def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print("Inside the function : ", total)
return total;

# Now you can call sum function
total = sum( 10, 20 );
print("Outside the function : ", total)
Inside the function :  30
Outside the function : 30

Scope and Lifetime of Variables in Python

  • Global variables
  • Local variables
def func3():
x=7
print(x)
>>> func3() #O/P: 7
>>> x
z = 7
def func3():
print(z)
>>> func3() #O/P: 7
>>> def func4():
global y
y+=1
print(y)
>>> func4() #O/P: 8

Lifetime

>>> def func1():
counter=0
counter+=1
print(counter)
>>> func1() #O/p: 1
>>> func1() #O/p: 1

Deleting Python function

>>> del func7
>>> func7()

Python Lambda Expressions

x = lambda a : a + 10
print(x(5))
>>> myvar=lambda a,b:(a*b)+2
>>> myvar(3,5)
17
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Why Use Lambda Functions?

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11)) #Output: 11 * 2 = 22
  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
  • An anonymous function cannot be a direct call to print because lambda requires an expression
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Python Recursion Function

def facto(n):
if n==1:
return 1
return n*facto(n-1)

facto(5) #output is 120

Conclusion: Python Functions

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store