PPS_Notes_Unit 3

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 39

SINHGAD TECHNICAL EDUCATION SOCIETY’S

SINHGAD INSTITUTE OF TECHNOLOGY


Kusgaon (Bk), Lonavala 410401

DEPARTMENT OF ENGINEERING SCIENCES

Programming and Problem Solving [110005]

F.E. Eng Sci. (SEM –I)

AY 2022-23

Prepared By

Prof. S.B.Patil
Vision and Mission of Institute

VISION

उत्तमपुरुषान् उत्तमाभियंतृन् निर्मांतु कटिबद्धाःवयम्

“We are committed to produce not only good engineers but good human beings, also.”

MISSION

• We believe in and work for the holistic development of students and teachers.
• We strive to achieve this by imbibing a unique value system, transparent work culture,
excellent academic and physical environment conducive to learning, creativity and
technology transfer.

Vision and Mission of the Department

VISION

The department of Engineering Sciences is committed to support the core engineering programs
with fundamental knowledge and skills with acumen to be leaders amongst the generation of
engineers.
MISSION
The department of Engineering Sciences strives to incorporate the best pedagogical methods to
deliver basic sciences to engineering students and to guide them to be proactive learners, deep
thinkers and responsible citizens in the early stages of their engineering education.

Short Term Goals

 To foster students of first year engineering for the respective programs of engineering
through expert lectures, seminars & mini projects.
 To implement activity plan for overall development of students.
 To develop laboratories for meaningful implementation of curriculum and then for
research.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 2


 To encourage continuous up-gradation of faculty members through higher education and
external interface with other universities.

Long Term Goals

 To apply project and problem based leaning approach for first year engineering program
to create a bridge to support to core departments for guiding projects of students.
 To cultivate research in the field of Engineering Sciences for the benefit of society.

Program Educational Objectives: PEO’s

I. To provide opportunity to acquire strong theoretical and sound practical knowledge of


basic sciences, so as to enable them to excel in further education.
II. To develop talent among students to innovate, communicate, analyze, interpret and apply
technical concepts to solve real time engineering problems.
III.To aware and accomplish scientific and engineering breadth amongst student through
various curricular, co-curricular and extra-curricular activities.
IV. To inculcate professional and ethical attitude among students for providing engineering
solution in a global and societal context.
V. To accomplish the overall development of students with the aid of project based learning
environment.
Program Outcomes: POs

POs are statements that describe what students are expected to know and be able to do upon
graduating from the program. These relate to the skills, knowledge, analytical ability attitude and
behavior that students acquire through the program.

Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

i) Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences and engineering sciences.
ii) Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 3


iii) Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions for complex problems:
 that cannot be solved by straightforward application of knowledge, theories and techniques
applicable to the engineering discipline as against problems given at the end of chapters in a
typical text book that can be solved using simple engineering theories and techniques;
 that may not have a unique solution. For example, a design problem can be solved in many
ways and lead to multiple possible solutions;
 that require consideration of appropriate constraints / requirements not explicitly given in
the problem statement such as cost, power requirement, durability, product life, etc.;
 which need to be defined (modelled) within appropriate mathematical framework; and
 that often require use of modern computational concepts and tools, for example, in the
design of an antenna or a DSP filter.
iv) Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
v) The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
vi) Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
vii) Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
viii) Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
ix) Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
x) Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
xi) Life-long Learning: Recognize the need for, and have the preparation and ability to engage
in independent and lifelong learning in the broadest context of technological change.
Program Specific Outcomes: PSOs

1. Get solid foundation in basic sciences along with engineering fundamentals for a
successful professional career.
2. Able to co-relate engineering issues to broad social context.

Faculty of Engineering Savitribai Phule Pune


University

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 4


110005: Programming and Problem Solving

Credit: 04

Teaching Scheme: Examination Scheme:

Lecture : 03hr/week In-Sem: 30 Marks

End-Sem: 70 Marks

