Python Notes Unit-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Programming for Problem Solving Using Python MVSREC

MATURI VENKATA SUBBA RAO (MVSR) ENGINEERING COLLEGE


NADERGUL, HYDERABAD-501510
(Sponsored by Matrusri Education Society, Estd.1980)
An Autonomous Institution
Approved by AICTE & Affiliated to Osmania University, Estd.1981
ISO 9001:2015 Certified Institution, Accredited by NAAC
website: www.mvsrec.edu.in

COURSE MATERIAL

For

PROGRAMMING FOR PROBLEM SOLVING USING


PYTHON

UNIT-2

Subject Code: U21ESN03CS


Class: B.E- First Year, Sem-2

B.E- First Year, Sem-2 Page: 1


Programming for Problem Solving Using Python MVSREC

UNIT-II

TOPICS COVERED
1. Overview of Functions
2. Built-in functions
3. User defined functions
4. Types of user-defined functions
5. Calling and called functions
6. Function returning multiple values
7. Default arguments in Function
8. Variable length arguments in function (*args)
9. Keyword arguments (kwargs)
10. Variable -length keyword arguments (**kwargs)
11. Scope and lifetime of variables
a. Local and global variables
b. “global” keyword
12. Lambda function
13. Nested functions
14. Recursive function
15. Difference between recursion and iteration
16. Example recursive programs (gcd,factorial ,fibonacci series)
17. Overview of modules
18. Built -in modules
a. math
b. os
c. statistics
d. random
19. Creating and Importing User-Defined Modules

B.E- First Year, Sem-2 Page: 2


Programming for Problem Solving Using Python MVSREC

OVERVIEW OF FUNCTIONS
A function is a block of statements that performs a specific task.
The given problem is divided into pieces of sub problems and each sub problem is solved
independently. Finally the solution from each sub sub problem is collected and integrated
to the main problem.
This process is called the divide and conquer approach.
Functions can communicate with each other and also further decompose a problem into
other sub problems which perform a top-down approach(see figure-2).

Use of functions:
1. Functions simplify the process of program development by dividing a given
problem into subsections.Each subsection can be written and tested separately.
2. Coding and debugging individual functions is easier than coding and debugging
the entire big problem.
3. Code reusability is the main important usage of functions. Set of instructions can
be written in a function block and that functions can be called many times
whenever required.
4. Modularity is another important advantage of using functions. For example, if n
instructions to be executed in a program and those n instructions may appear
abruptly many times anywhere in the program, then instead of writing them again
for many times,those n instructions are written in a block of code, such that
whenever is needed program calls that function to execute those instructions.
Observe the figure-3.
5. Programmers can use the functions written by other programmers in their code
without rewriting them.

B.E- First Year, Sem-2 Page: 3


Programming for Problem Solving Using Python MVSREC

BUILT- IN FUNCTIONS
Python supports many built-in (predefined) functions. These functions are already
defined and come with the python software during its installation. Programmers can directly use
them by importing the required functions into their current programs.
Built-in functions reduce the burden on the programmer for rewriting the code again.
As python has many built-in functions, describing each function is out of scope. Few important
functions are listed and described here.

Function name Description Example

len() This method finds the length of a string, a=[1,2,3,4,5]


list,set,tuple and dictionary. print(len(a))

id() This method prints address of an object a=10; print(id(a))

