UNIT 03 MDM.p...........................

bhaktikundhare 0 views 135 slides Oct 13, 2025
Slide 1
Slide 1 of 135
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135

About This Presentation

Python 3 rd chapter


Slide Content

Statements, Expressions, Strings: String processing. Exception handling, Basic input/output, Handling files. UNIT III

2.1 : Operations on String (Sequence data types) 1. Indexing in strings 2. Slicing the strings 3. Repeating the strings 4. Concatenation of strings 5. Checking Membership 6. Comparing the strings 7. Removing spaces from the string 8. Formatting the strings 9. Changing case of a string 10. String testing methods 2 String Operations

2.1 : 1 Indexing in String (Sequence data types) Index represents the position number. It is written using square braces [ ]. By specifying index, we can refer to an individual elements. For example, str[0] represents 0 th , str[1] represents 1 st and so on. Thus str[i] represents i th element of string called as index. When we use negative indexing, it refers to elements in reverse order. 3

2.1 : 2 Slicing the strings (Sequence data types) —A slice represents a part or piece of a string. The slicing format is: stringname[start: stop: stepsize] If start and stop are not specified, then slicing done from 0 th to n-1 th element. Similarly if stepsize is not written, taken as 1. 4

2.1 : 2 Slicing the strings (Sequence data types) >>> st = ‘Core Python’ >>> st [0:9:1] # accept string from 0 th to 8 th elements in steps of 1 Core Pyth >>> st [0:9:2] Cr yh >>> st [ : : ] ???? str [2:4:1] re 5

2.1 : 2 Slicing the strings (Sequence data types) >>> st [ : :2] Cr yhn >>> st [ 2: : ] re Python >>> st [ : 4: ] Core >>> st [-4:-1] tho >>> st [-6: : ] ????? 6

2.1 : 2 Slicing the strings (Sequence data types) >>> st [-1:-4:-1] noh >>> st [-1: :-1] nohtyP eroC 7

2.1 : 3 Repeating the strings (Sequence data types) — The repetition operator is denoted by ‘ * ‘ and is useful to repeat the string several times. For example, st*n repeats string str n times. >>> str = ‘Core Python’ >>> print (str*3) Core PythonCore PythonCore Python 8

2.1 : 3 Repeating the strings (Sequence data types) — Similarly it is also possible to repeat a part of string obtained by slicing as: >>> s = str [5:7] >>> print (s*3) PyPyPy 9

2.1 : 4 Concatenation of strings(Sequence data types) — Concatenation i.e. joining of the two strings is denoted by ‘+’. — For numbers, is called as addition operator, while for string is called as concatenation operator. 10

2.1 : 4 Concatenation of strings(Sequence data types) For example, s1 = ‘Core’ s2 = ‘Python’ s3 = s1+ s2 print(s3) CorePython 11

2.1 : 4 Concatenation of strings(Sequence data types) For example, >>> s1 = ‘Core’ >>> s2 = “420” >>> s3 = s1+ s2 >>> print(s3) Core420 For example, >>> s1 = ‘Core’ >>> s2 = 420 >>> s3 = s1+ s2 >>> print(s3) ????? 12

2.1 : 5 Checking Membership (Sequence data types) — We can check if a string or character is a member of another string or not using in or not in operators. For example, a = "Core Python“ b = 'Python‘ c = "CSMSS“ d = b in a e = c not in a print(d) print(e) 13

2.1 : 5 Checking Membership (Sequence data types) For example, str = input(‘Enter main string: ’) sub = input(‘Enter sub string: ’) if sub in str: print(sub,‘ is found in main string’) else: print(sub+‘ is not found in main string’) 14

2.1 : 5 Checking Membership (Sequence data types) OUTPUT: Enter main string: This is Core Python Enter sub string: Core Core is found in main string 15

2.1 : 5 Checking Membership (Sequence data types) OUTPUT: Enter main string: This is Core Python Enter sub string: Core Core is found in main string 16

2.1 : 6 Comparing the strings (Sequence data types) — We can use relational operators i.e. ==, !=, <, <=, >, >= to compare two or more strings, which returns Boolean values. — Python interpreter compares the strings in English dictionary order, i.e. string comes first in dictionary will have lower value than string comes next. 17

2.1 : 6 Comparing the strings (Sequence data types) s1 = ‘box’ s2 = ‘boy’ if (s1 == s2): print (‘s1 and s2 are same’) else: print (‘s1 and s2 are not same’) s1 and s2 are not same 18 s1 = ‘box’ s2 = ‘boy’ if (s1 < s2): print (‘s1 is less than s2’) else: print (‘s1 is greater than or equal to s2’) s1 is less than s2