Course Objectives: Prime objective is to give students a basic introduction to programming and
problem solving with computer language Python. And to introduce students not merely to the
coding of computer programs, but to computational thinking, the methodology of computer
programming, and the principles of good program design including modularity and
encapsulation.
1) To understand problem solving, problem solving aspects, programming and to know about
various program design tools.
2) To learn problem solving with computers
3) To learn basics, features and future of Python programming.
4) To acquaint with data types, input output statements, decision making, looping and functions
in Python
5) To learn features of Object Oriented Programming using Python
6) To acquaint with the use and benefits of files handling in Python

Course Outcomes:

On completion of the course, student will be able to

CO1. Inculcate and apply various skills in problem solving.

CO2. Choose most appropriate programming constructs and features to solve the problems in
diversified domains.

CO3. Exhibit the programming skills for the problems those require the writing of well-
documented programs including use of the logical constructs of language, Python.

CO4. Demonstrate significant experience with the Python program development environment

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 5


FE -2019 Patten
Savitribai Phule University, Pune
Subject: Programming and Problem Solving [110005]

Unit III : Functions and Modules

Contents: Need for functions, Function: definition, call, variable scope and
lifetime, the return statement. Defining functions, Lambda or anonymous function,
documentation string, good programming practices. Introduction to modules,
Introduction to packages in Python, Introduction to standard library modules.
Unit Objectives :
On completion the students will be able to :
1. Understand Function.
2. Understand Lambda.
3. Get standard library modules.

Unit outcomes:
Students are able to understand the functions and modules:
1. Understand use of functions in python program.
2. Exhibit the programming skills for the problems those require the writing of well-
documented programs including use of the logical constructs of language, Python.
Start to apply various skills in problem solving using functions and modules.

Outcome Mapping: Mapping of PEO,PO, CO, PSO


PEOs: I, II POs: i, ii, iii PSOs: 3,4 COs:3

Books :
1. Reema Thareja, “Python Programming Using Problem Solving Approach”,
Oxford University Press

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 6


Introduction to Using Functions:
We have been using functions in Python since the first chapter. These functions include
print, input, int, float, str, and type. The Python standard library includes many other functions
useful for common programming tasks. In mathematics, a function computes a result from a
given value; for example, from the function definition f(x) = 2x+3 we can compute f(5) = 2·5 +
13 = 13 and f(0) = 2·0+3 = 3. A function in Pythonworkslikeamathematicalfunction.
Tointroducethefunctionconcept, wewilllookatthestandard Python function that implements
mathematical square root. In Python, a function is a named block of code that performs a specific
task. If an executing program needs to perform such a task, it calls upon the function to do the
work. One example of a function is the mathematical square root function. Python has a function
in its standard library named sqrt (see Section 6.4). The square root function accepts one numeric
(integer or floating-point) value and produces a floating-point result; for example, √16 = 4, so
when presented with 16.0, sqrt responds with 4.0. Figure 6.1 illustratestheconceptual viewofthe
sqrt function. The square root function islike a blackboxto the code that uses it. Callers do not
need to know the details of the code inside the function in order to use it. Programmers are
concerned more about what the function does, not how it does it.
Thissqrtfunctionisexactlywhatweneedforoursquarerootprogram,Listing5.33(computesquareroot.p
y). The new version, Listing 6.1 (standardsquareroot.py), uses the library function sqrt,
eliminating the complex logic of the original code.

File1:- standardsquareroot.py
from math import sqrt

# Get value from the user num = float(input("Enter number: "))

# Compute the square root root = sqrt(num)

# Report result print("Square root of", num, "=", root)

The expression

sqrt(num)

is a function invocation, also known as a function call. A function provides a service to the code
that uses it. Here, our code in Listing 6.1 (standardsquareroot.py) is the calling code, or client
code. Our code is the client that uses the service provided by the sqrt function. We say our code
calls, or invokes, sqrt passing it the value of num. The expression sqrt(num) evaluates to the
square root of the value of the variable num. Unlike the other functions we have used earlier, the
interpreter is not automatically aware of the sqrt function. The sqrt
functionisnotpartofthesmallcollectionoffunctions(like type, int,and str)always available to Python
programs. The sqrt function is part of separate module within the standard library. A module is a

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 7