chr() This method returns the character print(chr(65) #prints A


associated with the given ASCII value.

ord() This method returns the ASCII value of a print(ord(‘A’)) #prints 65


given character

type() This method is used to specify the data print(type(25))


type of a given variable or a value. #output: <class ‘int’>

hex() This function is used to return the print(hex(15))


hexadecimal value of a given number. #output: 0xf

B.E- First Year, Sem-2 Page: 4


Programming for Problem Solving Using Python MVSREC

oct() This function is used to return the octal print(oct(10))


value of a given number. #output: 0o12

bin() This function is used to return the binary print(bin(12))


value of a given number. #output: 0b1100

max(), min() These functions return the maximum and print(max([10,20,30,40,50]))


minimum values among the list of print(min([10,20,30,40,50]))
numbers. #output: 50
10

pow(a,b) Returns a power b print(pow(2,3))


#output: 8

sum() Returns sum of list of numbers print(sum([1,2,3,4,5]))


#output: 15

USER-DEFINED FUNCTIONS
Python allows the programmers to write and define their own functions other than built-
in functions. They are called user-defined functions or custom functions.
To create and use the user-defined functions, two properties must be used.
I. function definition: It provides the body of the function where the logic is written for
the function. To define a function, the keyword ‘del’ is used. Below is the syntax.

Notice that, in python ‘Indentation’ will be the begin and end of the function definition.No curly
braces must be used for representing blocks.
There are some rules to be followed for defining functions:
→ function name should not begin with a digit or special characters
→ function name should not be a keyword or reserved word
→ function name should not contain spaces
→ function body should follow an indentation with the same level for all
instructions.
→ a function may or may not take arguments as input. It depends on the logic of
the function. In above syntax,arg1,arg2,...argN are formal arguments to store inputs of function.
II. function call: Once function is defined and ready, by default it won't be executed like
regular statements. It must be called by another statement in the program to transfer the control
and execute the function definition. Function call uses the following syntax.

B.E- First Year, Sem-2 Page: 5


Programming for Problem Solving Using Python MVSREC

functionName(value1,value2,...valueN)
Here, value1,value2,...valueN are actual arguments or data to be given for function
definition to further compute and process the result.
Note: A function must be defined only once but once it is defined, it can be called many times in
the program (Reusability).

Example Output

Inside test function


Test function executed

TYPES OF USER-DEFINED FUNCTIONS


Based on the way of passing inputs and fetching results from function they are categorized into
four types:
i) function with no arguments and no return value
ii) function with arguments and no return value
iii) function with no arguments and with return value
iv) function with arguments and with return value
i) function with no arguments and no return value:
This type of function doesn’t accept any arguments as parameters and doesn’t return any
output as result. It just executes the function with given instructions in its definition body.

Syntax Example Output

#function definition Inside test function


def functionName(): Test function executed
#body of function

#function call
functionName()

ii) function with arguments and no return value:


This type of function will accept any number of arguments as parameters and doesn’t return any
output as result. It takes the arguments as inputs to the function and executes with given
instructions in its definition body. Arguments can be of different data types. The number of

B.E- First Year, Sem-2 Page: 6


Programming for Problem Solving Using Python MVSREC

values and type of values should match in function call and function definition, otherwise leads
to error.

Syntax Example Output

#function definition #function definition Function


def functionName(arg1,arg2,..argN): def test(x,y,z): with
#body of function print("function with arguments") arguments
r=x+y+z x+y+z=6
#function call print("x+y+z=",r)
functionName(value1,value2,...valueN)
#function call
test(1,2,3)

iii) function with no arguments and with return value:


This type of function will not accept any arguments, but they return the result as output. The
function computes a specific logic and it returns a result to the calling function. The calling
function stores the result in another variable or prints the result using print() function.The
keyword return is used to fetch the result from the function. It can return any data type value.
Syntax Example Output

#function definition #function definition Function


def functionName(): def test(): returning
#body of function print("function returning value") value
return value x=5;y=6 Result=11
return x+y
#function call
resultVar=functionName() #function call
r=test()
print(‘Result=’,r)

iv) function with arguments and with return value:


This type of function will accept the arguments and also return a value. That’s why it is called a
bidirectional function. The number of arguments and type of arguments should match with the
actual parameters passed in the function call. The keyword return is used to return a value.
Syntax Example Output

B.E- First Year, Sem-2 Page: 7


Programming for Problem Solving Using Python MVSREC

#function definition #function definition function with


def functionName(arg1,arg2,...argN): def test(x,y,z): arguments
#body of function print("function with arguments and and returning
return value returning value") value
return x+y+z Result=6
#function call
resultVar=functionName(val1,val2,.. #function call
valN) r=test(1,2,3)
print(‘Result=’,r)

CALLING AND CALLED FUNCTIONS


Calling Function: A function which calls another function within a program is said to be calling
function.
Called function: A function which was called by another function within a program is said to be
a called function.
Calling and Called functions may be either user-defined or built-in functions.
For a given program, there will be a lot of calls between functions.
Consider the following figure:

