0% found this document useful (0 votes)
6 views

python part 4

The document provides an overview of Python programming concepts, including function types, local and global variable scopes, function composition, recursion, and string manipulation. It explains different function definitions, how to declare local and global variables, and illustrates string operations and methods. Additionally, it covers the immutability of strings and various string functions with examples.

Uploaded by

mkhandsettask
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

python part 4

The document provides an overview of Python programming concepts, including function types, local and global variable scopes, function composition, recursion, and string manipulation. It explains different function definitions, how to declare local and global variables, and illustrates string operations and methods. Additionally, it covers the immutability of strings and various string functions with examples.

Uploaded by

mkhandsettask
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

PYTHON PROGRAMMING III YEAR/II SEM MRCET

#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

#Type1 : No parameters and no return type

def Fun1() :
print("function 1")
Fun1()

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

function 1

#Type 2: with param with out return type

def fun2(a) :
print(a)
fun2("hello")

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

Hello

#Type 3: without param with return type

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

#Type 4: with param with return type

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

python is better then c

Local and Global scope:

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
..............

# create a global variable

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

# create a local variable

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)

Then when we try to run it shows an error,

Traceback (most recent call last):


File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py", line
6, in <module>
60
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print(y)
NameError: name 'y' is not defined

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.

# use local and global variables in same code

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.

# use Global variable and Local variable with same name

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:

#create a function compose2

>>> def compose2(f, g):


return lambda x:f(g(x))

>>> def d(x):


return x*2

>>> def e(x):


return x+1

>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)


>>> a(5) # FunctionC(x)
12

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))

[('red', 'orange'), ('green', 'banana'), ('blue', 'cherry')]

Recursion:

Recursion is the process of defining something in terms of itself.

Python Recursive Function

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.

Following is an example of recursive function to find the factorial of an integer.

# Write a program to factorial using recursion


def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial",fact(0))
print("five factorial",fact(5))

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.

Slice out substrings, sub lists, sub Tuples using index.

Syntax:[Start: stop: steps]

 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−

str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character print

str * 2 # Prints string two times

print str + "TEST" # Prints concatenated string

Output:

Hello World!

llo

llo World!

Hello World!Hello 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:

>>> greeting='mrcet college!'


>>> greeting[0]='n'

TypeError: 'str' object does not support item assignment

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:

>>> greeting = 'Hello, world!'


>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'

Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator

66
PYTHON PROGRAMMING III YEAR/II SEM MRCET

String functions and methods:

There are many methods to operate on String.

S.no Method name Description


1. isalnum() Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false
otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains only numeric
characters and false otherwise.
6. isspace() Returns true if string contains only whitespace
characters and false otherwise.
7. istitle() Returns true if string is properly “titlecased” and
false otherwise.
8. isupper() Returns true if string has at least one cased character and all
cased characters are in uppercase
and false otherwise.
9. replace(old, new Replaces all occurrences of old in string with new
[, max]) or at most max occurrences if max given.
10. split() Splits string according to delimiter str (space if not
provided) and returns list of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string
in another string
13. swapcase() Converts lowercase letters in a string to uppercase
and viceversa
14. startswith(str, Determines if string or a substring of string (if starting index
beg=0,end=le beg and ending index end are given) starts with substring str;
n(string)) returns true if so and false
otherwise.

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

Syntax: import string

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
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Python String Module Classes

Python string module contains two classes – Formatter and Template.

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.

Syntax: from string import Formatter

Template

This class is used to create a string template for simpler string substitutions

Syntax: from string import Template

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.

 Element− Each item stored in an array is called an element.


 Index − Each location of an element in an array has a numerical index, which is used
to identify the element.

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}

Type Name Size Index 0

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

Following are the basic operations supported by an array.


 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the
array is declared as shown below.
from array import *
arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some
common typecodes used are:

Typecode Value
b Represents signed integer of size 1 byte/td>

B Represents unsigned integer of size 1 byte

74
PYTHON PROGRAMMING III YEAR/II SEM MRCET
c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes

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

Access the elements of an Array:

Accessing Array Element

We can access each element of an array using the index of the element.

from array import *


array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])

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

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

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

['mrcet', 'it', 'cse', 'autonomous']

>>> college.append("eee")

>>> college.append("ece")

>>> college

['mrcet', 'it', 'cse', 'autonomous', 'eee', 'ece']

>>> college.pop()

'ece'

>>> college

['mrcet', 'it', 'cse', 'autonomous', 'eee']

>>> college.pop(4)

'eee'

>>> college

['mrcet', 'it', 'cse', 'autonomous']

>>> college.remove("it")

>>> college

['mrcet', 'cse', 'autonomous']

77
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT – IV

LISTS, TUPLES, DICTIONARIES

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;

Lists, Tuples, Dictionaries:

List:

 It is a general purpose most widely used in data structures


 List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
 We can construct / create list in many ways.

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

You might also like