collection of Python code that can used in other programs. The import keyword makes a module
available to the interpreter. The first statement in Listing 6.1 (standardsquareroot.py) shows one
way to use the import keyword:

from math import sqrt

Thisstatementmakesthe sqrt functionavailableforuseintheprogram. The math


modulehasmanyother mathematical functions. These include trigonometric, logarithmic,
hyperbolic, and other mathematical functions. This import statement will make only the sqrt
function available to the program.
Whencallingafunction,apairofparenthesesfollowthefunction’sname. Informationthatthefunction
requires to perform its task must appear within these parentheses. In the expression

sqrt(num)

num is the information the function needs to do its work. We say num is the argument, or
parameter, passed to the function. We also can say “we are passing num to the sqrt function.”
The function uses the variable num’s value to perform the computation. Parameters enable
callers to communicate information to a function during the function’s execution. The program
could call the sqrt function in many other ways, as Listing 6.2 (usingsqrt.py) illustrates.

File2: usingsqrt.py
# This program shows the various ways the

# sqrt function can be used.

from math import sqrt

x = 16

# Pass a literal value and display the result

print(sqrt(16.0))

# Pass a variable and display the result

print(sqrt(x))

# Pass an expression

print(sqrt(2 * x - 5))

# Assign result to variable

y = sqrt(x)

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 8


print(y)

# Use result in an expression

y = 2 * sqrt(x + 16) - 4

print(y)

# Use result as argument to a function call

y = sqrt(sqrt(256.0))

print(y)

print(sqrt(int('45')))

The Built-in Functions


These functions include print, input, int, float, str, and type. These functions and many others
reside in a module named __builtins__. The __builtins__ module is special because its
components are automatically available to any Python program with—no import statement is
required. The full name of the print functionis
__builtins__.print,althoughchancesareyouwillneverseeitsfullnamewritteninaPython program. We
can verify its fully qualified name in the interpreter:

>>> print('Hi')

Hi

>>> __builtins__.print('Hi')

Hi

>>> print <built-in function print>

>>> __builtins__.print

<built-in function print>

>>> id(print)

9506056

>>> id(__builtins__.print)

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 9


Standard Mathematical Functions
The standard math module provides much of the functionality of a
scientific calculator. Table 6.1 lists only a few of the available functions.
Table6.1A few of the functions from the math module math Module sqrt
Computes the square root of a number: sqrt(x) =√x exp Computes e
raised a power: exp(x) = ex log Computes the natural logarithm of a
number: log(x) = logex = lnx log10 Computes the common logarithm of
a number: log(x) = log10x cos Computes the cosine of a value specified
in radians: cos(x) = cosx; other trigonometric functions include sine,
tangent, arc cosine, arc sine, arc tangent, hyperbolic cosine, hyperbolic
sine, and hyperbolic tangent pow Raises one number to a power of
another: pow(x,y) = xy degrees Converts a value in radians to degrees:
degrees(x) = π 180x radians Converts a value in degrees to radians:
radians(x) = 180 π x fabs Computes the absolute value of a number:
fabs(x) =|x|
The math module also defines the values pi (π) and e (e). The following
interactive sequence reveals the math module’s full directory of
components:

>>> import math


>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod',
'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan',

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 10


'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi',
'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] >>>
Most of the names in the directory represent functions.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 11


Need of Functions:
1. Functions are very important part of programming language.
2. They help program to be modular. Means they help in writing small
parts of a program which are meaningful.
3. These small parts (modules) can be used again and again at different
places in a program.
Example :
1. Max( ) is a function to find max element from given list.
2. It can be used again and again.
3. Print( ) is a most commonly used function.

Function Basics
There are two aspects to every Python function:

• Function definition. The definition of a function contains the code that determines the
function’s behavior.

• Function invocation. A function is used within a program via a function invocation. In