In the above figure, print() is a function which is calling another function test(). We say it as
function invocation. test() is the called function.
The control transfers from print() function to the definition of test() and executes the test
definition. The test() function produces the result 10 by returning it. ‘Return 10’ makes the
control return back to the print function and prints output as 10.
Consider the following figure:

B.E- First Year, Sem-2 Page: 8


Programming for Problem Solving Using Python MVSREC

In the above figure, the main program is invoking func1(), func1() is invoking func2() and
func2() is invoking func3(). func3() after its execution it returns its control back to func2().
func2() after its execution it returns its control to func1(). func1() after its execution, returns its
control to the main program and the main program completes its pending execution.
→ main program is a calling function to func1(). func1() will be a function to the main program.
→ Similarly, func1() is a calling function to func2() and func2() will be a called function to
func1().
→ func2() is a calling function to func3() and func3() will be a called function to func2().

Example Output

B.E- First Year, Sem-2 Page: 9


Programming for Problem Solving Using Python MVSREC

FUNCTION RETURNING MULTIPLE VALUES


In python, we can define a function that could return many values at a time.
When a function is called, all these returned values will be stored in a tuple and return that tuple
to the calling function.
Below is the syntax and example:

Syntax:

Example-1 Output

B.E- First Year, Sem-2 Page: 10


Programming for Problem Solving Using Python MVSREC

Example-2

Output

DEFAULT ARGUMENTS IN FUNCTION


In python, we can use default arguments during function definition.
In function calls, if values are not passed , then default arguments are used for the function
definition for computing the results.
So ,we can execute a function with passing values and without passing values during function
call.
Default arguments are used only if values are not passed during function call.

Syntax:

Example Output

B.E- First Year, Sem-2 Page: 11


Programming for Problem Solving Using Python MVSREC

In the above example, the test() function is called 3 times differently. In the first call, test() takes
3 values i.e 4, 5 and 6.These values will be replaced by x,y and z respectively. So, x=4,y=5 and
z=6.
In the second call, test() takes 2 values i.e 2 and 3. These values are replaced by only x and y. I.e
x=2 and y=3. As the third value is not given, z will have a default value. i.e z=3.
In the third call, test() takes no values. So default values will be used for x,y and z. ie. x=1,y=2
and z=3.
Note: The number of values must be less than or equal to the number of arguments declared in
function definition.

VARIABLE LENGTH ARGUMENTS IN FUNCTION

In python, if we do not know how many arguments to be passed into the function definition, then
we add a ‘*’ before the argument name in the function definition.
This way the function will receive a tuple of arguments, and can access the values accordingly.
Each value will be accessed from tuple argument through index.
Below is the syntax and example.

Syntax:

B.E- First Year, Sem-2 Page: 12


Programming for Problem Solving Using Python MVSREC

Example-1 Output

Example-2 giving arguments along with Output


variable arguments

→ In example2, we have given variable arguments (*args) and also two normal arguments (x,y).
So the function call expects at least two values which will be assigned for x,y otherwise a
TypeError will be raised for missing values for x,y.
→ If more than two values are given , the first two values will be assigned to x,y and the rest of
the values will be assigned for ‘args’.
→ Always, the normal arguments should be assigned first and variable arguments should be
declared at last in function definition.
i.e def(x,y,*args): is valid but def(*args,x,y): and def(x,*args,y): are not valid.

KEYWORD ARGUMENTS (kwargs)


In python, for a function definition, we can send arguments with the form of key = value syntax
during function call. The key name should exist in the arguments of function definition.
This way the order of the arguments does not matter.
The number of key=value arguments should match the number of arguments in the function
definition.

B.E- First Year, Sem-2 Page: 13


Programming for Problem Solving Using Python MVSREC

Name of the key should match with any of the arguments in function definition.

Syntax:

Example: Observe key=value given in 3 orders Output

Now you see that, irrespective of the order we follow, values of x,y and z are assigned to them
accordingly. During function call, we are specifying the interpreter which value should go to the
corresponding argument using the ‘key’. See the below figure.

