python part 4
python part 4
#function call
display()
print("i am in main")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
i am in main
vandemataram
i am in main
def Fun1() :
print("function 1")
Fun1()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
function 1
def fun2(a) :
print(a)
fun2("hello")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Hello
def fun3():
return "welcome to python"
print(fun3())
58
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
welcome to python
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Local Scope:
A variable which is defined inside a function is local to that function. It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the
function is executing
Global Scope:
A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file.
The variable defined inside a function can also be made global by using the global
statement.
def function_name(args):
.............
global x #declaring global variable inside a function
..............
59
PYTHON PROGRAMMING III YEAR/II SEM MRCET
x = "global"
def f():
print("x inside :", x)
f()
print("x outside:", x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
x inside : global
x outside: global
def f1():
y = "local"
print(y)
f1()
Output:
local
If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside f2() or local scope.
x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
globalglobal
local
In the above code, we declare x as a global and y as a local variable in the f3(). Then,
we use multiplication operator * to modify the global variable x and we print
both x and y.
After calling the f3(), the value of x becomes global global because we used the x *
2 to print two times global. After that, we print the value of local variable y i.e local.
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
61
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
local x: 10
global x: 5
Function Composition:
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
In the above program we tried to compose n functions with the main function created.
Example 2:
>>> colors=('red','green','blue')
>>> fruits=['orange','banana','cherry']
>>> zip(colors,fruits)
62
PYTHON PROGRAMMING III YEAR/II SEM MRCET
<zip object at 0x03DAC6C8>
>>> list(zip(colors,fruits))
Recursion:
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
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.
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rec.py
zero factorial 1
five factorial 120
----------------------
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
63
PYTHON PROGRAMMING III YEAR/II SEM MRCET
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rec.py
The factorial of 4 is 24
Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or
double quotes. Every string object is of the type ‘str’.
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('mrcet')
>>> a
'mrcet'
>>> a=str(mrcet)
>>> a[2]
'c'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
64
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Stop is last index of list
And for step default is 1
For example 1−
Output:
Hello World!
llo
llo World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
65
PYTHON PROGRAMMING III YEAR/II SEM MRCET
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
The reason for the error is that strings are immutable, which means we can’t change an
existing string. The best we can do is creating a new string that is a variation on the original:
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator
66
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Note:
All the string methods will be returning either true or false as the result
1. isalnum():
67
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Syntax:
String.isalnum()
Example:
>>> string="123alpha"
>>> string.isalnum() True
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Syntax:
String.isalpha()
Example:
>>> string="nikhil"
>>> string.isalpha()
True
3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
String.isdigit()
Example:
>>> string="123456789"
>>> string.isdigit()
True
4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise.
Syntax:
68
PYTHON PROGRAMMING III YEAR/II SEM MRCET
String.islower()
Example:
>>> string="nikhil"
>>> string.islower()
True
5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
Syntax:
String.isnumeric()
Example:
>>> string="123456789"
>>> string.isnumeric()
True
6. isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.
Syntax:
String.isspace()
Example:
>>> string=" "
>>> string.isspace()
True
7. istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise
Syntax:
String.istitle()
69
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example:
>>> string="Nikhil Is Learning"
>>> string.istitle()
True
8. isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.
Syntax:
String.isupper()
Example:
>>> string="HELLO"
>>> string.isupper()
True
9. replace()
replace() method replaces all occurrences of old in string with new or at most max
occurrences if max given.
Syntax:
String.replace()
Example:
>>> string="Nikhil Is Learning"
>>> string.replace('Nikhil','Neha')
'Neha Is Learning'
10.split()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
String.split()
Example:
>>> string="Nikhil Is Learning"
>>> string.split()
70
PYTHON PROGRAMMING III YEAR/II SEM MRCET
['Nikhil', 'Is', 'Learning']
11.count()
count() method counts the occurrence of a string in another string Syntax:
String.count()
Example:
>>> string='Nikhil Is Learning'
>>> string.count('i')
3
12.find()
Find() method is used for finding the index of the first occurrence of a string in another
string
Syntax:
String.find(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.find('k')
2
13.swapcase()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
String.find(„string‟)
Example:
>>> string="HELLO"
>>> string.swapcase()
'hello'
14.startswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
71
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Syntax:
String.startswith(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('N')
True
15.endswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with substring str; returns true if so and false otherwise.
Syntax:
String.endswith(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('g')
True
String module:
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants and classes
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
72
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print(string.hexdigits)
#print(string.whitespace)
print(string.punctuation)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl.py
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Formatter
It behaves exactly same as str.format() function. This class becomes useful if you want to
subclass it and define your own format string syntax.
Template
This class is used to create a string template for simpler string substitutions
Python arrays:
Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Array Representation
73
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Arrays can be declared in various ways in different languages. Below is an illustration.
Elements
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 70
Basic Operations
Typecode Value
b Represents signed integer of size 1 byte/td>
74
PYTHON PROGRAMMING III YEAR/II SEM MRCET
c Represents character of size 1 byte
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/arr.py
10
20
30
40
50
We can access each element of an array using the index of the element.
75
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py
10
30
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
76
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Example:
>>> college=["mrcet","it","cse"]
>>> college.append("autonomous")
>>> college
>>> college.append("eee")
>>> college.append("ece")
>>> college
>>> college.pop()
'ece'
>>> college
>>> college.pop(4)
'eee'
>>> college
>>> college.remove("it")
>>> college
77
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT – IV
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
comprehension; Dictionaries: operations and methods, comprehension;
List:
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
78