Chapter 6, we invoked standard functions that we did not have to define ourselves.

Every function has exactly one definition but may have many invocations. An ordinary function
definition consists of four parts:

• def—The def keyword introduces a function definition.

• Name—The name is an identifier (see Section 2.3). As with variable names, the name chosen
for a functionshouldaccuratelyportrayitsintendedpurposeordescribeitsfunctionality.
(Pythonprovides forspecializedanonymousfunctionscalled lambda expressions, butwedefertheir
introduction until Section 8.7.)

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 12


• Parameters—every function definition specifies the parameters that it accepts from callers.
The parameters appear in a parenthesized comma-separated list. The list of parameters is empty
if the function requires no information from code that calls the function. A colon follows the
parameter list.

• Body—every function definition has a block of indented statements that constitute the
function’s body. The body contains the code to execute when callers invoke the function. The
code within the body is responsible for producing the result, if any, to return to the caller.

File3 shows the general form of a function definition. A function usually accepts some values
from its caller and returns a result back to its caller. (doublenumber.py) provides a very simple
function definition to illustrate the process.

File3: doublenumber.py

def name (parameter list):


block
Example:

def double(n):

return 2 * n # Return twice the given number

# Call the function with the value 3 and print its result

x = double(3)

print(x)

Defining functions:
1. When new function is to be used we need to first define it.
2. Local variables or objects cannot be accessed outside a function.
3. Note : Function name cannot contain spaces or special characters
except underscore (–).
Syntax :

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 13


def<space><function_name>(<parameters>):
<tab> ……
<tab> ……
<tab> return <variables to be returned>

For example:
Write a program to add two numbers using a function.
#Simple add function
def add(a,b):
c=a+b
return c
c=add(90,78)
print(‘Addition is’,c)

Example:
def count_to_n(n):
for i in range(1, n + 1):
print(i, end=' ')
print()

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 14


for i in range(1, 10):
count_to_n(i)
output:
1
12
123
1234
12345
123456
1234567
12345678
123456789

Call to a function:
1.A function can be called from any place in python script.
2.Place or line of call of function should be after place or line of
declaration of function.
Example:
• In following code, add function is called on line 6.
• Add() function definition start on line 2 and ends on line 4.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 15


• Then add() is called on line 6.

Program:

Example:
# Compute the greastest common factor of two integers

# provided by the user

def gcd(num1, num2):

# Determine the smaller of num1 and num2

min = num1 if num1 < num2 else num2

# 1 definitely is a common factor to all ints

largest_factor = 1

for i in range(1, min + 1):

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 16


if num1 % i == 0 and num2 % i == 0:

largest_factor = i # Found larger factor

return largest_factor

Variable Scope and Lifetime:


• In functions, there are two kinds of variables, local and global.
Local Variables / Objects :
1. Variables or objects which are used only within given function are
local variables or local objects.
2. Local objects include parameters and any variable / object which is
created in a given function.
Example:
• In following code, mult() function has two local variables.
• Local variable a and local variable b.
Program:

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 17


Global variables / objects:
1. Objects which can be accessed throughout the script/program are global variables or objects.

2. Global variables or objects are created in python script outside any function.

3. Global objects are available after “global” keyword defined in the script.

1. Reading Global variable value

Example :

• In following example global variable is accessed for printing / reading purpose.

• No modification to global variable is done here.

Program:

• #No modification in global variable id made

• def add_gv(a,b):

• c=a+b+gv

• print("in function value of gv is =",gv)

• print("The addition is :",c)

• gv=100

• print("The initial value of gv =", gv)

• add_gv(10,20)

• print("After function value of gv =",gv)

Modification of Global Variable Value

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 18


• ‘global’ keyword is used to modify a global variable inside a function.

Example :

• In following example “global” keyword is used inside the function.

• Now global variable can be modified within the function.

• Modifications made in the function (after using “global”) will stay after the function as
well.

Program:
#Modification in global variable is made

def add_gv(a,b):

global gv