VARIABLE -LENGTH KEYWORD ARGUMENTS (**kwargs)


In python, we can use keyword arguments (kwargs), but if we do not know how many keyword
arguments that will be passed into the function definition, then we can add two asterisk ‘**’
symbols before the argument name in the function definition.
The function will receive a dictionary of arguments, and can access the items accordingly.

B.E- First Year, Sem-2 Page: 14


Programming for Problem Solving Using Python MVSREC

Each argument value can be accessed using its corresponding key. We can do a function call
with many keyword arguments or a function call with no arguments at all.
Below is the syntax and example.

Syntax:

Example-1
(defining
variable-
keyword
arguments
and calling
function
with and
without
keyword
arguments)

Output

B.E- First Year, Sem-2 Page: 15


Programming for Problem Solving Using Python MVSREC

Example-2
(Accessing
each
keyword
argument
using for
loop)

Output

SCOPE AND LIFETIME OF VARIABLES


Scope of a variable: It describes the accessibility of a variable within a program.
Not all variables are accessible in the entire program. Some variables are accessible within a
block or a function and some are accessible anywhere in the program.
Lifetime of a variable: It describes the validity of a variable within a program. That is, how
long a variable can stay and give its service to the program. It depends on the creation and
deletion of that variable in the program. Few variables are automatically deleted but few can be
deleted explicitly.
Scope and lifetime of variables depends on the point from which they have created and accessed.

B.E- First Year, Sem-2 Page: 16


Programming for Problem Solving Using Python MVSREC

Depending on the above scenario, variables can be categorized into four types.
a. local variables
b. Global variables
c. Instance variables
d. Class variables
First two variables are discussed here and the rest of two variables are discussed in unit-3 (under
OOPs concepts).
a. Local variables:
Variables which are defined within a function are called local variables.
These variables can be accessed only within a function and can not be accessed outside
the function.
These variables are initialized only when a function is called.
These variables are valid till the end of the function execution. Once a function completes
its execution, local variables are deleted automatically and no longer valid in the
program.
If a function is called N times, then local variables are also created and deleted N times.
Local variables have a very short lifetime in the program.
Formal arguments are also treated as local variables.

Example: Output

B.E- First Year, Sem-2 Page: 17


Programming for Problem Solving Using Python MVSREC

Example-2: Error raised if local Output


variable is trying to access outside
function

b. Global variables:
Variables which are defined within a program are called global variables.
These variables can be accessed anywhere in the program, i.e inside a function and
outside a function.
Changing the value of a global variable by a function will reflect that change in other
functions and the entire program.
These variables are created and deleted only once when the program begins and exits.
These variables are valid till the end of the program execution.
Global variables have more lifetime than local variables.

Example Output

‘global’ keyword : The purpose of ‘global’ keyword is :


I. to allow a function to modify the value of global variable

B.E- First Year, Sem-2 Page: 18


Programming for Problem Solving Using Python MVSREC

II. to promote the local variable to global variable.


→ By default, a function cannot modify the value of global variables. To allow the
function to modify, the global variable should be declared as ‘global’ before the
modifying statement inside the function.
→ Below example shows two outputs: with and without using global keyword.

Example-1: function trying to modify Output


global variable directly

Example-2: function trying to modify Output


global variable using ‘global’ keyword

→ A local variable can be promoted to a global variable such that its scope and lifetime
will be increased. It can be accessed by all functions and anywhere in the program.

B.E- First Year, Sem-2 Page: 19


Programming for Problem Solving Using Python MVSREC

→ The local variable must be declared as ‘global’ for promoting the local variable to
global variable.

Example Output

Note-1: Both local variables and global variables cannot be used in a function at a time.
Note-2: If the names of both local variables and global variables are the same, then
priority will be given to local variables inside a function.

Write a python program to create,access, modify and delete the global variable.
program

B.E- First Year, Sem-2 Page: 20


Programming for Problem Solving Using Python MVSREC

Output

