Python Basics For Beginners Programming Material
Python Basics For Beginners Programming Material
&
Programming Material
Course: Python Programming Basics
(Duration: around 45 Hours)
Contents
1. What is Python and why is it important today
2. Introduction to Programming Using Raptor Tool
3. Introduction to Python Programming
4. Control Structures
5. String Handling
6. Arrays
7. Lists, Tuples, Dictionaries & Sets
8. Functions
9. Modules & “from” keyword
10. Command Line arguments
11. Object Oriented Programming Basics
12. Inheritance & Polymorphism
13. Exception Handling
14. File Handling
15. Turtle Graphics Programming
16. Regular Expressions in Python
17. Date & Time
18. Miscellaneous topics
DATAPRO COMPUTERS 1
1
Contents
Chapter-1 (What is Python and why is it important today)
1. What is Python
2. Which companies are already using it
3. Why everyone is talking about it now
4. Different types of applications that can be created using Python
5. Features of Python
DATAPRO COMPUTERS 2
2
7. Program: Demo on boolean operators
8. Program: Demo on “is” operator
9. Program: Demo2 on “is” operator
10. Program: “for” loop demo
11. Program: “while” loop demo
12. Program: To print in the same line
13. Program: To display odd numbers from 1 to 10 using range()
14. Program: To display numbers from 10 to 1 in descending order
15. Program: Multiplication table
16. Program: Reversing an integer
17. Program: Finding whether a given number is an Armstrong number or not
18. Program: Nested Loops
19. Program: Multiple Multiplication tables using nested loops
20. Program: Finding factorial of a given number
21. Program: Finding whether a given number is a strong number or not
22. Program: Display Fibonacii Series
23. Program: Infinite Loop
24. Introduction to Jump Statements
25. Program: break statement
26. Program: continue statement
27. Program: Finding whether a given number is a Perfect number or not
28. Program: Finding whether a given number is a Prime number or not
29. Program: LCM of two numbers
30. Program: GCF of two numbers
31. Program: Pyramid Ex1
32. Program: Pyramid Ex2
33. Program: Pyramid Ex3
34. Program: Pyramid Ex4
35. Program: Demo on pass statement
36. Program: “else” clause on loops
37. Program: assert statement Demo
38. Some Assignments
DATAPRO COMPUTERS 3
3
16. Program: Demo on strip(), lstrip(), rstrip()
17. Program: Finding position of a sub string – Demo
18. Program: To display all positions of a substring – Demo
19. Program: Counting substrings in a string
20. Strings are Immutable
21. Program: Strings are Immutable – Demo1
22. Program: Strings are immutable – Demo2, also covers id()
23. Program: Demo on replace()
24. Program: Demo1 on splitting a string
25. Program: Demo2 on splitting a string
26. Program: Demo on joining the strings
27. Program: Demo on changing case of a string
28. Program: Demo on startswith() and endswith()
29. Program: Demo on testing the nature of characters in a String
30. Program: Demo on sorting of strings
31. Some Assignments
Chapter-6 (Arrays)
1. What is an Array
2. Advantages of Arrays
3. Syntax of Creating an Array and Typecodes
4. Program: Importing “array” module in different ways and creating an integer array
5. Program: Creating floating type array
6. Program: Creating a character array
7. Program: Creating one array from another array
8. Program: Retrieve the elements of an array using array index
9. Slicing an array
10. Program: Demo on slicing an array
11. Program: Demo on using various methods of arrays class
12. Program: Reading a student’s marks in 5 subjects into an int array and find the average marks
13. Program: Generating Results sheet from students’ marks
14. Program: Bubble sorting of integer array
15. Program: Types of arrays
16. Some assignments
DATAPRO COMPUTERS 4
4
15. Program: Aliasing of lists
16. Program: Cloning of lists
17. Program: Finding biggest and smallest elements in a list
18. Program: Count number of occurrences of an element in the list
19. Program: Demo1 on List comprehensions
20. Program: Demo2 on List comprehensions
21. Program: Demo3 on List comprehensions
22. Lists Vs Tuples
23. Program: Demo on Tuples
24. Program: Tuples – Demo2 – Tuple unpacking
25. Program: Demo on some basic operations of a Tuple
26. Program: To find the first occurrence of an element in a tuple, also covers converting list to tuple
27. Program: Demo on nested tuples
28. Program: To sort a tuple with nested tuples
29. Program: Inserting elements in a tuple
30. Program: Modifying elements in a tuple
31. Program: Deleting elements from a tuple
32. Program: Dictionary – ex1
33. Program: Dictionary – ex2 – List as a value
34. Program: Dictionary – ex3 – A Dictionary nested inside another Dictionary
35. Program: Dictionary – ex4 – finding length, adding & removing
36. Program: Create a dictionary with cricket players names and scores in a match, retrieve runs by
entering the player’s name
37. Program: Using for loop to retrieve elements of a dictionary
38. Program: Sorting the elements of a dictionary with Lambdas
39. Program: Converting Lists into Dictionary
40. Program: Demo on converting a string to dictionary
41. Program: Demo on ordered dictionary
42. Program: Sets Demo
43. Program: Demo on frozenset
44. Program: Finding common elements in two lists using sets – Ex1
45. Program: Finding common elements in two lists using sets – Ex2
Chapter-8 (Functions)
1. Introduction to creating user defined functions
2. Program: Demo on creating user defined functions
3. Program: Demo on creating a docstring in a function and referring to it while calling the function
4. Program: Returning multiple values from a function Demo1
5. Program: Returning multiple values from a function Demo2
6. Functions are also objects in Python
7. Program: Assigning a function to a variable
8. Program: Nesting of functions
9. Program: Passing function as parameter to another function
10. Program: Demo on returning a function from another function
11. Function call mechanisms in Python
12. Program: Passing an integer to a function and modifying it
13. Program: Passing a list to a function and modifying it – Demo1
14. Program: Passing a list to a function and modifying it – Demo2
15. Types of actual arguments
16. Program: Demo on positional arguments
DATAPRO COMPUTERS 5
5
17. Program: Demo on keyword arguments
18. Program: Demo1 on default arguments
19. Program: Demo2 on default arguments
20. Program: Demo1 on variable length arguments
21. Program: Demo2 on variable length arguments
22. Program: Demo3 on variable length arguments
23. Program: Demo4 on variable length arguments
24. Program: Demo on keyword variable length argument
25. Program: Demo on Local Vs Global variables
26. Program: Demo on Global keyword
27. Program: Demo on recursive functions Ex1
28. Program: Demo on recursive functions Ex2
29. Lambda Expressions in Python
30. Program: Lambda expressions Ex1
31. Program: Using Lambdas with filter() – Ex1
32. Program: Using Lambdas with filter() – Ex2
33. Program: Using Lambdas with map() – Ex1
34. Program: Using Lambdas with map() – Ex2
35. Program: Using Lambdas with reduce() – Ex1
36. Program: Using Lambdas with reduce() – Ex2
37. Program: reduce() with operator module functions
38. Program: Demo on accumulate()
39. Function Decorators
40. Program: Function Decorators – Ex1
41. Program: Function Decorators – Ex2
42. Special variable __name__
43. Program: Demo on special variable __name__
DATAPRO COMPUTERS 6
6
10. Program: Static Methods Demo
11. Program: Inner classes demo
12. Some assignments
DATAPRO COMPUTERS 7
7
13. Program: File Handling – Writing Records in Binary Mode
14. Program: File Handling – Reading Records in Binary Mode
15. Program: File Handling - Zipping files
16. Program: File Handling - UnZipping a file to extract its contents
17. Program: File Handling - To know the current working directory
18. Program: File Handling - To display all contents of the current directory and its sub-directories as
well
19. Program: File Handling - To create a sub directory
20. Program: File Handling - To remove a sub directory
DATAPRO COMPUTERS 8
8
16. Program: Quantifiers in Regular Expression – Ex1
17. Program: Quantifiers in Regular Expression – Ex2
18. Program: Quantifiers in Regular Expression – Ex3
19. Program: Quantifiers in Regular Expression – Ex4
20. Special Characters in Regular Expression
21. Program: Special Characters in Regular Expression – Ex1
22. Program: Special Characters in Regular Expression – Ex2
23. Program: Special Characters in Regular Expression – Ex3
24. Program: Special Characters in Regular Expression – Ex4
25. Program: Special Characters in Regular Expression – Ex5
26. Program: Using Regular Expressions on Files – Ex1
27. Program: Using Regular Expressions on Files – Ex2
28. Program: Using Regular Expressions to get data from a HTML table
DATAPRO COMPUTERS 9
9
DATAPRO COMPUTERS 10
10
Chapter-1: What is Python and why is it important today
DATAPRO COMPUTERS 11
11
ome Popular
created using
Python
DATAPRO COMPUTERS 12
12
DATAPRO COMPUTERS 13
13
11
DATAPRO COMPUTERS 14
14
12
ery
ery is o ering it at
Undergraduate le el itself
ery is asking for it
DATAPRO COMPUTERS 15
15
oom in
oom in
15
DATAPRO COMPUTERS 16
16
DATAPRO COMPUTERS 17
17
DATAPRO COMPUTERS 18
18
DATAPRO COMPUTERS 19
19
pplica ons console & UI using kinter t
ccessing like racle My L MongoD irebase
pplica ons using Django lask frameworks
using Pandas
eaborn
kicit learn
ensor ow Keras
Programming pyspark
MRI Images atellite Images nibabel
face recogni on 21
22
DATAPRO COMPUTERS 20
20
2
DATAPRO COMPUTERS 21
21
25
DATAPRO COMPUTERS 22
22
Chapter-2: Introduction to Programming using Raptor Tool
Introduction to Programming
DATAPRO COMPUTERS 23
23
Different Programming languages
DATAPRO COMPUTERS 24
24
11
12
DATAPRO COMPUTERS 25
25
1
Go to: https://raptor.martincarlisle.com/
DATAPRO COMPUTERS 26
26
DATAPRO COMPUTERS 27
27
Launch the Application
DATAPRO COMPUTERS 28
28
Example1: Sum of two numbers
Step1.
DATAPRO COMPUTERS 29
29
tep Drag and drop “Input” symbol to accept a number
tep Now right click inside the input symbol (that has been dragged) and click “ dit”
Note: The prompt message must be enclosed within double quotation marks
DATAPRO COMPUTERS 30
30
nd click “Done”
It changes to:
DATAPRO COMPUTERS 31
31
It changes to:
DATAPRO COMPUTERS 32
32
Step6. Now we need assignment (sum of two numbers)
lick “Done”
It changes to:
DATAPRO COMPUTERS 33
33
Step7. Now we have to display the output:
Here we have to combine/join/concatenate the message and the ariable using the “+” sign
DATAPRO COMPUTERS 34
34
It changes to:
DATAPRO COMPUTERS 35
35
Click again:
DATAPRO COMPUTERS 36
36
Click again:
DATAPRO COMPUTERS 37
37
Click again:
DATAPRO COMPUTERS 38
38
Click again:
Click again:
DATAPRO COMPUTERS 39
39
Notice the output message on the console:
Click again:
Step9. Instead, if we click on the following icon, then click is required only once:
DATAPRO COMPUTERS 40
40
Step10. To increase figure size:
Example2: To check whether the given number is even number or odd number (conditions)
41
Drag and drop the “input” symbol and dit it
Step2.
tep Right click inside the “Diamond” shape of the “selection” symbol and edit it
DATAPRO COMPUTERS 42
42
It appears as:
DATAPRO COMPUTERS 43
43
Step5. Now write respective output messages
DATAPRO COMPUTERS 44
44
Step6. Now run the program
If input is 24:
DATAPRO COMPUTERS 45
45
Step7. If input is 25:
DATAPRO COMPUTERS 46
46
DATAPRO COMPUTERS 47
47
Chapter-3: Introduction to Python Programming
No. It wasn't named after a dangerous snake. Rossum was fan of a comedy series from late seventies.
The name "Python" was adopted from the same series "Monty Python's Flying Circus".
Step1. Go to python.org:
DATAPRO COMPUTERS 48
48
Initialization may take some time - around 5 minutes
DATAPRO COMPUTERS 49
49
Step4. Once the installation is over, we can find corresponding items in the start menu:
lick “IDL ”
We should see the python shell (IPython shell: Interactive Python Shell):
DATAPRO COMPUTERS 50
50
Program: To display a welcome message on the console
Note: When we press enter key after print() statement automatically the code gets executed.
Note: When the python interpreter finds there is something to be printed it prints immediately.
Note: This shell is also known as REPL (Read, Execute, Print & Loop)
Note: Notice that parentheses are required in python 3.5.2 whereas it is not required for example in
2.6.1
Note: we can even enclose the strings within single quotation marks.
DATAPRO COMPUTERS 51
51
Program: Comments and variables, sum of two numbers
Note: fter printing the result also the alue persists Now if we gi e “a” or “b” or “c” it prints its
corresponding result.
DATAPRO COMPUTERS 52
52
Note: Underscores are allowed in a variable name.
Program: To use built-in mathematical functions and to show all the built-in functions in python
DATAPRO COMPUTERS 53
53
To show help on any built-in function
Ex:
Help mode
DATAPRO COMPUTERS 54
54
Note: Type “q ” to get out of help mode.
Program: Demo on importing a module and using it, also covers giving alias names to built-in
functions in modules
DATAPRO COMPUTERS 55
55
Program: Demo on how to save and run python files
Note: Till now we are running the python code on the shell, we are not saving the code for later use.
Also recollect that we are unable to go to the previous line to edit the code
Step2. To Run:
Output:
DATAPRO COMPUTERS 56
56
How to run a Python program without opening the python shell every time we want to run the
program
Step1. 1st edit the previous program, just add the following at the end:
DATAPRO COMPUTERS 57
57
Note: The 1st two are called interactive modes where we can type the program one line at a time and
the PVM executes it immediately. The 3rd one is called non-interactive mode where we ask the PVM to
execute our program after typing the entire program
: ’
Step1. To open
Note: type exit() to terminate the PVM and close the window
Method2: ’ E
Step1. To open
DATAPRO COMPUTERS 58
58
Note: Here we increase / decrease font size and change font style.
Note: Instead of executing line by line, we can 1st create a .py file by saying File → New File
Step1. Open some text editor like notepad and type the program
Step2. Save it
Step3. pen the perating ystem’s command prompt (In Windows – DOS prompt) and go to that
directory where the .py file is saved, then issue the command to run the program
DATAPRO COMPUTERS 59
59
Built-in Datatypes in Python
• None type
• Numeric types (int, float, complex)
• Boolean type (True, False)
• Sequences (str, list, tuple)
• Sets (for unique elements)
• Mappings/Dictionary (for key:value pairs)
None ype: represents an object that does not contain any alue In Ja a it is equi alent to “null”
One of the uses of “None” is that it is used inside a function body as a default alue of the arguments
User-defined datatypes
In Python, arrays, classes and modules are user-defined datatypes. We shall see how to create them in
the upcoming topics
DATAPRO COMPUTERS 60
60
Operators in Python
You have seen operators in C, C++ and Java language, similarly Python also has got some operators.
Arithmetic operators:
+, -, *, /, %, // (integer division), ** (exponential / power)
Relational operators:
<, >, <=, >=
Equality operators:
==, !=
Identity operators:
These operators compare the memory locations of two objects. There are two identify
operators: is, is not
Logical operators:
Note: Remember that True indicates any non-zero value, whereas False indicates 0.
DATAPRO COMPUTERS 61
61
There are three logical operators in python: and, or, not
Boolean operators:
boolean operators act upon “bool” type of literals and they pro ide bool type output here are
three boolean operators in python: and, or not
Assignment operators:
=, +=, -= etc
Unary operators:
Unary minus (-)
Bitwise operators:
~ itwise one’s compliment
<< left shift
>> right shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
Membership operators:
Note: It is useful to find whether an element exists in a collection or not. There are two
membership operators: in, not in
Operators Precedence/Priority/Hierarchy
Operator Description
() Parenthesis
** Exponentiation (raise to the power)
~, +, - itwise one’s omplement unary plus and minus
*, /, %, // Multiply, divide, modulo and floor division
+, - Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise 'AND'
^, | Bitwise exclusive `OR' and regular `OR'
<=, <, >, >= Relational operators
==, != Equality operators
=, %=, /=, //=, -=, +=, *=, **= Assignment operators
Is, is not Identity operators
In, not in Membership operators
not, or, and Logical operators
Operator Associativity
DATAPRO COMPUTERS 62
62
Associativity is the order in which an expression is evaluated that has multiple operator of the same
precedence. Almost all the operators have left-to-right associativity.
Output:
DATAPRO COMPUTERS 63
63
Chapter-4: Control Structures
Control Structures are used to control the flow of execution of the program.
Whenever we need to execute some code based on some conditions, then we use Decision Control
Structures.
Ex1: In the context of ATM center, withdraw amount only if the requested amount is <= balance amount
Ex2: In the context of filling an online form, if phone number is not entered then display the message:
“phone number is missing”
You will understand each one of them when you see the programs.
Whene er we need to repeatedly execute a set of statements for “n” number of times then we use
Loop Control Structures.
Ex1: To display mini statement (say to display latest 10 transactions), the run the loop for 10 times.
Ex2: to display power bill payment history of 1 year, we run the loop for 12 times.
: “ ”
DATAPRO COMPUTERS 64
64
Output:
: “ ” “ ”
Note: indentation indicates block here if we don’t put indentation it assumes that the statement(s) are
not inside “if” or “else”
Output:
: “ ” “ ”
Output:
DATAPRO COMPUTERS 65
65
Program: Demo on logical operators
(a)
Output:
(b)
Output:
(c)
DATAPRO COMPUTERS 66
66
Output:
: ( “ ” operator)
Note: “is” is used to compare memory locations of two objects but not their contents
DATAPRO COMPUTERS 67
67
Note: to the object we ha e named “a” later to the same object we ha e named “b” So, the
same object 67 now has two names.
Program: Demo2 “ ”
Note: Even though the elements are same, for lists separate memory is created, so both “x” “ ”
have different ids which is unlike integers
Output:
Output:
Ex1:
Note: range() generates numerical values between the min(including) and max(excluding) values
Output:
DATAPRO COMPUTERS 68
68
Ex2:
Output:
Output:
DATAPRO COMPUTERS 69
69
Program: To display odd numbers from 1 to 10 using range()
Output:
Output:
Output:
DATAPRO COMPUTERS 70
70
Program: Reversing an integer
Output:
Output:
DATAPRO COMPUTERS 71
71
Program: Nested Loops
Output:
Output:
DATAPRO COMPUTERS 72
72
Program: Finding factorial of a given number
Output:
Output:
DATAPRO COMPUTERS 73
73
Program: Display Fibonacci Series
Output:
The Jump statements are used to alter the normal flow of a loop, like to terminate a loop
prematurely/when a certain condition is met, or to skip the next statements in a loop for a particular
iteration(s).
DATAPRO COMPUTERS 74
74
Program: break statement
Note: Whene er a “break” statement is encountered in a loop the control jumps out of the loop
Note: Whene er a “continue” statement is encountered in a loop the compiler interpreter skips the
execution of the remaining statements in the loop and continues with the next iteration.
Output:
DATAPRO COMPUTERS 75
75
Program: Finding whether a given number is a Perfect number or not
Output:
Output:
DATAPRO COMPUTERS 76
76
Program: LCM of two numbers
Output:
Output:
DATAPRO COMPUTERS 77
77
Program: Pyramid Ex1
Requirement:
Code:
Requirement:
Code:
DATAPRO COMPUTERS 78
78
Program: Pyramid Ex3
Requirement:
Code:
Requirement:
Code:
DATAPRO COMPUTERS 79
79
Program: Demo on pass statement
Output:
:“ ”
Note: You can use the else statement in the for and while loops in Python. The else statement is
optional and executes if the loop iteration completes normally. If the loop is terminated with a break
statement, the else statement will not be executed.
Case1:
Output:
DATAPRO COMPUTERS 80
80
Now, you might be wondering what is the purpose! Just put the statement of “else” without using “else
Case2:
Output:
Case3:
Now consider the example in which the code inside the else statement will not be executed
Note: The “else” clause of a loop does not get executed if the loop is terminated due to the execution of
a “break” statement inside the loop.
Output:
DATAPRO COMPUTERS 81
81
Case4:
Output:
An assert is a statement in Python which tests for a condition. If the condition is true, the program
continues normally and if the condition is false, the program is terminated and a user-defined error
message
Note: The assert statement is useful to check if a particular condition is fulfilled or not
Note: The Python interpreter checks if num> 0 is True or not. If it is True, then the next statements shall
be executed else it will display “ ssertion rror” along with the message “Wrong input entered”
Output:
DATAPRO COMPUTERS 82
82
Chapter-5: String Handling
Output:
Output:
DATAPRO COMPUTERS 83
83
Note: without format specifier
Program: Printing multiple values together using place holders and format()
Another way:
Note: These names can be used any number of times in the placeholders
DATAPRO COMPUTERS 84
84
Note: Default Delimiter is space, try s.split(',') as well.
Output:
Program: Demo on accessing each element of a string in forward and reverse orders using while loop
DATAPRO COMPUTERS 85
85
Output:
DATAPRO COMPUTERS 86
86
Program: Demo on checking membership
Note: Here we use “in” and “not in” operators hey are useful in checking whether a string exits in
another larger string or not
Output:
Output:
DATAPRO COMPUTERS 87
87
Output:
Note: These functions are used to remove unnecessary whitespaces in the beginning and/or ending of a
string
Output:
Output:
Note: if we use index() instead of find() index() returns “Value rror” exception when the sub string is
not found.
Note: To accomplish this task, there is no library function, we have to write our own logic
DATAPRO COMPUTERS 88
88
Eg:
Akhil is studying at ANITS. Akhil has joined at datapro for Python course. Datapro is liked by Akhil. I have
seen Akhil at R K Beach.
Output:
An immutable object is an object which cannot be changed. A mutable object is the one which can be
modified.
In Python:
numbers, strings and tuples are immutable
Lists, sets, dictionaries are mutable
Main reasons why strings are made immutable (in Python and Java too)
DATAPRO COMPUTERS 89
89
Efficiency: When an object is made mutable, it shall have fixed size in RAM. At string creation time itself
memory is allocated and it won’t change It increases the performance of the program
The dependents are not affected: Any attempts made to modify the contents of a string object will
create a new object in RAM, and the identity number of the new string object will be different.
DATAPRO COMPUTERS 90
90
Program: Demo1 on splitting a string
Note: split() is used to split a string into pieces and return the pieces as a list type.
DATAPRO COMPUTERS 91
91
Program: Demo on testing the nature of characters in a String
s3 = sorted(s1, reverse=True)
(OR)
s1.sort(reverse=True)
DATAPRO COMPUTERS 92
92
: ’ x “” ’ .
DATAPRO COMPUTERS 93
93
Chapter-6: Arrays
What is an Array
An array is an object that stores a group of elements/values of same datatype. The main advantage of
an array is to store elements in a single variable and process them easily.
In Python there is a standard module – “array” that helps us to create and use arrays
Advantages of Arrays
• Arrays are similar to lists (we shall see them later), the main difference is that arrays can store
similar type of elements only whereas lists can store different types of elements.
• While dealing with a huge number of elements, arrays use less memory than lists and they offer
faster execution than lists.
• Unlike in C, C++, In Python arrays can increase or decrease their size dynamically. We need not
declare the size of the array in advance. As and when the elements are added it will increase its
size and when the elements are removed, it will automatically decrease its size in memory.
• here are a lot of methods (in “array” module) to process the elements in an array
Syntax:
arrayname = array(typecode, [the elements])
Typecode:
: “ ”
DATAPRO COMPUTERS 94
94
(b) import method1
Output:
Note: Here the advantage is no need to prefix with the module name
DATAPRO COMPUTERS 95
95
Note: Here the advantage is all classes/functions of array module can be used directly without any
prefixing
import math
dir(math)
import array
dir(array)
Output:
DATAPRO COMPUTERS 96
96
Output:
Output:
Output:
DATAPRO COMPUTERS 97
97
Program: Retrieve the elements of an array using array index
Output:
Slicing an array
A slice represents a piece of the whole. When we perform slicing operations on an array, we can retrieve
subgroup of elements. Indexing is useful in retrieving element by element from the array, whereas
slicing is useful in retrieving a range of elements.
Syntax:
arrayname[start:end:step]
DATAPRO COMPUTERS 98
98
Output:
Also try:
Note: get the last 8 elements, then in the original array, upto index 4 (excluding)
DATAPRO COMPUTERS 99
99
Output:
:R ’ j average marks
Method1:
Output:
100
Method2:
Note: Recollect that array processing is faster. If all the elements are of same type, then better put
them in an array.
Output:
: R ’
101
Output:
102
Output:
In standard Python, we can create and work with Single dimensional arrays only. Python does not
support multi-dimensional arrays directly. We can deal with them using third party packages like
numpy. We shall see it in Python Data Analysis topic
103
Chapter-7: Lists, Tuples, Dictionaries & Sets (Python built-in Data Structures)
Lists Introduction
A List is similar to an array that consists of a group of elements. The major difference is a list can store
different types of elements whereas an array can store same type of elements only. Hence lists are
more versatile than arrays, in fact list are the most used datatype in Python.
Step1.
Step2. Create a new folder where you want to save all your Python Programs
Eg:
104
Step3. Open Visual Studio Code Editor
105
Note: If the Python extensions are already installed, they will be loaded, otherwise install them when
suggested.
106
Step7. To run the program
Output:
Note: Notice that the Visual Studio Code Editor internally uses the Python Installation Location to use
the python.exe file to run our Python file first.py
107
Note: If we give a high index than the no. of elements, we get: IndexError: list index out of range
Output:
108
Program: Lists Demo2
Note: Remember that we get only the copy of the list (ages) but not its address.
Output:
109
It is like substring() in Java Strings
Output:
Output:
110
Output:
del holidaySpots[0:10]
with step value: del holidaySpots[0:10:2]
holidaySpots.clear()
Mapping Collection
Keys values
sellername
village/area
mandal/town
District
State
Phonenumber
111
Output:
: “ ”
Output:
112
Output:
Output:
Output:
Note: We can check whether an element is a member of a list or not using “in” and “not in” operators
DATAPRO COMPUTERS 113
113
Output:
Note: i ing a new name to an existing list is called “aliasing” he new name is called “alias” name
Output:
Note: If the programmer wants two independent lists, then he/she should go for cloning/copying
instead of aliasing.
114
Output:
Note: max() and min() can’t be applied for nested lists e en though they are of same type
Output:
Output:
Note:
Assume that it is a list of movie heroes voted by 100 students. We want to find out how many
times each hero name is repeated.
We can use a set type to store all the unique elements say: 10 hero names.
Then we can use count() inside a loop
115
Note: List comprehensions represent creation of new lists from an iterable object that satisfies a given
condition.
Output:
Note: List comprehensions contain very compact code usually a single statement.
Output:
Note: Get squares of integers from 1 to 20 and take only the even numbers from the result.
Output:
116
Note: convert each word into uppercase and store the resultant words into another list
Output:
Lists vs Tuples
• You can't add elements to a tuple. Tuples have no append or extend method.
• You can't remove elements from a tuple. Tuples have no remove or pop method.
• tuples use parentheses, whereas lists use square brackets.
Note: Notice that we use parenthesis for tuples whereas we use square brackets for lists.
Output:
117
Note: In the above two examples, all the tuples must contain same no. of elements.
Output:
118
Program: To find the first occurrence of an element in a tuple, also covers converting list to tuple
Output:
Output:
119
Output:
Step1. 1st of all copy the elements of “x” from 0th position to pos-1 position into “y”
Step3. Concatenate the remaining elements from pos-1 till the end of “x” to the new tuple “y” the
whole tuple can be stored again with the old name “x”
120
Note: A tuple can contain even a single element. Eg: t1 = (40,). Note that comma is required. Otherwise
it would be treated as in integer.
Output:
Note: If we convert a string to tuple, then it is split into individual characters, but not as a single string:
121
Output:
Output:
Note: Dictionaries are used to maintain data in the form of Key-Value pairs
Examples:
Key Value
101 Dennis Ritchie, C, 1972
102 James Gosling, Java, 1991
MyCart Python Programming Book, Lenovo Ideapad laptop, Running Shoe
9999999999 Missed call 5 times
Username mark
Videotime 300 seconds
Likes 100
Comments 20
122
Program: Dictionary Ex2 – List as a value
Note: To modify/update a key, just assign a new value by mentioning its key.
Note: the last one is equivalent to appending a new key-value pair to the existing dictionary.
: ’ ;
’
123
Note: if we say players[name] and if the key is not found, then, we get error
Output:
124
Output:
Output:
Note: When we have two lists, it is possible to convert them into a dictionary.
Output:
125
Note: If we have less no. of values than the no. of keys, then the keys which do not have corresponding
values would be ignored. i.e., if we add one more key in the above example without its pair in the 2 nd list
then the length of the dictionary would be still 4.
Output:
Note: Recollect that the elements of a dictionary are not stored in the given order. Sometimes it may be
a problem. Eg: We want to store employees details depending on their seniority or salary scale. Senior
most employees’ data should be at the beginning of the database.
An ordered dictionary is the one which will keep the order of the elements in the given order.
Note: Refer to Lists Demo-6. Notice that the key-value pairs and not stored in the given order.
126
Output:
Note: Similar to set, there is something called as frozenset. The main difference is that the elements of
a set datatype can be modified, whereas the elements of a fronzenset cannot be modified
127
Note: To add a single element, use the add() but not append()
Note: Sometimes it is useful to know which elements are repeated in two lists. Eg: there is a scholarship
exam for which a group of students enrolled in a college. There is another scholarship exam for which
another group of students got enrolled. Now we want to know the names of students who have
enrolled for both the scholarship exams so that we can restrict them to take only one exam.
Output:
128
Output:
129
Chapter-8: Functions
What is a Function
Types of Functions
1. Library functions
2. User-defined functions
Program: Demo on creating a docstring in a function and referring to it while calling the function
130
In the Python prompt, invoke the function.
Note: In “ ” “Ja a” etc., any function can return only one value directly. But in Python a function can
return more than one value at a time.
Output:
Note: If we receive multiple values into a single variable, then that variable would be a tuple. We can
use index to get each of the results or we can iterate the values using a for loop.
131
Output:
It means:
• We can assign a function to a variable
• It is possible to define one function inside another function
• We can pass a function as an argument to another function
• It is possible that a function can return another function
Ex1:
Output:
Ex2:
132
Program: Nesting of functions
Output:
Note: test without using parenthesis while passing the “question” function
print(wish(question)))
Output:
133
Output:
In call by value: a copy of the actual argument is passed to the called function and any modifications to
the formal arguments will not reflect the actual argument.
In call by reference: Here we send the reference/memory address of the actual argument to the called
function, the actual argument is modified by the called function through memory address
(dereferencing) and hence the modified value will reflect/change the actual argument.
The following programs demonstrates the style of function call mechanisms in Python
Output:
134
Program: Passing a list to a function and modifying it – Demo1
Output:
Note: Here we shall demonstrate that a new object inside the function does not modify outside/original
object
Output:
When we call a function we may pass data alues to that function hese alues are called as “actual
arguments” In Python these can be classified into 5 types:
• Positional arguments
• Keyword arguments
• Default arguments
• Variable length arguments
• keyword variable length argument
Note: These are the arguments passed to a function in correct positional order. Here, the no. of
parameters and their positions in the function definition should match exactly with the no. and position
of the arguments in the function call.
135
Output:
Note: These are very heavily used in Python Data Analytics and Visualizations/Charts
Note: Here we need not pass the arguments in the same order if we mention the correct parameter
name to which it should be passed to
Output:
Note: These too are very heavily used in Python Data Analytics and Visualizations
Output:
136
Output:
Note: hese are represented in Ja a using elipses(…) and it # Net using “params” keyword
Note: the ariable length parameter is written with a “*” symbol before it in the function definition as:
Output:
Output:
137
Note: The variable length argument parameter must be the last parameter the function definition.
“*”
Output:
“*”
Output:
138
To get the output as per expectation – i.e., each element on a separate line:
Output:
Note: A keyword variable length argument is an argument that can accept any no. of values provided in
the format of keys and values. We can declare it with “**” symbols before the parameter name as:
Output:
139
: “**” -value pairs can be passed
Output:
Note: Here, only the access is allowed, modification is not allowed. To modify it we have to redeclare
it inside the “ ”
Note: If global variable and local variable have same name, then the local variable has higher priority
inside the function o o erwrite the priority we can use the “globals()” function
Output:
140
Program: Demo on recursive functions Ex1
Output:
Output:
lambda operator or lambda function is used for creating small, one-time and anonymous function
objects in Python.
lambda operator can have any number of arguments, but it can have only one expression. It cannot
contain any statements and it returns a function object which can be assigned to any variable.
141
Note: They are used very heavily in Data Analytics
Output:
Note: Notice that the lambda expression has removed “ ” keyword, “ ” keyword and name of
the function. However, we have to use a new keyword: “lambda”
Output:
print(type(sum))
Output:
142
Output:
Output:
143
Syntax:
Output:
Note: the whole point of anonymous functions is: what is there in the name, all that matter is its
functionality.
Output:
144
Note: Here, each i^th element of list_a and list_b will be passed as arguments to the lambda function.
Output:
Note: The reduce() reduces a sequence of elements into a single value by processing the elements
according to a function supplied.
Note: First time, the first two values are received into the x and y respectively. Then onwards the
“x” .
Output:
If the above import is not working try importing the “reduce()” from the “functools” module
145
Output:
Note: reduce() can also be combined with operator functions to achieve the similar functionality as with
lambda functions and makes the code more readable.
Output:
Note: reduce() stores the intermediate result and only returns the final value. Whereas, accumulate()
returns a list containing the intermediate results.
Note: into the accumulator "x" the following values are stored. 1st 1 is stored, then 1+2 -> 3 is stored,
then 3+3 -> 6 is stored so on...
Output:
146
Note: A decorator is a function that takes a function as its only parameter and returns a function. This
is helpful to “ ” .
Without Decorator
Output:
ssume that we ha e 100’s of such functions where common code is present (as we ha e in this
example, both the functions have common code of getting time(start time & end time), calculating
difference and printing)
With Decorator
147
Note: When we call a function, which has a decorator, 1st the decorator function gets invoked, which in
turn invokes the function being decorated
Note: func.__name__ : gives the name of the function currently being executed.
Output:
• Code duplication
• Cluttering (filling with unnecessary code) main logic of a function with additional functionality
(i.e., timing in our example)
Without decorator
148
Output:
With decorator
Output:
When a program is executed in Python, there is a special variable internally created by the name
‘ name ’ his ariable stores information regarding whether the program is executed as an
individual program or as a module.
When the program is executed directly the Python interpreter stores the alue ‘ main ’ into this
variable. When the program is imported as a module into another program, then the Python interpreter
stores that module’s name into this variable.
149
Output:
Step2. Create another file program2.py (make sure that both the files are in the same location)
Output:
Note: he imported module’s global code gets executed 1st and the functions are executed when they
are invoked from the main program.
150
Chapter-9: Modules & from keyword
What is a module?
Ans: A module represents a group of related classes, functions and variables. When a module is
developed it can be reused in any program that needs that module.
In Python, we have several built-in modules like sys, io, datetime, time, socket, threading, xml, json,
email, array, calendar etc. We can create our own modules as well, and these modules can be used by
other team members of the project or in other projects as well. So, modules make software
development faster.
Step1. 1st create a file rajudiwalimodule1.py and save it some location, say: E:\team\fruit
Step3. Now using the above function from another file – useModule1.py, this file can be saved
anywhere, say: D:\Raju\MyPythonPrgs\MyModulePrgs
Reason for error: because the imported file is not present in the current working directory
C:\Users\bvraju\AppData\Local\Programs\Python\Python37\Lib
151
To know this location:
No!
Module Vs Package
: “from”
Note: The from keyword is used for importing a specific variable, class, or a function from a
module/package.
Note: Here “sys” is the name of the module and “ ersion” is a predefined ariable in it
:“ ”
152
Method1:
Output:
Method2:
Output:
Notice that myFun2() is not accessible as we have imported specifically myFun1() only
153
Chapter-10: Command Line arguments
These are the arguments that we pass to the program/main function from the command line/command
prompt.
Program: Passing any number of command line arguments and using them
Step1.
154
Note: “args” would be a list type
Step2.
155
Chapter-11: OOP Basics using Python
Introduction to OOP
Def of OOP:
Object-oriented programming is a programming paradigm based on the concept of "objects", which can
contain data and code. A feature of objects is that an object's own procedures can access and often
modify the data fields of itself.
Note: OOP (Object Oriented Programming) is used to model real world things as objects
Ex.s: A Car, An Employee, A Student, A College, A Product etc.
Here each object has its own data and functionality instead of global data and global functions unlike
“ ” .
Program: Demo on creating a class, some member functions, creating an instance and invoking the
member functions
Step1.
156
Note: he ariables “firstName” and “lastName” are known as instance variables as every instance of
the Student class contains a separate copy of the instance variables.
Output:
Note: the “self” is equi alent to “this” pointer reference used in ++ Ja a # Net It contains the
memory address of the current object.
Note: We can replace “self” with something else as well eg: “datapro”
157
The __init__() method name has two underscores before and after his indicates that this method’s
name is internally defined and we cannot call this method explicitly.
Output:
158
Output:
Output:
159
Output:
Output:
Note: __str__() is a standard Python class method which returns a human-readable string for an object.
Note: It is equivalent to overriding toString() method in Java/C#.Net
Note: In Python, the variables which we write inside a class are of two types:
• Instance variables and
• class/shared variables
160
Note: Till now we have been dealing with instance variables, in this example we shall deal with class
variables.
Note: unlike instance variables, class variables are the ones which have only a single copy for all the
instances of the class. All the instances share the same class variable.
Output:
161
Output:
Note: getter/accessor methods are classified into instance methods category. Similarly
setter/mutator methods are also classified into instance methods category.
• Class methods: These methods act at class level. These methods are used to access the data
which is common to all the instances of a class. These methods are usually invoked via
162
classname.methodname(). You will understand it in the upcoming examples.
• Static methods: We need them when the processing is at the class level but we need not involve
the class or instances. You will understand it in the upcoming examples.
Output:
Note: To create a static method that calculates the square value of a given number
Output:
Note: A static method cannot modify/access either an instance variable or a class variable.
Note: a class created inside another class is known as an inner/nested class. Inner classes can be used
when we want to subgroup the data of a class.
163
Output:
164
Chapter-12: Inheritance and Polymorphism
What is Inheritance
Output:
Note: Like in Java and C#.Net, in Python too all classes are implicitly derived from “ j ” lass.
165
Output:
Note: In Python, there is no method overloading unlike in C++, Java and C#.Net because in Python we
don’t mention the datatypes explicitly for the function parameters.
Output:
• Single Inheritance
DATAPRO COMPUTERS 166
166
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
167
Hierarchical Inheritance
Hybrid Inheritance
168
Program: Demo on Multiple Inheritance
Output:
169
Output:
Output:
170
Output:
Runtime Polymorphism
It uses method overriding where even though the method name and parameters passed is similar, the
behavior is different based on the type of object
171
Ex3: Printers
172
So, concept remains the same, how we implement/code it in Python - is different.
Polymorphism
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It means one thing
behaving in different forms.
173
Program: Polymorphism in built-in functions
Output:
174
Another way:
Output:
175
Output:
Note: Notice that if we don’t o erride the draw() in any of the subclasses the base class implementation
gets invoked.
Note: now it becomes mandatory to implement the draw() method in its subclasses.
176
Operator Overloading in Python
++ #. ( “ ” ). The
concept is same in Python too, however the way we implement it is completely different in Python.
Operator overloading is the concept of applying operators on other than primitive types / numerical
types. In other words: If any operator performs additional actions other than what it is meant for, it is
called as operator overloading.
Operator overloading is one form of polymorphism where an operator can perform different tasks.
Program: Demo1 on Operator Overloading – addition operator (+) on Python built-in types
Output:
Note: When we apply any operator on user-defined object, we have to provide some special methods
which get invoked automatically – known as magic methods
The following is the list of important operators and their corresponding internal methods that can be
overridden to act on user-defined objects:
177
Program: Demo2 on Operator Overloading - addition operator (+) on user-defined objects
Output:
178
Note: Notice that the Python interpreter could not know what to do
Output:
Output:
179
Output:
Note: In the above example, the requirements of all the 3 objects are same, i.e., to calculate square.
But sometimes the requirements of the objects will be different. E.g.: In the previous example if the 1st
object(obj1) wants to calculate square, the 2nd object (obj2) wants to calculate square root and the 3rd
object(obj3) wants to calculate cube. In such case how do we write the calculate() in MyMaths class?
One solution is write three different methods like calculateSquare(), calculateSquareRoot() and
calculateCube() in MyMaths class, then all the 3 methods are available for all the three objects which
is not necessary. A better solution is abstract methods
Note: An abstract method is a method whose action is redefined in the subclasses as per the
requirement of different subclass objects
Note: If a class has at least one abstract method, the class becomes abstract class
180
Output:
Note: Interface is like an abstract class, except that an interface contains only abstract methods whereas
an abstract class contains both abstract methods and concrete methods.
Note: In languages like Java and C#.Net, interfaces are created using interface keyword but in Python
an interface is created as an abstract class only. The interface concept is not explicitly available in
Python. I have mentioned it just for the sake of Java, C#.Net Programmers.
181
Output:
182
DATAPRO COMPUTERS 183
183
Chapter-13: Exception Handling
Introduction
Exception Handling means Handling runtime errors. When an exception occurs, program gets
terminated abnormally. To avoid abnormal program termination, we have to handle the exceptions.
Examples of Exceptions:
These are not the mistakes in the program (by the Programmer), but the program/programmer should
anticipate the possible problems and handle them.
What should we do when an exception occurs (what are the available options?)
• Graceful exit (tell the user want went wrong and then stop the program)
• Skip and continue (skip the related code and continue execution of the program)
• Rectify and continue (rectify the problem and continue execution)
Note: One more advantage of Exception Handling is we have separate blocks which contains the
exception prone code, and separate blocks for handling the code, so maintenance becomes easier
Output:
Case1: if input is 4 and 2:
184
Case2: if input is 4 and 0:
Note:
Just except: means any type of exception can be handled
Note: Recollect that the statements inside the finally block are executed irrespective of whether an
exception is raised or not. This ensures that all the opened resources like files / databases / sockets
connections are properly closed.
185
Output:
Verify:
186
Output:
Note: The concept is similar to that of Java and C#.Net, main difference is instea “ ”
“ ”
Output:
187
DATAPRO COMPUTERS 188
188
Chapter-14: File Handling
Note: By default, the open() function opens the file in read mode.
readlines() returns a list of strings/elements/lines
Output:
189
Program: File Handling – To know whether a file exists or not
Output:
If file exits:
190
Step1.
: “ ”
Output:
Step2. Now open the file - pythondemo.txt (from the location: e:\team\fruit)
191
r+ (read and write) To read and write - both operations are allowed. The file pointer is placed at
the beginning of the file.
a+ (append and read) To append and read data. Here the file pointer would be positioned at the
end of the file if the file already exists; otherwise, a new file gets created.
x (exclusive) To open the file in exclusive creation mode. The file creation fails if the file
already exists.
Program: File Handling - to append data to an existing file and then displaying the entire file
Step2. Write the following program to append some content to the above file
192
: “ ”
Note: he abo e “with” statement will automatically close the file after the nested block of code.
Output:
Program: File Handling – To count number of lines, total words and number of words in each line in a
text file
Output:
If input is:
193
Output:
Program: File Handling – Working with Binary Files – read and write images/audio files
Serialization is the process of converting a data structure or object state into a format that can be
stored (for example, in a file or memory buffer, or transmitted across a network connection link) and
get/retrieved later in the same or another computer environment.
The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is
also called inflating or unmarshalling).
So essentially storing an object to a file (or sending it to a network) is called Serialization and retrieving
it back is called Deserialization.
194
In Python, we use the pickle module to accomplish it.
Note: It’s better to put the “ tudent” class inside some user-defined module. So that it can be reused in
both Serialization and De-Serialization programs
Output:
Note: ’ .
Note: We can notice that only text data is readable. Also notice that it contains not only data but also
the field names and class name. This information is required during the De-Serialization process.
195
Note: This class name and these field names must exactly match with that of the previous example.
Output:
Note: create a user-defined module – StudentClassFile.py which contain the Student class as created in
the earlier programs. We are going to use this module in the following two programs.
Output:
196
Program: File Handling – Reading Records in Binary Mode
Output:
Step1.
197
Note: ZIP_DEFLATED: The numeric constant for the usual ZIP compression method. No other
compression methods are currently supported.
:“ ” directory
Output:
Note: Now delete the original folder – CSSFiles, as we are going to get it back via extraction/unzipping
Step1.
Step3. Verify:
198
Program: File Handling - To know the current working directory
Output:
Program: File Handling - To display all contents of the current directory and its sub-directories as well
Note: If we replace dirpath, dirnames, filenames with single variable, entire information is stored in it.
But if we replace dirpath, dirnames, filenames with two variables then error.
Output:
199
Program: File Handling - To create a sub directory
Output:
Verify:
200
Note: If the directory is not empty:
Output:
201
Chapter-15: Turtle Graphics Programming
Introduction
“ ” is a pre-installed Python library that enables users to create pictures and shapes by providing them with
a virtual canvas. The onscreen pen that you use for drawing is called the turtle and this is what gives the library
its name.
The turtle Library is primarily designed to introduce children to the world of programming. With the help of
Turtle's library, new programmers can get an idea of how we can do programming with Python in a fun and
interactive way.
202
Pen Control methods
Drawing State
Color control
Filling
Visibility
Appearance
203
Event methods
Methods of TurtleScreen/Screen
Window control
Animation control
204
Settings and special methods
Input methods
205
Program: Creating a Canvas / Drawing window
Step1.
(OR)
Step1.
206
(OR)
207
DATAPRO COMPUTERS 208
208
Program: To move right and left
Step1.
209
Program: To draw a Square
Step1.
210
Method2:
Step1.
211
Program: To draw a Rectangle
Step1.
212
Program: Drawing a Circle
Step1.
213
Program: To draw a semicircle
Step1.
Step1.
214
Program: Drawing a Dot
Step1.
Step2.
Step1.
215
Step2. Run the program
Step2.
216
Step3. Run the program
Step1.
217
Program: Fill color
Step1.
218
Program: To draw Polygons
Step1.
219
Hexagon:
numberOfSides = 6 #Hexagon
Octagon:
numberOfSides = 8 #Octagon
220
Program: To draw a star
Step1.
Step2.
221
DATAPRO COMPUTERS 222
222
Chapter-16: Regular Expressions in Python
Introduction
A Regular Expression is a string that contains special symbols and characters to find and extract the
information needed by us from the given data/string. A Regular Expression helps us to:
Python provides “ ” that stands for Regular Expression. This module contains methods like:
compile(), search(), match(), findall(), split() etc which are used in finding the information in the data.
Output:
Note: Notice that search() gives the 1st occurrence value only
223
Output:
Output:
Note: match() returns the resultant string only if it found at the beginning of the string
Output:
224
Program: Regular Expression Ex5 – split()
Note: split(), splits the given string into pieces/tokens according to the regular expression and returns
the tokens as a list.
Output:
Note: sub() is used to find a string and replace it with a new string
Output:
225
Sequence Characters in Regular Expression
Character Description
\d Represents any digit (0-9)
\D Represents any non-digit
\s Represents white space (\n, \t, \r, \f, space, tab
space)
\S Represents non-white space character
\w Represents any alphanumeric character
\W Represents non-alphanumeric
\b Represents a space or special symbol around
words
\A Matches only at start of the string
\Z Matches only at end of the string
“*”
[\w]* represents 0 or more alphanumeric characters
Requirement: o retrie e all words starting with “a” in the given string
Output:
Note: Notice that we got all words not only starting with “a” but also words which ha e “a” in the
middle of any word
Solution:
226
Output:
Requirement: To retrieve all words enclosed within single quotes in the given string
Output:
227
Output:
Output:
Output:
228
Program: Sequence Characters in Regular Expression – Ex6
Output:
'\Ao[\w]*'
Note: In RE, some characters represent more than one character to be matched in the string. Such
characters are called quantifiers.
Character Description
+ 1 or more repetitions of the preceding RE
* 0 or more repetitions of the preceding RE
? 0 or 1 repetitions of the preceding RE
{m} xactly “m” occurrences
{m, n} rom “m” to “n”
“m” defaults to “0”
whereas “n” defaults to “infinity”
229
Output:
Output:
230
Output:
Output:
Character Description
\ Escape special character nature
. Matches any character except new line
^ Matches beginning of a string
$ Matches end of a string
[…] Denotes a set of possible characters
[^…] Opposite to the above
(…) Matches the RE inside the parentheses and the
result can be captured
R|S Matches either R “R” or R “ ”
231
Output:
Note:
Output:
Requirement: Whether the strings starts with “He” and ends with “er”
DATAPRO COMPUTERS 232
232
Note: he result would be “None” or a “Match”
Requirement: using “I N R ”
Output:
Requirement: o retrie e students’ marks and their names separately from a gi en string
Output:
233
Program: Using Regular Expressions on Files – Ex1
Note: We can use RE not only on individual strings, but also on files where huge data is available.
The Program:
Output:
234
Program: Using Regular Expressions on Files – Ex2
Requirement: to retrieve only employee ids and their corresponding salaries data
Output:
235
Requirement: To retrieve employees names and corresponding salaries from the HTML file
Output:
236
Chapter-17: Date & Time
Note: he “epoch” is the point where the time starts. For Unix based system, the epoch is 00 hours of
January 1st 1970
Output:
Output:
237
Program: Finding current Date and Time
Output:
Output:
Note: we can create “datetime” class object by combining date class object and time class objects using
combine()
Output:
238
Formatting Date & Time – codes
%z UTC offset in the form +HHMM or -HHMM (empty string if the the object
is naive).
239
Code Meaning Example
%U Week number of the year (Sunday as the first day of the week) as a zero 39
padded decimal number. All days in a new year preceding the first
Sunday are considered to be in week 0.
%W Week number of the year (Monday as the first day of the week) as a 39
decimal number. All days in a new year preceding the first Monday are
considered to be in week 0.
Output:
Output:
240
Program: Formatting Time
sOutput:
Program: To accept a date from the keyboard and display the day of the week
Output:
241
Output:
Output:
242
Output:
243
Output:
Note: we shall store a group of dates into a list and then apply list’s sort() method
Output:
Program: ’ x
244
Output:
ame as that of pre ious programs’ output only difference is each line would be displayed with 5
seconds delay
:K ’
Note: Many ID ’s like Net eans ID for Ja a programming ndroid tudio ID for ndroid pp
Development shows the amount of time it took for the completion of execution of the program, Let’s
see how the calculations are made
Note: Python pro ides two functions: perf counter() and process time() of “time” module to measure
the time difference between two points in a program.
245
Output:
: “ ” – Ex1
Output:
: “ ” – Ex2
246
Output:
: “ ” – Ex3
Output:
247
DATAPRO COMPUTERS 248
248
Chapter-18: Miscellaneous topics
Program: Demo on enumerate() to get both the indices and elements from a list
Ans:
1. In Python, everything is an object – even integers and strings – look at the proof
2. All data is stored on Heap memory (also known as Pri ate Heap pace) (unlike in “ ” Language)
3. All function calls and local variables are stored in Stack memory
Whenever there is no reference variable to any object in heap memory, it would be garbage collected or
marked for garbage collection.
Output:
249
→ o if we do assignment then multiple ariables point to the same memory location (unlike in “ ”
Language)
→So, notice that if values are same, then multiple variables point to the same memory location.
Output
Modification:
250
Output:
Garbage Collector
251
Namespaces in Python
• Local
• Enclosed (variables declared in outer functions can be accessed inside their inner functions)
(they are neither local variables nor global variables)
• Global
• Built-in (predefined variable names of Python like __name__, __file__)
To know which variables and function names are present in the current scope
252
Demo on using __file__ built-in variable name
Output:
Note: The LEGB Rule applies when variables in two different scopes have same names.
253
Output:
nonlocal keyword
Note:
If we want to modify a non-local variable inside a nested function, then it must be declared with
nonlocal keyword
254
Step4. Re-Run the Program
Output:
Note: Recall that A function defined inside another function is known as a nested/inner function and
inner functions can access variables of the enclosing scope i.e. variables of their outer functions.
A closure is basically a nested function which has access to a variable of its enclosing function that has
finished its execution - these are very heavily used in decorators concept.
255
Step2. Run it
Output:
Step4. Re-run it
Output
Generators in Python
DATAPRO COMPUTERS 256
256
A generator is a function that returns an iterable object which can be used to iterate/loop over the
elements, one at a time.
(OR)
A Python generator is a function that produces a sequence of results. It works by maintaining its local
state (values in its variables), so that when the function is resumed exactly where it left off, when called
subsequent times.
Note: If a function contains at least one yield statement, it becomes a generator function.
Output:
Note:
“ “ “ ”
Both “return” and “yield” will return some value from a function.
257
Note:
Q: Is Multiple Inheritance available in Python
Output:
Base2.fun(d)
258