gv=150

print(gv)

c=a+b+gv

return c

gv=100

print(gv)

x=add_gv(10,20)

print(x)

print(gv)

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 19


Arguments to a Function:
1. A function may accept arguments or it may not accept any arguments or parameters.

2. Arguments or Parameters to a function are treated as local variable for that function.

3. While defining the function, number of parameters has to be specified as sequence of


variables.

Types of Arguments:

There are different types of arguments :

1. Positional Arguments

2. Default Arguments

3. Unlimited-Positional Arguments

4. Keyword Arguments

Positional Arguments :

1. These arguments are passed to function based on their position.

2. Any normal arguments are positional arguments.

3. Example. In following example add functional takes two positional arguments a and
b.

4. When function is called add(90,78) then arguments are assigned by their position.

5. First position is of a so value 90 will be assigned to variable a.

6. Second position is of b so value 78 will be assigned to variable b.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 20


Example of Positional Arguments:

Default Arguments:
• One of the argument to a function may have its default value.

• For example laptop has default built-in speakers. So if no speaker is connected it will
play default speaker.

• Similarly in function argument, a default value can be assigned to an argument.

• Now if value for this argument is not passed by the user then function will consider that
arguments default value.

• Calling functions with very large number of arguments can be made easy by default
values

• For example, in following code mult_default function takes b argument as default.

• So, even if value of b is not passed, then default value of b will be 10.

• It is clear from the result that call mult_default(89) results in 890.

• Means a=89 and b = 10. So result= 89 * 10 = 890

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 21


1. Example of Default Arguments:

2. Example of Default Arguments:

#Default arguments

#A default argument is an argument that assumes a default value if a value is not provided

#in the function call for that argument.

#The following example gives an idea on default arguments,

#it prints default age if it is not passed

# Function definition is here

def default_Argument( name, age = 35 ):

"This prints a passed info into this function"

print "Name: ", name

print "Age ", age

return;

# Now you can call printinfo function

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 22


nm = input("Enter your Name =")

print(" Function with Both arguments =")

default_Argument( age=50, name=nm)

print(" Function with only one arguments =")

default_Argument( name=nm)

Unlimited Positional Arguments:


• Some functions can have some compulsory arguments and after that there can be any
number of arguments.

• Example is print().

• In print() function we can pass any number of strings separated by comma.

• And all strings will get printed.

• So, programmer can also create such a function taking unlimited arguments.

Keyword Arguments:
• These are another special category of arguments supported in python.

• Here arguments are passed in format “key=value”

• All key-word arguments can be taken in a special variable with **.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 23


Example of Keyword Arguments:

# Function definition is here

def printinfo( name, age ):

"This prints a passed info into this function"

print ("Name: ", name)

print ("Age ", age)

return;

# Now you can call printinfo function

printinfo( age=49, name="Manoj Kavedia" )

Example of Required Arguments:

def Required_argument_demo( n1,n2,n3 ):

"Finding Sum of Number"

result = n1+n2+n3

return result

#Another Example to Find Sum of Three Number

no1 = int(input("Enter Number 1 ="))

no2 = int(input("Enter Number 2 ="))

no3 = int(input("Enter Number 3 ="))

sum = Required_argument_demo( no1,no2,no3)

print("Sum =",sum)

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 24


#modify with three argument

Return Statement:
• It is statement to return from a function to its previous
function who called this function.
• After return control goes out of the current function.
• All local variables which were allocated memory in current
function will be destroyed.
• Return statement is optional in python.
• Any function can return multiple arguments.
Example:
• return #This returns none value
• return None #This returns none value
• return a, b #This returns two values
• return a #This returns single value
• These all are valid examples of a return statement.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 25


Example of Function:
#function defintion
#no1 , no2 are formal argument and will get value from num1 and
num2 ,and return result
def Addition (no1 , no2):
result = no1+ no2 #Local variable
return result

def getData ():


n1= int(input("Enter Number ="))
return n1

def displayData (n1,n2,n3):