LAMBDA FUNCTION
● Lambda Function, also referred to as ‘Anonymous function’ is the same as a regular
python function but can be defined without a name.
● While normal functions are defined using the def keyword, anonymous functions are
defined using the ‘lambda’ keyword.
● Lambda functions are restricted to have only a single line of expression. They can take in
multiple arguments or no arguments as in regular functions.
● There is not much difference between regular function and lambda function except that
lambda functions should have only one expression for instant execution whereas regular
functions can have multiple expressions/instructions.
● Syntax and example of lambda function.

Syntax:

Example-1: using lambda with Output


reference variable, add
Add=11

B.E- First Year, Sem-2 Page: 21


Programming for Problem Solving Using Python MVSREC

Example-2: using lambda without Output


reference variable
4

● Lambda functions can be called directly. See Example-2 above.


● Lambda functions can be nested inside a regular function
Example: incrementing value of a by 1 Output
through lambda inside test

● Lambda functions can be passed as an argument to a function

Example: printing square and cube of a Output


value through lambda function

B.E- First Year, Sem-2 Page: 22


Programming for Problem Solving Using Python MVSREC

a= 5
square= 25
cube= 125

NESTED FUNCTIONS
A function defined inside another function is said to be a nested function(also referred as inner
function).
→ Inner function can access local variables of outer function but outer function cannot access
inner function local variables.
→ If Inner function has global variables , the outer function also can access it.
→ Inner function cannot be called directly. First main program invokes outer function which in
turn invokes inner function.
Syntax

Example Output

B.E- First Year, Sem-2 Page: 23


Programming for Problem Solving Using Python MVSREC

RECURSIVE FUNCTION
Recursion: The process of calling a function by itself until the final call doesn’t require the self
recursive call is called Recursion.
→ Functions which call themselves are called Recursive functions.
→ A recursive function requires two cases:
i) base condition: usually it is an if-else condition that allows or stops the further
recursive call.
ii) recursive case: the given problem is handed over to a recursive function which further
continues self recursive calls to obtain solution. Once a solution is obtained, it will be returned to
the main program by integrating the solutions from the parts of the recursive functions.
→ During recursion, depth of function calling increases.
→ Python allows a function to call itself upto a maximum limit of depth(1024 calls), after that
raises RuntimeError for further recursive call saying that maximum recursion depth limit
exceeded.
→ Recursion is mainly used to solve a given problem in a divide and conquer approach.

B.E- First Year, Sem-2 Page: 24


Programming for Problem Solving Using Python MVSREC

→ Divide and conquer: A big problem is divided into sub-problem , the sub-problem is again
divided into another sub-problem and this
process continues till no further division is
required. After dividing the problem, a solution

from the last divided sub-problem is achieved and


submitted to the previous sub-problem and this
process continues to the top of the main problem.
Finally a solution is achieved.
→ Recursion follows a top-down approach.

Example Output

Flow of the above example

B.E- First Year, Sem-2 Page: 25


Programming for Problem Solving Using Python MVSREC

RECURSION VS ITERATION

Recursion Iteration

Follows top-down approach Follows bottom-up approach

Maintains a runtime stack memory to run all Uses runtime stack memory but not too much
recursive calls and store the data from the first like a recursive function. Deletes the data for
recursive call every iteration and loads data of current
iteration into stack.

Does not allow for further recursion if depth No maximum limit for iteration unless the
of recursion increases to maximum limit system signals by itself to stop further
iteration

Overload on the runtime stack to store all the No overload on runtime stack as it will clear
recursive data for the final solution which is the data for every iteration
not a very efficient way.

Difficult to find bugs if global variables are Easy than recursion to find bugs incase of
used global variables are used

B.E- First Year, Sem-2 Page: 26


Programming for Problem Solving Using Python MVSREC

Consumes more memory and time Less consumption of memory and time than
recursive functions

EXAMPLE RECURSIVE PROGRAMS (GCD,FACTORIAL ,FIBONACCI SERIES)


Program to find GCD of two numbers using recursion

Program Output

B.E- First Year, Sem-2 Page: 27


Programming for Problem Solving Using Python MVSREC

Program to find the factorial of a given number using recursion

Program Output

Program to find fibonacci series upto n terms using recursion

Program Output