2.1 : 7 Removing spaces from the string (Sequence data types) — A space is also considered as a character inside a string. — Sometimes unnecessary spaces in a string lead to wrong results. — For example , “Mukesh” != “ Mukesh ” — This spaces can be removed using rstrip(), lstrip(), strip() methods. 19

2.1 : 7 Removing spaces from the string (Sequence data types) >>> str = “ Mukesh Deshmukh ” >>> print(str.rstrip()) # Removes spaces at right of string >>> print(str.lstrip()) # Removes spaces at left of string >>> print(str.strip()) # Removes spaces at both sides of string ….Mukesh Deshmukh Mukesh Deshmukh…. Mukesh Deshmukh 20 These methods do not remove spaces in the middle of the strings.

2.1 : 8 Formatting the strings (Sequence data types) — Formatting a string means presenting the string in clearly understandable manner. — The format() method is used as: ‘format string with replacement fields’. format (values) — The various attributes in above syntax are: — ‘format string with replacement fields’: — The replacement fields are denoted by curley braces {} that contain names or indexes. — These names are indexes represent the order of values. — For example, lets take an employee details like id number, name and salary in three variables: ‘id’, ‘name’ and ‘sal’. 21

2.1 : 8 Formatting the strings (Sequence data types) >>> id = 10 >>> name = ‘Shankar’ >>> sal = 19500.75 >>> str = ‘{},{},{}’.format(id,name,sal) 10,Shankar,19500.75 >>> str = ‘{}-{}-{}’. format(id,name,sal) 10-Shankar-19500.75’ >>> str =‘ID ={},\nName ={},\nSalary ={}’. format(id,name,sal) ID = 10 Name = Shankar Salary = 19500.75 22

2.1 : 9 Changing case of a string (Sequence data types) — Python offers 4 methods that are useful to change the case. — upper(): convert all characters of string into uppercase letters. — lower(): convert all characters of string into lowercase letters. — swapcase(): convert uppercase letters into lowercase and vice versa. — title(): convert the string such that each word starts with uppercase letter and remaining will be small case letters. 23

2.1 : 9 Changing case of a string (Sequence data types) — For example, str = ‘Python is the future’ print(str.upper()) PYTHON IS THE FUTURE print(str.lower()) python is the future print(str.swapcase()) pYTHON IS THE FUTURE print(str.title()) Python Is The Future — 24

2.1 : 10 String testing methods (Sequence data types) — Several methods to test the string which results either True or False. — 25 Operator Description isalnum() Returns True if all characters are alphanumeric else False. isalpha() Returns True if all characters are alphabets else False. isdigit() Returns True if all characters are numeric digits else False. islower() Returns True if all characters are lowercase else False. isupper() Returns True if all characters are uppercase else False. istitle() Returns True if all characters are title case else False. isspace() Returns True if contains only spaces else False.

Exception Handling in Python

Introduction Software programs and applications do not always work flawlessly. When we write a program, we can make mistakes that cause errors when we run it. In general, we can classify errors in a program into one of these three types: Compile-time errors( Syntax error ) Runtime errors( Exception ) Logical errors 27

In short errors are Syntax Errors → caught before execution Runtime Errors → occur during execution Logical Errors → no crash, but wrong output

Compile-time errors These are syntactical errors found in the code, due to which a program fails to compile. This are also known as Syntax errors For example, forgetting a colon in the statements like if, while, for, def, etc. will result in compile-time error. Such errors are detected by python compiler and the line number along with error description is displayed by the python compiler. 29

Example of Compile-time errors Example: A Python program to understand the compile-time error. 30 a = 1 if a == 1 print “hello” Output: File ex.py, line 3 I a == 1 ^ SyntaxError: invalid syntax

Syntax Errors Occur when code violates Python grammar rules Detected before execution Example: if x > 5 print('x is greater than 5') Error: SyntaxError : expected ':'

Logical errors These errors shows flaws in the logic of the program. The programmer might be using a wrong formula of the design. Logical errors are not detected either by Python compiler or PVM. The programme is solely responsible for them. 32

Example of Logical errors In the following program, the programmer wants to calculate incremented salary of an employee, but he gets wrong output, since he uses wrong formula. 33 def increment(sal): sal = sal * 15/100 return sal sal = increment(5000) print “Salary after Increment is”, sal Output: Salary after Increment is 750

Logical Errors Program runs without crashing Produces incorrect output Example: numbers = [10, 20, 30] average = sum(numbers) / len (numbers) - 1 print('Average:', average) # Wrong output

