Unit 4
Unit 4
Unit 4
Syntax of Function
def function_name (parameters):
statement(s)
my_function()
Output:
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 1
Scripting Language – Python (4330701)
4.2 Passing parameters to a function and returning values from a function
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 (name). When the function is called,
we pass along a name, which is used inside the function to print the name:
calling a function:
my_function ('22CE')
Output:
Returning a Values: To let a function return a value, use the return statement:
Example of a function with parameter and return value:
def my_function(x):
return 5 * x
calling a function:
print (my_function(3))
print (my_function(5))
print (my_function(9))
Output:
15
25
45
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 2
Scripting Language – Python (4330701)
Example of functions
Function :without argument and without return Function :with argument and without return type
type
Output: Output:
sum is 30 sum is 30
Function :without argument and with return type Function :with argument and with return type
Output: Output:
sum is 30 sum is 30
Python Default Arguments:
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=).
Example:
def sum(a,b=10): def my_function (name, msg="Good morning!"):
return a+b print("Hello ", name, msg)
print(sum(5))
print(sum(5,5)) my_function ("21CE")
my_function ("ENGINEERS", "How do you do?")
Output: Output:
15 Hello 21CE Good morning!
10 Hello ENGINEERS, How do you do?
4.3 Recursion
What is recursion?
A Function calls itself is said to be a recursion.
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively.
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 3
Scripting Language – Python (4330701)
Python Recursive Function:
In Python, we know that a function can call other functions. It is even possible for the function to
call itself. These types of construct are termed as recursive functions.
The following image shows the workings of a recursive function called recurse.
Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example :
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
calling a function:
num = 3
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 3 is 6
Let's look at an image that shows a step-by-step process of what is going on:
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 4
Scripting Language – Python (4330701)
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting
in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results in
RecursionError.
Advantages of Recursion
Recursive functions make the code look clean and elegant.
A complex task can be broken down into simpler sub-problems using recursion.
Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
Sometimes the logic behind recursion is hard to follow through.
Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
Recursive functions are hard to debug.
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 5
Scripting Language – Python (4330701)
Python standard libraries make the program simpler and remove the need to rewrite commonly
used commands again and again.
They can be used by calling/importing at the beginning of python script.
Python contains built-in modules that are already programmed into the language and user
defined modules are created by user.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
A file containing Python code, for example: example.py, is called a module, and its module
name would be example.
result = a + b
print( result)
Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.
>>import example
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 6
Scripting Language – Python (4330701)
This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there.
Using the module name we can access the function using the dot ( . ) operator. For example:
>>> example.add(4,5.5)
9.5
Python has tons of standard modules. You can check out the full list of Python standard
modules and their use cases. These files are in the Lib directory inside the location where you
installed Python.
Various ways to import modules
Python import statement:We can import a module using the import statement and access the
definitions inside it using the dot operator.
Example.
import math
print("The value of pi is", math.pi)
Output:
The value of pi is 3.141592653589793
Python from...import statement: We can import specific names from a module without importing
the module as a whole.
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 7
Scripting Language – Python (4330701)
The value of pi is 3.141592653589793
Import all names: We can import all names (definitions) from a module.
Here, we have imported all the definitions from the math module. This includes all names visible in
our scope except those beginning with an underscore(private definitions).
rand module - Random numbers generators
Python Random module is an in-built module of Python which is used to generate random
numbers.
It can be used to perform some action like to get a random number,select random element
from a list, shuffle elements randomly etc.
The random module has a set of methods, some of methods are listed here:
Output: 0.371793355562307
uniform( ): It is used to generate random floats between two given parameters.
Syntax: random.uniform(First number,Second number)
Example: import random
print(random.uniform(1,10))
Output: 7.771509161751196
randint( ): It returns a random integer between the given integers.
Syntax: random.randint(First number,Second number)
Example: import random
print(random.randint(1,10))
Output: 3
randrange( ): It returns a random integer from the range created by the start,stop and step
arguments.The value of start is 0 by default. The value of step is 1 by default.
Syntax: random. randrange (start,stop,step)
Example: import random
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 8
Scripting Language – Python (4330701)
print(random.randrange(1,10,2))
Output: 5
choice( ):It returns a randomly selected element from a non empty sequence.
Syntax: random.choice(sequence)
Example: Selecting random elements from the list, string, and tuple
Example 1: import random
print(random.choice((1,10,2)))
Output: 2
Example 2:import random
print(random.choice('computer'))
Output: o
choices( ): It returns a list from a non empty sequence.
Syntax: random.choices(sequence)
Example: Selecting random elements from the list, string, and tuple
Example 1: import random
print(random.choices((1,10,2)))
Output: [2]
Example 2:import random
print(random.choices('computer'))
Output: [‘o’]
shuffle(): It is used to shuffle a sequence (list). Shuffling means changing the position of the
elements of the sequence
Syntax: random.shuffle(sequence)
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 9
Scripting Language – Python (4330701)
Example : import math
print(math.ceil(8.23))
Output : 9
floor():Rounds a number down to the nearest integer
Example : import math
print(math.floor(8.23))
Output : 8
Logarithmic Functions
log() : It returns the log value of number with base b. If the base is not mentioned, the computed
value is of the natural log.
log2(a) : It returns the log value of number with base 2.
log10(a) function computes value of log a with base 10.
Example: Output:
import math
print (math.log(10)) 2.302585092994046
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 10
Scripting Language – Python (4330701)
print (math.log10(10)) 1.0
print (math.log2(10)) 3.321928094887362
We can use dir() function to get a list containing all attributes of a module.
Output
import datetime ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__',
print(dir(datetime)) '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime',
'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
Example :3(Get current date and time with different timezones.)(Using datetime class)
import datetime
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 11
Scripting Language – Python (4330701)
d=datetime.datetime.now() Output
d=d.replace(tzinfo=datetime.timezone.utc)
print(d) 2022-11-28 12:30:48.583378+00:00
print("Year:",d.year) Year: 2022
print("Month:",d.month) Month: 11
print("Date:",d.day) Date: 28
print("Hour:",d.hour) Hour: 12
print("Minute:",d.minute) Minute: 30
print("Second:",d.second) Second: 48
print("Timezone Information:",d.tzinfo) Timezone Information: UTC
Example:7 print today’s year, month and day (using date class)
import datetime Output
d = datetime.date.today()
print("Today's date is", d) Today's date is 2022-11-29
print("Current year:", d.year) Current year: 2022
print("Current month:", d.month) Current month: 11
print("Current day:", d.day) Current day: 29
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 12
Scripting Language – Python (4330701)
t2=date(2017,8,10)
t3=t1-t2
print(t3) 1867 days, 0:00:00
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 13
Scripting Language – Python (4330701)
from matplotlib import pyplot as plt
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.plot(x,y)
# function to show the plot
plt.show()
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 14
Scripting Language – Python (4330701)
from matplotlib import pyplot as plt
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.scatter(x, y)
plt.show()
4. Pie Chart: It refers to circular graph which is broken down into segments. It is used to show
the percentage or proportional data where each slice of pie represents a category.
EXAMPLE: OUTPUT:
import matplotlib.pyplot as plt
y =[25, 35, 25, 15]
plt.pie(y)
plt.show()
5. Histogram :
EXAMPLE: OUTPUT:
from matplotlib import pyplot as plt
y = [10, 5, 8, 4, 2]
plt.hist(y)
plt.show()
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 15
Scripting Language – Python (4330701)
We use a well-organized hierarchy of directories for easier access.
Python has packages for directories and modules for files.
As a directory can contain subdirectories and files, a Python package can have sub-packages
and modules.
A directory must contain a file named __init__.py in order for Python to consider it as a package.
This file can be left empty but we generally place the initialization code for that package in this
file.
Here is an example. Suppose we are developing a game. One possible organization of packages
and modules could be as shown in the figure below.
import Game.Level.start
Now, if this module contains a function named select_difficulty(), we must use the full name to
reference it.
Game.Level.start.select_difficulty(2)
Now create one more python file with name p2.py in EMP directory with following code.
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 16
Scripting Language – Python (4330701)
def getSalary():
salary=[1000,2000,3000]
return salary
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 17
Scripting Language – Python (4330701)
pip -V
Practical : Write a program using the function to find maximum from two numbers.
def max(x,y):
if x>y:
max=x
else:
max=y
return max
a=int(input("Enter a"))
b=int(input("Enter b"))
maximum=max(a,b)
print("maximum is:",maximum)
Output:
Enter a12
Enter b4
maximum is: 12
Practical : Create a user defined function which prints square of all the even numbers between 1 to 5
def square():
for i in range(1,6):
if i%2==0:
print(i*i)
square()
Output:
4
16
Practical :Create a user defined function which will return the count of numbers divisible by 5 in range
1 to 20.
def divisible():
count=0
for i in range(1,21):
if i%5==0:
count+=1
print("Total numbers divisible by 5 is:",count)
divisible()
Output:
Total numbers divisible by 5 is: 4
Prepared by: Mrs. Ami Patel and Mrs. Neha Patel (Lecturer in CE Dept.) Page 18