OVERVIEW OF MODULES
What is a module? A module is a python program that contains the collection of functions,
global variables, classes and objects.
It is used to utilize the existing variables, functions, classes and objects in the current program
which are already defined in another python program.
Main idea of the module is to provide the Reusability of program codes like functions, variables,
classes and objects.
Also used to avoid the naming conflicts between the identifiers used in multiple programs.

B.E- First Year, Sem-2 Page: 28


Programming for Problem Solving Using Python MVSREC

Using a module, a current program can access many outside python programs and get their code
benefits.
Python supports many built-in modules. Lots of built-in modules already exist at the time of
python software installation.
Sometimes, there is a need to use external python libraries. Then they should be installed first
and then can be used in the program.
For example, modules like ‘numpy’,’pandas’
, ‘matplotlib’ modules could not exist by
default in python software.They must be
installed separately.
→ To use a module in the current program,
first the module should be imported into the
current program.
→ The keyword ‘import’ is used to import a
module into the program. Below is the syntax
for importing a module in different ways.
Syntax-1:
import moduleName
Import the specified module with the given
name
Example: import math
Syntax-2:
import module1,module2,...moduleN
Imports multiple modules
Example: import math,os,random
Syntax-3:
import moduleName as aliasName
Imports the specified module and can be accessed every time the module with the given alias
name.
Example: import random as rd
‘rd’ is the alias name which is used to access any data from a random module.
For example, rd.randint() can be called instead of random.randint()
Syntax-4:
from moduleName import *
Imports all variables,classes and functions from specified module. Equivalent to syntax-1.
Syntax-5:
from moduleName import object1,object2…,objectN
Imports only specified objects(variables,functions,classes) from the specified module.
Example:
from math import pi,sqrt,pow

B.E- First Year, Sem-2 Page: 29


Programming for Problem Solving Using Python MVSREC

Above example will import only 3 objects: pi variable, sqrt,pow functions

Note: ‘import’ statement can be used anywhere in the program but it is recommended to import
modules at the beginning of the program.

Modules are of two types:


I. Built-in modules
II. User-defined modules.

BUILT-IN MODULES
Modules which are already defined and readily available to use in the program are called built-in
modules or pre-defined modules.
→ some built-in modules are already available during python installation but some modules are
to be installed separately.
→ four built-in modules are discussed below which already come with python installation.
a. math module :
This is a built-in module to perform mathematical tasks such as trigonometric
functions, operations on given numbers, representation functions, logarithmic functions,
etc.
→ To import math module, use the following syntax at the beginning of the program.
Syntax:
import math
It has many built-in functions and also built-in constants. Few of them are discussed
below.
Built-in constants:

Constant name Description Example

math.pi Returns the pi value as import math


3.141592653589793 print(math.pi)

math.e Returns the Euler’s value import math


as 2.718281828459045 print(math.e)

Built-in functions:

Built-in function Description Example

math.ceil() Rounds a number up to the nearest import math


float number print(math.ceil(6.78))
#output: 7

B.E- First Year, Sem-2 Page: 30


Programming for Problem Solving Using Python MVSREC

math.comb(n,r) Finds the value of ncr. i.e import math


n!/r!*(n-r!) print(math.comb(4,2))
#output: 6

math.copysign(a,b) Returns a number consisting of the import math


value of the first parameter and the print(math.copysign(4,-2))
sign of the second parameter #output: -4

math.cos(x) Returns the cosine of number x import math


print(math.cos(30))
#output: 0.15425144988

math.degrees(x) Converts an angle from radians to import math


degrees print(math.degrees(30))
#output: 5156.6201

math.dist(p,q) Returns the Euclidean distance import math


between two points (p and q), p=[5,2] ; q=[8,4]
where p and q are the coordinates print(math.dist(p,q))
of that point #output: 3.6055512

math.factorial(x) Returns the factorial of a number x import math


print(math.factorial(5))
#output: 120

math.floor(x) Rounds a number down to the import math


nearest integer print(math.ceil(6.78))
#output: 6

math.gcd(x,y) Returns the gcd of x,y import math


print(math.gcd(12,18))
#output: 6

math.perm(n,r) Returns the value of n!/r! import math


print(math.perm(5,2))
#output: 20