Runtime Errors (Exceptions) Occur during program execution Examples: ZeroDivisionError : 10/0 NameError : print(num) TypeError : '10' + 5 IndexError : my_list [5]

Run-time errors When PVM cannot execute the byte code, it flags runtime error. For example, inability of PVM to execute some statement come under runtime errors. Runtime errors are not detected by the python compiler. They are detected by the PVM, Only at runtime. 36

Example of Run-time errors Example: A Python program to understand the Run-time error. 37 print ("hai"+25) Output: Traceback (most recent call last): File "<pyshell#0 >", line 1, in <module> print "hai"+25 TypeError: cannot concatenate 'str' and 'int' objects

Exceptions: An exception is a runtime error which can be handled by the programmer. If the programmer cannot do anything in case of an error, then it is called an “error‟ and not an exception. All exceptions are represented as classes in python. The exceptions which are already available in python are called “built-in” exceptions. The base class for all built-in exceptions is “BaseException” class. 38

Exceptions: From BaseException class, the sub class “Exception” is derived. From Exception class, the sub classes “StandardError‟ and “Warning‟ are derived. All errors (or exceptions) are defined as sub classes of StandardError. An error should be compulsory handled otherwise the program will not execute. Similarly, all warnings are derived as sub classes from “Warning” class. A warning represents a caution and even though it is not handled, the program will execute. So, warnings can be neglected but errors cannot neglect. 39

40

Exception Handling: The purpose of handling errors is to make the program robust. The word “robust” means “strong”. A robust program does not terminate in the middle. Also, when there is an error in the program, it will display an appropriate message to the user and continue execution. Designing such programs is needed in any software development. For that purpose, the programmer should handle the errors. When the errors can be handled, they are called exceptions. 41

Programmer should perform the following four steps: Step 1: The programmer should observe the statements in his program where there may be a possibility of exceptions. Such statements should be written inside a “try‟ block. A try block looks like as follows: The greatness of try block is that even if some exception arises inside it, the program will not be terminated. When PVM understands that there is an exception, it jumps into an “except‟ block. 42 try: statements

Programmer should perform the following four steps: Step 2: The programmer should write the “except‟ block where he should display the exception details to the user. This helps the user to understand that there is some error in the program The programmer should also display a message regarding what can be done to avoid this error. Except block looks like as follows: 43 except exceptionname: statements The statements written inside an except block are called “handlers” since they handle the situation when the exception occurs.

Programmer should perform the following four steps: Step 3: If no exception is raised, the statements inside the “else‟ block is executed. Else block looks like as follows: 44 else: statements

Programmer should perform the following four steps: Step 4: Lastly, the programmer should perform clean up actions like closing the files and terminating any other processes which are running. The programmer should write this code in the “finally” block. Finally block looks like as follows: The speciality of finally block is that the statements inside the finally block are executed irrespective of whether there is an exception or not 45 finally: statements

Complete exception handling syntax 46 try: statements # Block of code to try risky_code () except Exception1: statements # Code to handle ExceptionType1 except Exception2: statements # Code to handle ExceptionType2 else: statements # Code to run if no exception occurs finally: statements # Code that always runs, whether exception occurs or not

The following points are followed in exception handling: A single try block can be followed by several except blocks. Multiple except blocks can be used to handle multiple exceptions. We cannot write except blocks without a try block. We can write a try block without any except blocks. Else block and finally blocks are not compulsory. When there is no exception, else block is executed after try block. Finally block is always executed. 47

48

49

50

Following is an example for handling divide by zero 51 numerator = int(input(“Enter the numerator ”)) denominator = int(input(“Enter the denominator ”)) try: quotient = numerator / denominator print("Quotient:", quotient) except ZeroDivisionError: print("Denominator cannot be zero") Input: Enter the numerator10 Enter the denominator 0 Output: Denominator cannot be zero

Following is an example for handling ValueError 52 while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again...") Please enter a number: hi Oops! That was no valid number. Try again... Please enter a number: 5 This example, asks the user for input until a valid integer has been entered

Following is an example for handling ValueError & ZeroError 53 try: numerator = int(input("Enter the numerator ")) denominator = int(input("Enter the denominator ")) quotient = numerator / denominator print("Quotient:", quotient) except ZeroDivisionError: print("Denominator cannot be zero") except ValueError: print("Please enter the no. not string") Enter the numerator Ten Please enter the no. not string