print("Number 1 =",n1)
print("Number 2=",n2)
print("Sum =", n3)

#Driver code
num1 = getData()
num2 = getData()

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 26


sum =Addition(num1, num2) #num1 and num2 are actual argument,
Function is called
displayData(num1,num2,sum)

Anonymous Functions / Lambda Functions:


• Functions containing only single operation can be
converted into an anonymous function.
• ‘Lambda’ is the keyword used to create such anonymous
functions.
• Syntax:
Lambda < space > <parameter> : < operation >
• Example:
my_addition = lambda x, y : x + y
print(“addition is ”, my_addition(20, 30))
• Output = 50

Documentation String:
• In python, programmer can write a documentation for every
function.
• This documentation can be accessed by other functions.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 27


• Advantage of Document string:
• It is useful when we want to know about any function in
python.
• Programmer can simply print the document string of that
function and can know what that function does.

Documentation String Example:

def func( ):
"""Welcome to Coulomb"""
return
print(func.__doc__)

Good Programming Practices in Python :


Important Python Best Practices:
1. Create a Code Repository and implement version control.
2. Create readable Documetation
3. Follow Style Guidelines
4. Correct Broken Code immediately
5. Use the PyPI instead of doing it yourself.
6. The Zen of Python
7. Use the Right Data Structures

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 28


8. Write Readable Code.

1. Write a Python function to find the Max of three numbers.

def max_of_three( x, y, z ): #Function Definition


if(x > y and x > z):
return x #Return Statement
elif(y > z and y > x):
return y
else:
return z
a=int(input("Enter 1st number:"))
b=int(input("Enter 2nd number:"))
c=int(input("Enter 3rd number:"))
print("max number is:",max_of_three(a,b,c)) #Function Call

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 29


2. Write a Python function to sum and multiply all the numbers
in a list.

def sum(numbers):

total = 0

for x in numbers:

total += x

return total

L=[2,4,1,5,6]

print(sum(L))

3. Write a Python function to calculate the factorial of a number


(a nonnegative integer). The function accepts the number as an
argument.

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

n=int(input("Input a number to compute the factiorial : ")) print(factorial(n))

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 30


4. Write a Python function that takes a number as a parameter
and check the number is prime or not.
def test_prime(n):

if (n==1):

return False

elif (n==2):

return True;

else:

for x in range(2,n):

if(n % x==0):

return False

return True

a=int(input("Enter a number:"))

print(test_prime(a))

5. Write a Python program to print the even numbers from a


given list.

def is_even_num(l):

enum = []

for n in l:

if n % 2 == 0:

enum.append(n)

return enum

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 31


print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))

6. Write a Python program to print the fibonacci series:


0,1,1,2,3,5,8…..

def fibo(n):

if(n<2):

return n

return(fibo(n-1)+fibo(n-2))

nterms=int(input("Enter terms to display"))

print("fibonacci series:")

for i in range(nterms):

print(fibo(i))

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 32


Introduction to Modules:
 Modules make python programs re-usable.
 Every python code (.py) file can be treated as a module.
 A module can be accessed in other module using import statement.
 A single module can have multiple functions or classes.
 Each function or class can be accessed separately in import
statement.

Example to create your own module:


 Create a file named sample.py in your directory.
 Write function add() in it. (as we have seen in previous sections)
 Now create another file trial.py in same directory
 In trial.py write
 import sample.add
print(“addition is “, sample.add(10,20))
 Now run trial.py.
 Now the output will be 30.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 33


Introduction to Packages in Python:
Packages are namespaces which contain multiple packages
and modules themselves.
They are simply directories, but with a twist.
Each package in Python is a directory which must contain a
special file called __int__.py.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 34


Standard Libraries in Python:
1. Math (import math)
This is a package for providing various functionalities
regarding mathematical operations.
2. Random (import random)
This is the module which supports various functions for
generation of random numbers and setting seed of random
number generator.
3. Numpy (import numpy)
This is a package in python which supports various
numeric operations. It supports multidimensional arrays or
matrices and their calculations.
4. Scipy (import scipy)
This is the package for various scientific computations.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 35


