Python Unit-3
Functions in Python:
A function is a block of code which only runs when it is called. You can
pass data, known as parameters, into a function. A function can return data
as a result.
Creating a Function:
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis: as given
in following example:
Example:
def my_function():
print("Hello from a function")
my_function():
output:
Hello from a function
Arguments
Information can be passed into functions as arguments. Arguments are
specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example:
def my_function(fname):
print(fname + " Correct")
my_function("Emil")
my_function("Age")
my_function("Address")
output:
Emil Correct
Age Correct
Address Correct
Parameters or Arguments
The terms parameter and argument can be used for the same thing: inform
ation that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
Number of Arguments:
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.
Example:
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "is correct")
output:
Emil is correct
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
output:
TypeError Traceback (most recent call last)
<ipython-input-24-49655f8043be> in <module>
2 print(fname + " " + lname)
3
----> 4 my_function("Emil")
TypeError: my_function() missing 1 required positional argument: 'lname'
To remove the error in above program do the following :
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil",”is correct”)
output:
Emil is correct
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example:
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
output:
The youngest child is Linus
Note: Arbitrary Arguments are often shortened to *args in Python
documentations.
Keyword Arguments:
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "shanu", child2 = "suraj", child3 = "shiva")
output:
The youngest child is shiva
Notes: The phrase Keyword Arguments are often shortened to kwargs in
Python documentations.
Arbitrary Keyword Arguments, **kwargs:
If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
This way the function will receive a dictionary of arguments, and can
access the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter
name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "goel")
output:
His last name is goel
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.
E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
output:
apple
banana
cherry
Return Values
To let a function return a value, use the return statement:
Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
output:
15
25
45
The pass Statement
function definitions cannot be empty, but if you for some reason have a
function definition with no content, put in the pass statement to avoid
getting an error.
def myfunction():
pass
output:
No output
Recursion:
Python also accepts function recursion, which means a defined function
can call itself.
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can
loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy
to slip into writing a function which never terminates, or one that uses
excess amounts of memory or processor power. However, when written
correctly recursion can be a very efficient and mathematically-elegant
approach to programming.
In this example, tri_recursion() is a function that we have defined to call
itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not
greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
output:
Recursion Example Results
1
3
6
10
15
21
Infinitely Recursion:
In the following example recursion will be infinitely.
def nf():
print("hello")
nf()
nf()
output:
infinitely hello will be displayed
Scope Rules in Functions
Functions provide a nested namespace (sometimes called a scope),
which localizes the names they use, such that names inside the
function won’t clash with those outside (in a module or other function).
We usually say that functions define a local scope, and modules
define a global scope. The two scopes are related as follows:
The enclosing module is a global scope
Each module is a global scope—a namespace where variables created
(assigned) at the top level of a module file live.
Each call to a function is a new local scope
Every time you call a function, you create a new local scope—a namespace
where names created inside the function usually live.
Assigned names are local, unless declared global
By default, all the names assigned inside a function definition are put in the
local scope (the namespace associated with the function call). If you need
to assign a name that lives at the top-level of the module enclosing the
function, you can do so by declaring it in a global statement inside the
function.
Global Variable:
Example:
i=0
def nf():
global i
i=i+1
print("my output",i)
nf()
nf()
output:
infinitely the incremental value of i will be displayed on the screen because
of global variable(I is defined as a global variable).
Note: What happened when i is defined as a local variable, look in the
following example:
Example:
def nf():
i=0
i=i+1
print("my output",i)
nf()
nf()
output:
infinitely my output 1 will be displayed on the screen because of local
variable(I is defined as a local variable).
Notes:
Actually in python infinitely recursion is not allowed it is bounded, yet if
you want to know that how many times recursion is going on then use the
following code:
import sys
print(sys.getrecursionlimit())
output:
output depend on setting, it may be vary from python version to version.
Notes:
We can also set the recursion limit as given in the following example.
Example:
import sys
sys.setrecursionlimit(100)
print(sys.getrecursionlimit())
output:
100
Example:
import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(3000)
print(sys.getrecursionlimit())
output:
1000
3000
String:
Length of Strings and perform concatenation ad repeat
operation in it:
To calculate the length of a string in Python, you can use the built-in len()
method. It takes a string as a parameter and returns an integer as the
length of that string. For example len(“educative”) will return 9 because
there are 9 characters in “educative”.
Using the for loop
If you don’t want to use the len() method, you can calculate the length by
iterating the string using a for loop and incrementing a counter variable in
every iteration. The following code shows how this is done:
Example:
counter = 0
for c in "educative": # traverse the string “educative”
counter+=1 #increment the counter
print (counter) # outputs the length (9) of the string “educative”
output:
9
String Concatenation:
In Python, Strings are arrays of bytes representing Unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets [] can be used to access
elements of the string.
Example:
# Python program to demonstrate
# strings
# Assign Welcome string to the variable var1
var1 = "Welcome"
# Assign statistics string to the variable var2
var2 = "statistics"
# print the result
print(var1)
print(var2)
Output
Welcome
Statistics
String Concatenation in Python
String Concatenation is the technique of combining two strings. String
Concatenation can be done using many ways.
We can perform string concatenation using following ways:
1) Using + operator
2) Using join() method
3) Using % operator
4) Using format() function
5) Using , (comma)
Using + Operator
It’s very easy to use + operator for string concatenation. This operator can
be used to add multiple strings together. However, the arguments must be
a string.
Note: Strings are immutable, therefore, whenever it is concatenated, it is
assigned to a new variable.
Example:
# Python program to demonstrate
# string concatenation
# Defining strings
var1 = "Hello "
var2 = "World"
# + Operator is used to combine strings
var3 = var1 + var2
print(var3)
Output
Hello World
Here, the variable var1 stores the string “Hello ” and variable var2 stores the
string “World”. The + Operator combines the string that is stored in the var1
and var2 and stores in another variable var3.
Using join() Method
The join() method is a string method and returns a string in which the
elements of sequence have been joined by str separator.
Example:
# Python program to demonstrate
# string concatenation
var1 = "Hello"
var2 = "World"
# join() method is used to combine the strings
print("".join([var1, var2]))
# join() method is used here to combine
# the string with a separator Space(" ")
var3 = " ".join([var1, var2])
print(var3)
Output
Hello World
Hello World
In the above example, the variable var1 stores the string “Hello” and
variable var2 stores the string “World”. The join() method combines the
string that is stored in the var1 and var2. The join method accepts only the
list as it’s argument and list size can be anything. We can store the
combined string in another variable var3 which is separated by space.
Note: To know more about join() method click here.
Using % Operator
We can use % operator for string formatting, it can also be used for string
concatenation. It’s useful when we want to concatenate strings and
perform simple formatting.
Example:
# Python program to demonstrate
# string concatenation
var1 = "Hello"
var2 = "World"
# % Operator is used here to combine the string
print("% s % s" % (var1, var2))
Output
Hello World
Here, the % Operator combine the string that is stored in the var1 and var2.
The %s denotes string data type. The value in both the variable is passed to
the string %s and becomes “Hello World”.
Using format() function
str.format() is one of the string formatting methods in Python, which allows
multiple substitutions and value formatting. This method lets us
concatenate elements within a string through positional formatting.
Example:
# Python program to demonstrate
# string concatenation
var1 = "Hello"
var2 = "World"
# format function is used here to
# combine the string
print("{} {}".format(var1, var2))
# store the result in another variable
var3 = "{} {}".format(var1, var2)
print(var3)
Output
Hello World
Hello World
Here, the format() function combines the string that is stored in the var1
and var2 and stores in another variable var3. The curly braces {} are used to
set the position of strings. The first variable stores in the first curly braces
and second variable stores in the second curly braces. Finally it prints the
value “Hello World”.
Note: To know
more about format() function click here.
Using , (comma)
“,” is a great alternative to string concatenation using “+”. when you want to
include a single whitespace.
Example:
# Python program to demonstrate
# string concatenation
var1 = "Hello"
var2 = "World"
# , to combine data types with a single whitespace.
print(var1, var2)
Output
Hello World
Use , when you want to combine data types with a single whitespace in
between.