math.pow(x,y) Returns x power y import math


print(math.pow(2,3))
#output: 8

math.remainder(x,y) Returns the value of x%y import math


print(math.remainder(5,2))
#output: 1.0

math.sqrt(x) Returns the square root of x import math


print(math.sqrt(25))
#output: 5.0

B.E- First Year, Sem-2 Page: 31


Programming for Problem Solving Using Python MVSREC

math.sin(x) Returns the sine of a number x import math


print(math.sin(90))
#output: 0.89399

math.tan(x) Returns the tangent of a number x import math


print(math.tan(45))
#output: 1.6197

b. os module:
It is a built-in module that provides variables and functions for interacting with the file
system of the operating system.
→ Used to create,read and delete directories in the os.
→ Also reads the information about users and running processes of the os.
To import os module we use the following syntax:
import os

Below are the built-in functions of statistics module

Built-in function Description Example

name Returns the name of the os. For


windows,it is nt and for linux it is
posix.

getcwd() Returns the current working


directory of the running program

getlogin() Returns the current username of


the computer who logged in

getpid() Returns process id of a program


running in the os. It is a unique
integer.

listdir() Returns list of files and sub-


directories from the current
directory

B.E- First Year, Sem-2 Page: 32


Programming for Problem Solving Using Python MVSREC

mkdir(path/name) Create a directory with the given


name at given path

test folder created

rmdir(path/name) Removes an existing directory


with the given name at given path

test folder removed

makedirs(d1/d2/..dn) Create multiple subdirectories. /


indicates sub directory in the
leftmost directory

test3 inside test2 inside test1


directories created

removedirs(d1/d2/..dn) Removes multiple subdirectories. /


indicates sub directory in the
test3 inside test2 inside test1
leftmost directory
directories will be removed

system(command) Opens an application suitable for import os


the given command. For example, os.system(‘calc’)
to open a calculator and paint ,the os.system(‘mspaint’)
commands are ‘calc’ and Opens calculator and paint
‘mspaint’ in windows. applications

os.path.getsize(file) Returns the size of the file in bytes

os.path.exists(path/na check whether a file exists or not


me) by passing the name of the file as
a parameter.

os.walk(path) It displays the list of paths, directory names and file names in
the current directory given as a parameter.
Syntax:
for path,dname,fname in os.walk(os.getcwd()):
#print path,directories,files

B.E- First Year, Sem-2 Page: 33


Programming for Problem Solving Using Python MVSREC

Example:

c. Statistics module:
This is a built-in module used to calculate mathematical statistics of numeric data.
To import statistics module we use the following syntax:
import statistics
OR
import statistics as st
OR
from statistics import *
OR
from statistics import object1,object2…objectN

Below are the built-in functions of statistics module

Built-in function Description Example

harmonic_mean(list) Calculates the harmonic mean


(central location) of the given
data

mean(list) Calculates the mean (average)


of the given data

B.E- First Year, Sem-2 Page: 34


Programming for Problem Solving Using Python MVSREC

median(list) Calculates the median (middle


value) of the given data

mode(list) Calculates the mode (repeated


value) of the given numeric or
nominal data

variance(list) Calculates the variance from a


sample of data

stdev(list) Calculates the standard


deviation from a sample of
data. (Square root of variance)

Procedure for finding harmonic Mean for given sample data:


Sample data=[1,2,3,4,5]
Step-1: find the reciprocal for each value of sample data.
1/1 => 1 ; ½=>0.5 ; ⅓ => 0.33 ; ¼ => 0.25 ; ⅕ =>0.2
Step-2: Find the sum of reciprocals got from step-1
sum=1+0.5+0.33+0.25+0.2 =>2.28
Step-3: Compute (total items) /sum
Total items in sample data is 5.
(5)/2.28 =>2.19
Procedure for finding variance for given sample data:
Sample data=[1,2,3,4,5]
Step-1: find the mean of sample data
mean=(1+2+3+4+5)/5 =>3
Step-2 : subtract each item of sample data with mean, and find its square
1-3 => -2 => (-2)**2 => 4
2-3 => -1 => (-1)**2 => 1
3-3 => 0 => (0)**2 =>0
4-3 => 1 => (1)**2 =>1
5-3 => 2 => (2)**2 =>4
Step-3 : Add the squares obtained in step-2
sum=(4+1+0+1+4) => 10
Step-4: compute sum/total items -1
Total items in sample data is 5.
So, variance= 10/4 =>2.5