Summary of Chapter:

A. Important points:
1. Need of function
2. Call function
3. Arguments in function
4. Local and Global variable
5. Documentation string
6. Good programming practices
7. Introduction to modules and packages
8. Standard library in python

B. Important Questions (University already Asked)

Q.No. Question Marks

1 What do you mean by function? Mention the advantages of using function in 5


program.

2 What is function? Explain code reuse. Explain with example Docstring. 6

3 Explain various ways of calling functions with suitable example. 5

4 How to Call a Function in Python? Explain it with proper syntax. 6

5 What is need for Functions? Explain. 6

6 What is function? Explain the need for writting a function in python. 6

7 Differentiate global variables and local variables. 6

8 Differentiate between local and global variable. Write a python program to 6


demonstrate difference between local and global variable.

9 What is global variable and local variable? Explain along with suitable example. 6

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 36


10 Explain the difference between required argument and Default Argument with 6
example

11 What are types of arguments and explain it with example of program 5

12 Explain keyword argument in python. Write a python program to demonstrate 6


keyword arguments.

13 Write Short note on 1. Required arguments 2. Default arguments with example. 6

14 Write a Program using function to swap two numbers.(Use required arguments). 6

15 List types of function arguments? Explain any one with example. 6

16 Define Function, Function Call and Function Parameters with a Python program(s) 6
that demonstrate mismatch conditions between function parameters and
arguments.

17 What are function parameters? Define a function that take two parameters and 6
does their addition and display it.

18 Explain documentation string with example. 5

19 What is documentation string in python? Expalin its advantages and rules to write 6
docstrig?

20 Explain importance of docstring in function. 6

21 What are docstrings? Explain with program. 6

22 What are Docstrings? What is difference between comments and Docstrings 6


Explain with example.

23 Explain Lambda function with example. 6

24 Write a program that uses lambda function to multiply two numbers. 6

25 Write a lambda function to calculate Temperature in Fareinheit.(accept 6


temperature in celcius as an argument)

26 What is lambda function? Write a program to find smaller of two numbers using lambda 6
function.

27 Write a Note on The 'return' Statement with uses and limitations. 6

28 Write a program that uses a lambda function to find the sum of 1st 10 natural 6
numbers?

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 37


29 Write a Program using function and return statement to check whether a number 6
is even or odd.

30 The return statement is optional. Justify this statement with the help of an 6
example.

31 What are good programming practices? 6

32 Write a short note on good programming practices? 6

33 Write a python program using function to compute addition, subtraction, 6


multiplication ,division and average of two user entered numbers.

34 Write a python program using function to compute area of triangle, square, circle 6
and rectangle.

35 Write python program using function to find greatest of three numbers by passing 6
numbers as argument.

36 Write a python program using function to find whether number is odd or even. 6

37 Write a Python function that takes a number as a parameter and check the 6
number is prime or not.

38 What is the result of the below lines of code?Here is the example code.def fast 6
(items= []): items.append (1) return itemsprint fast ()print fast ()

39 Write a Python function to find the Max of three numbers. 6

40 write a python program to reverse a number using function 5

41 write a python program for performing Addition and multiplication of two 5


numbers

42 write note on i) Packages ii) Modules in python 6

43 What are packeges in Python? Write down steps to create packages. 6

44 How will you create and use the module in python. 6

45 What are modules? How do you use them in your program 6

46 Write a program that prints absolute value, square root and cube of a number. 6

47 What is package explain in details 6

48 Explain difference between function and modules. 6

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 38


49 Write a program to initialize (invoke) a package. 6

50 Write a program to display the date and time using the time module. 6

51 Write Short note on - Standard library modules in Python. 6

52 What are the standard library modules in python? Explain. 5

53 Write a program to display Calendar of curent month,todays date and current 6


time.

Prof. S. B. Patil Mech. Dept, SIT Lonavala. 39

You might also like