Raising an Exception We can raise exceptions manually even though there are no exceptions using the raise keyword. You can raise exceptions in several ways by using the “raise” statement. Following is syntax of Exception raising ExceptionName is the type of exception we want to raise. Arguments is optional 54 raise ExceptionName(arguments)

Example Raising an Exception Raise an error and stop the program if x is lower than 0 55 0: raise Exception("Sorry, no numbers below zero”) Exception: Sorry, no numbers below zero

Example Raising an Exception Raise an error if age below 18 years 56

User-Defined Exceptions: Like the built-in exceptions of python, the programmer can also create his own exceptions which are called “User-defined exceptions” or “Custom exceptions”. In some situations where none of the exceptions in Python are useful for the programmer. In that case, the programme has to create his/her own exception and raise it. For example, let’s take a bank where customers have accounts. Each account is characterized by customer name and balance amount. The rule of the bank is that every customer should keep minimum Rs. 2000.00 as balance amount in his account. 57

User-Defined Exceptions: The programmer now is given a task to check the accounts to know every customer is maintaining minimum balance of Rs. 2000.00 or not. If the balance amount is below Rs. 2000.00, then the programmer wants to raise an exception saying “Balance amount is less in the account of so and so person.‟ This will be helpful to the bank authorities to find out the customer. So, the programmer wants an exception that is raised when the balance amount in an account is less than Rs. 2000.00. Since there is no such exception available in python, the programme has to create his/her own exception. 58

User-Defined Exceptions: For this purpose, he/she has to follow these steps: Step1: Since all exceptions are classes, the programme is supposed to create his own exception as a class. Also, he should make his class as a sub class to the in-built ”Exception‟ class. Here, MyException class is the sub class for “Exception‟ class. This class has a constructor where a variable “msg” i s defined. This“msg‟ receives a message passed from outside through “arg‟. 59 class MyException(Exception): def __init__(self, arg): self.msg = arg

User-Defined Exceptions: Step2: The programmer can write his code; maybe it represents a group of statements or a function. When the programmer suspects the possibility of exception, he should raise his own exception using “raise‟ statement as: Here, raise statement is raising MyException class object that contains the given “message‟. 60 raise MyException(‘message’)

# Defining the User defined Exception class MyException(Exception): def __init__ (self, arg): self.msg = arg # Function to check the Checking the balnce def check(dict): for k,v in dict.items(): print("Name=",k,"Balance=",v) if v<2000: raise MyException("Balance amount is less in the account of "+k) # Code Showing the bank={"ravi":10000.00,"ramu":8500.00,"raju":1990.00} try: check(bank) except MyException as me: print(me.msg) 61

62

Introduction • Exceptions are runtime errors in a program. • Without handling, exceptions stop program execution. • Exception handling makes programs robust and error-tolerant.

Keywords in Exception Handling • try → Code block to test for errors. • except → Code to handle error. • else → Runs if no error occurs. • finally → Always executes (cleanup tasks). • raise → Used to trigger exceptions.

Simple Try-Except Example try: num = int(input('Enter a number: ')) print('Square:', num ** 2) except ValueError : print('Invalid input! Please enter a number.')

Multiple Except Blocks try: a = 10 b = int(input('Enter divisor: ')) print('Result:', a / b) except ZeroDivisionError : print('Error: Division by zero not allowed!') except ValueError : print('Error: Please enter a valid integer.')

Try-Except-Else try: x = int(input('Enter a number: ')) except ValueError : print('Invalid number!') else: print('You entered:', x)

Try-Finally Example try: file = open('example.txt', 'w') file.write ('Python Exception Handling Example') finally: file.close () print('File closed successfully.')

Raising Exceptions x = -5 if x < 0: raise ValueError ('Number must be positive')

Best Practices • Always handle specific exceptions instead of generic ones. • Use finally block for cleanup tasks. • Avoid catching exceptions silently. • Use raise for custom validations.

File Handling in Python

Introduction • File handling allows programs to store data permanently. • Python provides built-in functions to work with files. • Common operations: create, read, write, append. • open(' filename','mode ') is used to open a file.

File Modes in Python • 'r' → Read (default, file must exist) • 'w' → Write (creates new file or overwrites) • 'a' → Append (adds content at the end) • 'x' → Create (new file, error if exists) • 'b' → Binary mode (images, PDFs) • 't' → Text mode (default)

Example: Writing to File file = open('example.txt', 'w') file.write ('Hello, Python File Handling!') file.close ()

Example: Reading from File file = open('example.txt', 'r') content = file.read() print(content) file.close()

Example: Appending to File file = open('example.txt', 'a') file.write('\nThis line is appended.') file.close()

Best Practice: Using with with open('example.txt', 'r') as file: for line in file: print(line.strip()) • 'with' automatically closes the file.

Working with Binary Files with open('image.jpg', 'rb') as file: data = file.read(20) print(data)

The purpose of programming is to solve problems related to various areas, starting from simple problems like adding two numbers to very complex problems like designing of aircrafts. When there is a simple problem, any problem can be solved it by writing a simple program, but when there is a complex problem, a developer have to develop a lengthy complex code. To solve this problem, structural programming is a strategy used by programmers in general. In this method, the main program is divided into subparts represented by one or more functions. These subparts are called as ‘Modules’ . Structured Programming and Modules

Consider an example to calculate a net salary from basic salary. Gross salary = Basic Salary + Allowances gross = basic + da + hra Here, da is Dearness Allowance, HRA is House Rent Allowance Net Salary = Gross Salary – Deductions net = gross – pf – itax Here, pf = Provident Fund and itax = Income Tax Hence, to calculate a net salary, we have to calculate da, hra , pf and income tax. All these can be considered as modules and can be coded using functions. Structured Programming and Modules

This is represented by following diagram, Structured Programming and Modules main program net salary gross salary basic hra pf itax da

A Python program to calculate the gross and net salary of an employee using structured programming. # to calculate dearness allowance def da (basic): """ da is 125% of basic """ da = basic * 125/100 return da # to calculate house rent allowance def hra (basic): """ hra is 30% of basic """ hra = basic * 30/100 return hra Structured Programming and Modules

A Python program to calculate the gross and net salary of an employee using structured programming (Continued…..) # to calculate provident fund def pf (basic): """ pf is 12% of basic """ pf = basic * 12/100 return pf # to calculate income tax def itax (gross): """ tax is 10% of gross salary """ itax = gross * 10/100 return itax Structured Programming and Modules

A Python program to calculate the gross and net salary of an employee using structured programming (Continued…..) # main program basic = float (input ("Enter the basic salary: ")) gross = basic + da(basic) + hra(basic) print ("The gross salary is: ", gross) net = gross - pf(basic) - itax(gross) print ("The net salary is: ", net) Enter the basic salary: 25384.50 The gross salary is: 64730.475 The net salary is: 55211.2875 Structured Programming and Modules

A module represents a group of classes, methods, functions and variables. While developing software, there may be several classes, methods and functions. We should first group them depending on their relationship into various modules and then use these modules in other programs. When module is developed it can be reused in any program. In python, number of built-in modules are present. Similarly, a programmer can create their own modules and use them whenever needed. Creating Modules

Once module is created, to import that module, we can write: After import we can write next part of the program as, # to import employee module import employee # to calculate gross and net salary basic = float (input ("Enter the basic salary: ")) gross = basic + da(basic) + hra(basic) print ("The gross salary is: ", gross) net = gross - pf(basic) - itax(gross) print ("The net salary is: ", net) Enter the basic salary: 25384.50 Traceback (most recent call last): NameError: name 'da' is not defined Import Statement

Here it raises a ‘NameError’. In this case, we have to refer to the functions by adding the module name as employee.da(), employee.hra(), employee.pf() and employee.itax(). As discussed, import statement needs to refer every function defined in a module leading to complexity in code. To avoid this, we can use another import statement as, from employee import * In this case, all the functions of an employee module are referenced and hence, we can refer them without using a module name. From Import Statement

A Python program using from import statement, # to import employee module from employee import* # to calculate gross and net salary basic = float (input ("Enter the basic salary: ")) gross = basic + da(basic) + hra(basic) print ("The gross salary is: ", gross) net = gross - pf(basic) - itax(gross) print ("The net salary is: ", net) Enter the basic salary: 25384.50 The gross salary is: 64730.475 The net salary is: 55211.2875 From Import Statement

We already studied about assigning the names to the variables. Now it’s time to move on to the concept of namespaces. To simply put it, a namespace is a collection of names. In Python, you can imagine a namespace as a mapping of every name you have defined to corresponding objects. Different namespaces can co-exist at a given time but are completely isolated. A namespace containing all the built-in names is created when we start the Python interpreter and exists as long as the interpreter runs. Namespacing

This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program. Each module creates its own global namespace. These different namespaces are isolated. Hence, the same name that may exist in different modules do not collide. Modules can have various functions and classes. A local namespace is created when a function is called, which has all the names defined in it. Similar, is the case with class. Name Spacing

Although there are various unique namespaces defined, we may not be able to access all of them from every part of the program. The concept of scope comes into play. A scope is the portion of a program from where a namespace can be accessed directly without any prefix. At any given moment, there are at least three nested scopes. Scope of the current function which has local names. Scope of the module which has global names. Outermost scope which has built-in names. When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace. Python Variable Namespace Scope

Example of Scope and Namespace in Python def outer_function (): b = 20 def inner_func (): c = 30  a = 10 Here, the variable a is in the global namespace. Variable b is in the local namespace of outer_function () and c is in the nested local namespace of inner_function (). Python Variable Namespace Scope

When we are in inner_function (), c is local to us, b is nonlocal and a is global. We can read as well as assign new values to c but can only read b and a from inner_function (). If we try to assign as a value to b, a new variable b is created in the local namespace which is different than the nonlocal b. The same thing happens when we assign a value to a as shown below. In next program, three different variables a are defined in separate namespaces and accessed accordingly. So, at every execution a is in different Namespace scope and shows that particular value. Python Variable Namespace Scope

def outer_function (): a = 20 print('a =', a) def inner_function (): a = 30 print('a =', a) inner_function () a = 10 outer_function () print('a =', a) a = 30 a = 20 a = 10 Python Variable Namespace Scope

Consider next program, def outer_function (): global a a = 20 def inner_function (): global a a = 30 print('a =', a) inner_function () print('a =', a) a = 10 outer_function () print('a =', a) Python Variable Namespace Scope

An output of a program is a = 30 a = 30 a = 30 If we declare a as global, all the reference and assignment go to the global a. Here, all references and assignments are to the global a due to the use of keyword Python Variable Namespace Scope

Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist. In day today life we don't usually store all of our files in our computer in the same location. We use a well-organized hierarchy of directories for easier access. Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory. Analogous to this, Python has packages for directories and modules for files. As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. Python Packages

This makes a project (program) easy to manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules. Each package in Python is a directory which MUST contain a special file called __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file, so it can be imported the same way a module can be imported. Python Packages

PIP --- Preferred Installer Program PIP is a package manager for Python packages (either install or uninstall), or modules if you like. Check if PIP is Installed Navigate your command line to the location of Python's script directory, and type the following: C:\Users\ Your Name \>pip --version Introduction to PIP

If PIP is already installed, then it pop an installer with version number as shown below: If PIP is not installed, it can download and install from this page:  https://pypi.org/project/pip/ Note:  If you have Python version 3.4 or later, PIP is included by default. Introduction to PIP

In Python IDLE, a large number of packages are available to work with. We can verify whether a required package is already installed in IDLE or not, type at Python prompt: >>> help(‘modules’) It will display the list of all packages installed. If required package did not appear, then it can be installed using PIP installer as, C:\> pip install package_name Similarly, an already installed package can be uninstalled as, C:\> pip uninstall package_name Installing Packages via PIP

Now, we will look at all steps of PIP installer. Consider, we have to work with a good quality 2D graphics. For, this purpose a package “ matplotlib ” is needed. So, first we search that whether it is already installed or not using command, >>>help(‘modules’) After this command, all the packages are displayed on screen, which does not include “ matplotlib ” as shown in next window. So, it can be installed using command, > pip install matplotlib Installing Packages via PIP

Now, again type command, >>> help(‘modules’) Now, it will show the “ matplotlib ” package in the list. Similarly, if any package is not needed more, it can be uninstalled as, > pip uninstall matplotlib Now, again type command, >>> help(‘modules’) Now, it will not show the “ matplotlib ” package in the list. All this process can be shown graphically as, Installing Packages via PIP

Type at Python prompt: >>> help(‘modules’) It will display all installed packages in alphabetic order. Now, we are looking for a package, “matplotlib” which is not displayed in list. Installing Packages via PIP

Now, it can be installed using command prompt as: > pip install matplotlib Installing Packages via PIP

Now, it will check the pip version. If latest version is not installed it prompts about it instruct to install the new version as, Installing Packages via PIP

A new version can be installed using command as, > python –m pip install –upgrade pip It shows that, latest version now “Successfully installed” Installing Packages via PIP

Then type again at command prompt: > pip install matplotlib Installing Packages via PIP

It shows that “matplotlib” is installed successfully. Now, to verify, again type at Python prompt: >>> help(‘modules’) Look carefully, “matplotlib” is displayed in list now. Installing Packages via PIP

After its work, it can be removed also using command prompt, > pip uninstall matplotlib Installing Packages via PIP

Command prompt will confirm again using prompt as, Proceed (y/n)? Installing Packages via PIP

After entering ‘y’ the package will successfully uninstalled from IDLE as shown below, Installing Packages via PIP

Now, we can verify, again by typing at Python prompt: >>> help(‘modules’) “matplotlib” is not displayed in list now. Installing Packages via PIP

As we have discussed, a large number of Packages are present inside a Python Library. We also discussed the installing and uninstalling of Packages using PIP installer. Following are some of the most used Python Packages. 1. numpy: Python supports only single dimensional arrays. To create multi-dimensional arrays, a special package named ‘numpy’ is used. Using Python Packages

2. pandas ‘pandas’ is a package used in data analysis. This package is mostly used by data scientist and data analysts. 3. xlrd ‘xlrs’ is a package that is useful to retrieve data from Microsoft Excel spreadsheet files. Hence, this is also useful in data analysis. 4. matplotlib ‘matplotlib’ is another important package in Python that is useful to produce good quality 2D graphics. It is used for the purpose of showing data in the form of graphs and also designing circuits, machinery parts, etc. Using Python Packages

Pass by Object Reference In C and Java, the values are passed to function using two methods: Pass (call) by value and pass (call) by reference. In pass by value, the variable values are passed to function by copying them inside a function, and any modifications in the variable value inside function will not reflect outside it. In pass by reference, a memory address holding that variable is passed to the function. Variable value is modified by the function through memory address and hence the modified value will reflect outside the function also. Neither of these two concepts is applicable in Python.

Pass by Object Reference In Python, the values are sent to functions by means of object references, because everything in Python like, numbers, strings, lists, tuples, etc all considered as object. For example, if we store a value inside a variable as, x = 10 In this case, in C or Java, a variable with name ‘x’ is created and some memory is allocated to variable. Then the value 10 is stored in variable ‘x’. This is not the case in Python. In Python everything is an object. So, in this case an object with value 10 is created first in memory (heap memory, generally a very huge memory depending on RAM of a system) and then is referred by a name (variable) x.

Pass by Object Reference To know the location of an object in heap, we can use id() function that gives identity number (memory location) of an object as, x = 10 id (x) 140728458201024 This number may change from computer to computer depending on available memory location to create an object. When we pass values like numbers, strings, tuples or lists to a function, the references of these objects are passed to the function. Consider the next program,

Pass by Object Reference def modify (x): x = 15 print (x, id(x)) x = 10 modify (x) print (x, id(x)) 15 140728458201184 10 140728458201024 From output, it is clear that the value of ‘x’ inside function is 15 and is not available outside the function. It can be explained as below.

Pass by Object Reference This means another object 15 is created in memory and that object is referenced by ‘x’. The reason of creation of another object that integers are immutable. So in function, when we display ‘x’ value, it will display 15. Once, we come outside function, it will display old object i.e. 10. The Identity values of x inside and outside function are different, since they are different objects. When we call modify () function and pass ‘x’, we are passing object reference to modify () function. The object is 10 and reference name is ‘x’. Inside function, we use x = 15 x outside the function inside modify() function x 15 10

Pass by Object Reference In Python integers, floats, strings and tuples are immutable. That means, when we try to modify their values, a new object is created with the modified value. On the other hand, lists and dictionaries are mutable. That means, when we change their data, same object gets modified and new object is not created. For example, we pass list elements to modify function. When we append a new element to the list, the same list is modified and hence the modified list is available outside the function also. Consider the next program,

Pass by Object Reference def modify ( lst ): lst.append (8) print ( lst , id( lst )) lst = [1, 2, 3, 4] print ( lst , id( lst )) modify ( lst ) print ( lst , id( lst )) [1, 2, 3, 4] 2832417495808 [1, 2, 3, 4, 8] 2832417495808 [1, 2, 3, 4, 8] 2832417495808 As shown in output, the modified list is available outside the function also. It can be explained as below.

Pass by Object Reference Since, lists are mutable, adding a new element to same object is possible. Hence, append() method modifies the same object. So, outside the function also, a modified list only is available. The Identity values of lst inside and outside function are same. When we call modify () function and pass ‘lst’, we are passing object reference to modify () function. The object is list and reference name is ‘lst’. Inside function, we are appending a new element ‘8’ to the list lst outside the function inside modify() function lst append 1, 2, 3, 4

Pass by Object Reference So, the final point is that: in Python, The values are passed to a function by object reference only. If the object is immutable, the modified value is not available outside the function. If the object is mutable, its modified version is available outside the function also. But a caution is needed here. If we create altogether a new object inside the function (not a modification of existing mutable object), then it will not be available outside the function. Consider the next program,

Pass by Object Reference def modify ( lst ): lst = [10, 11, 12] lst.append (8) print ( lst , id( lst )) lst = [1, 2, 3, 4] print ( lst , id( lst )) modify ( lst ) print ( lst , id( lst )) [1, 2, 3, 4] 1698584370560 [10, 11, 12, 8] 1698583019456 [1, 2, 3, 4] 1698584370560 As shown in output, the modified list is not available outside the function as it treated as different object (with different ID) inside the function. It can be explained as below.

Pass by Object Reference When we append new element ‘8’ inside a function it will modify the ‘lst’ defined inside a function and not ‘lst’ defined outside a function. So, the identity numbers of these two lists are different as they are different objects. Here, inside a modify () function, new list is created as [10, 11, 12]. It means, a new object is created inside a function referred by a name lst. So, inside a function, object lst is displayed as, lst = [10, 11, 12] lst outside the function inside modify() function lst 1, 2, 3, 4 10, 11, 12

Keyword Variable Length Arguments A keyword variable length argument is an arrangement that can accept any number of values provided in the format of keys and values. It is declared with ‘**’ before the argument as, def fun (farg, **kwargs): Here, ‘kwargs’ represents keyword variable length argument. We can pass one or more arguments to this ‘args’ and it will store them all as a dictionary. It means, when we provide values for ‘kwargs’, we can pass multiple pairs of values using keywords as shown in next program.

A Python program for keyword variable length arguments. def display ( farg , ** kwargs ): print("Formal argument = ", farg ) for x,y in kwargs.items (): print ("Key = {}, value = {}“. format(x, y)) display (1, roll_no = 5) display (1, roll_no = 5, name = "Vijay") The output is: >>> Formal argument = 1 Key = roll_no , value = 5 >>> Formal argument = 1 Key = roll_no , value = 5 Key = name, value = Vijay Keyword Variable Length Arguments

Global Keyword In previous program we access global variable inside a function using ‘global keyword’ . The disadvantage is that the value of global variable is also get modified. If a programmer wants to work with both global and local value of variable, then is possible using ‘ globals keyword’ as shown, a = 1 def myfunction (): a = 2 x = globals () ['a'] print ('global value of a = ', x) print ('modified global value of a = ', a) myfunction () print ('global value of a = ', a) global value of a = 1 modified global value of a = 2 global value of a = 1

Passing Group of Elements to Function To pass a group of elements like numbers or strings, we can accept them into a list first and the pass it to the functions. For example, A Python program to accept a group of numbers and find their sum and average. First accept all the numbers using list comprehension as, lst = [ int (x) for x in input(). split()] The input () function takes a group of integers separated by space as a string which then split into pieces using space for split () method and converted into integers by int () function. These integers returns into a list ‘lst’ , to pass to function. The function returns two values ‘sum’ and ‘average’.

Same can be written in Python program as, def calculate ( lst ): n = len ( lst ) sum = 0 for i in lst : sum += i avg = sum / n return sum, avg print ('Enter the numbers separated by space: ' ) lst = [ int (x) for x in input().split()] print ( "The list is :", lst ) x,y = calculate ( lst ) print ("The Sum is :", x) print ("The average is: ", y) Passing Group of Elements to Function

The output is: Enter the numbers separated by space: 5 10 15 20 The list is : [5, 10, 15, 20] The Sum is : 50 The average is: 12.5 Passing Group of Elements to Function

A Python program to display the name of students (group of string) using functions. def display (lst): for i in lst: print (i) print ('Enter the names separated by space: ' ) lst = [ x for x in input().split()] display (lst) Enter the names separated by space: Vijay Ankit Madhuri Rashmi Vijay Ankit Madhuri Rashmi Passing Group of Elements to Function

Generators are the functions that return a sequence of values. A generator function is written like an ordinary function but it uses ‘yield’ statement instead of return statement. Generator statement always returns a generator object with the sequence of numbers as returned by ‘yield’ statement. For example, a generator function to return numbers from x to y def mygen(x,y): while x <= y: yield x x += 1 g = mygen(5,10) for i in g: print (i, end = ' ') 5 6 7 8 9 10 Generators

Once generator object is created, we can store the elements of the generator into a sequence (list, tuple or set) using list(), tuple() or set() function as shown in following program. def mygen(x,y): while x <= y: yield x x += 1 g = mygen(5,10) lst = list (g) print (lst) [5, 6, 7, 8, 9, 10] # tuple (g) gives output as (5, 6, 7, 8, 9, 10) # set (g) gives output {5, 6, 7, 8, 9, 10} Generators
Tags