B.E- First Year, Sem-2 Page: 35


Programming for Problem Solving Using Python MVSREC

d. Random module:
It is a predefined module used to generate random numbers and perform manipulations
on those numbers.
Syntax:
import random

It has some built-in functions and few of them are discussed below.

Built-in Description Example


function

randint(m,n) Generates a random number between


m and n-1

randrange(m,n) Generates a random number between


m and n

seed(x) Sets the number x for generating the


same random number in the program.
If x is changed then a new random
number will be generated. seed()
without parameters also generates
different random numbers. seed()
must be called before random number
generation.

choice(list) Generates a random number from a


given list of items. List may have
similar or dissimilar items.

shuffle(list) Shuffles the list of items and returns


the shuffled list. List may have similar
or dissimilar items.

B.E- First Year, Sem-2 Page: 36


Programming for Problem Solving Using Python MVSREC

sample(sequence returns a list with a randomly selection


,k) of a specified number of items from a
sequence(list,set,range). Will not affect
the Original list. K is the no. of items
randomly generated from sequence.

random() Returns a random float number between


0 and 1

getrandbits(bitsi Generates a random number that has


ze) specified bitsize. For example, If
bitsize=8, numbers whose memory will
not exceed more than 8 bits will be
generated.

CREATING AND IMPORTING USER-DEFINED MODULES


Python allows us to create and import our own modules.
Creating a module means creating and saving a python file with .py extension.
Once modules are created, they can be used many times anywhere in the program(s).
Use the below steps to create the module:
Step-1: create a python file with filename.py and save it in some location X
Step-2: Define all your necessary variables, functions,classes and objects in the
python file.
Now, use the below steps to import the module.
Step-1: Create a python file that runs your program.
Step-2: Save it with filename2.py. Ensure both files must be in the same location
X.
Step-3: import the module using below syntax
import userModuleName
Step-4: now you can call functions and variables from first file filename.py

Below is the syntax for creating a user-defined module.

B.E- First Year, Sem-2 Page: 37


Programming for Problem Solving Using Python MVSREC

File-1 saved as filename.py is imported into file-2 saved as filename2.py.


Filename2.py will import filename.py data and call necessary functions from it. It also
contains its own instructions to run.
Note-1: To access a variable or a function or object from a module, we use the dot
operator preceded by that variable/function/object.
moduleName.variable OR moduleName.function()
Below is the example of a user-defined module.

Creating a module importing a module into module2.py


module1.py

Output:

Note-2: We can import only specific variables/functions from a module using below
syntax.
from moduleName import object1,object2,...objectN
Above syntax does not need a dot operator for accessing imported
variables/functions.They can be accessed directly.

B.E- First Year, Sem-2 Page: 38


Programming for Problem Solving Using Python MVSREC

Example: Importing only display() and k from module1.py

Creating a module importing only k,display from module1


module1.py into module2.py

Output:

Note-3: Importing module using alias name. Below is the syntax.


import moduleName as aliasName
Now only alias name should be used along dot operator to access imported
variables/functions
Example: importing module1.py using alias name m1.

Creating a module importing module1 using alias name


module1.py into module2.py

B.E- First Year, Sem-2 Page: 39


Programming for Problem Solving Using Python MVSREC

Output:

Note-4: Avoiding naming conflicts between variables/functions in multiple


modules.
Assume that there are two modules m1 and m2 to be imported into m3. If m1 and m2
have variables and functions defined with the same name, then m3 gets ambiguity to
access specific variables/functions from a module.
This can be resolved using below syntax:
moduleName.variable OR modulename.functionName()

module1.py

module2.py

Main.py
(importing
above two
modules)

B.E- First Year, Sem-2 Page: 40


Programming for Problem Solving Using Python MVSREC

output

B.E- First Year, Sem-2 Page: 41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy