You are on page 1of 259

Python

&
Programming Material
Course: Python Programming Basics
(Duration: around 45 Hours)

For absolute beginners in Programming

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

Problem Solving Assignments

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

Chapter-2 (Introduction to Programming using Raptor Tool)


1. Introduction to Programming
2. What is Raptor
3. Download and Install Raptor Tool
4. Example1: Sum of two numbers
5. Example2: To check whether the given number is even number or odd number (conditions)

Chapter-3 (Introduction to Python Programming)


1. Why the name Python?
2. How to install Python
3. Program: To display welcome message on the screen
4. Program: Demo on Numbers and Arithmetic
5. Program: Demo on Exponential operator
6. Program: Comments and variables, sum of two numbers
7. Program: Taking input from the user
8. Program: Typecasting demo
9. Program: To use built-in mathematical function and to show all the built-in functions in python
10. To show help on any built-in function
11. Help mode
12. Demo on importing a module and using it, also covers giving alias names to built-in functions in
modules
13. Demo on how to save and run python files
14. How to run a Python program without opening the python shell every time we want to run the
program
15. Different ways of executing a Python Program
16. Built-in Datatypes in Python
17. Program: Demo on complex datatype
18. User-defined datatypes
19. Keywords/reserved words in Python
20. Operators in Python
21. Operator Precedence
22. Operator Associativity
23. Program: Demo on exponential operator - to prove its associativity
24. Some Assignments

Chapter-4 (Control Structures)


1. Introduction to Control Structures
2. Program: Demo on “if”
3. Program: Demo1 on “if” and “else”
4. Program: Demo2 on “if” and “else”
5. Program: Demo on “elif” and string comparision
6. Program: Demo on logical operators (“and” and “or”)

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

Chapter-5 (String Handling)


1. Program: Strings demo1
2. Program: String Concatenation
3. Program: String Concatenation Ex2
4. Program: Printing formatted string using %
5. Program: Printing multiple values together using place holders and format()
6. Program: String indexing
7. Program: String library functions – demo
8. Program: Evaluating an expression entered from keyboard
9. Program: To nullify the effect of escape characters - demo
10. Program: Demo on accessing each element of a string in forward and reverse orders using while
loop
11. Program: Demo on String slicing
12. Program: Demo on Repeating the strings
13. Program: Demo on checking membership
14. Program: Demo1 on Comparing strings
15. Program: Demo2 on Comparing strings

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

Chapter-7 (Lists, Tuples, Dictionaries & Sets)


1. Lists Introduction
2. Python Programming using Visual Studio Code Editor
3. Program: Lists demo1
4. Program: Lists demo2
5. Program: Lists demo3 - slicing
6. Program: Lists demo4 – slicing ex2
7. Program: Lists demo5– inserting, sorting, reversing, removing
8. Program: Lists demo6 – dealing with mapping collection
9. Program: Lists demo7 – nesting of lists
10. Program: List of Lists and “for” loop
11. Program: To convert the generated values using range() into a list
12. Program: Concatenation of two lists
13. Program: Repetition of lists
14. Program: Membership in Lists

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__

Chapter-9 (Modules & from keyword)


1. What is a module?
2. Creating and using Modules in Python
3. Modules Vs Packages
4. from keyword demo1
5. from keyword demo2

Chapter-10 (Command Line arguments)


1. Program: Passing two command line arguments and using them
2. Program: Passing any number of command line arguments and using them

Chapter-11 (OOP Basics using Python)


1. Introduction to OOP
2. Program: Demo on creating a class, some member functions, creating an instance and invoking
the member functions
3. Program: Constructor Ex1
4. Program: Constructor Ex2 – with default arguments
5. Program: Demo on private data members
6. Program: To print an object directly
7. Program: Instance variables/fields and static variables/fields demo
8. Types of methods in Python
9. Program: Class Methods Demo

DATAPRO COMPUTERS 6

6
10. Program: Static Methods Demo
11. Program: Inner classes demo
12. Some assignments

Chapter-12 (Inheritance and Polymorphism)


1. Program: Demo on Inheritance
2. Invoking the base class constructor
3. Types of Inheritance in Python
4. Program: Demo on Multiple Inheritance
5. Program: Demo on Multi-level Inheritance
6. Program: Demo on Hierarchical Inheritance
7. Program: Demo on Hybrid Inheritance
8. Polymorphism
9. Program: Polymorphism in Operators
10. Program: Polymorphism in built-in functions
11. Program: Polymorphism in user-defined methods
12. Program: Polymorphism with Inheritance
13. Program: Demo on NotImplementedError() – without using it
14. Program: Demo on NotImplementedError() – with using it (abstract methods in Java/C#.NET)
15. Operator Overloading in Python
16. Program: Demo1 on Operator Overloading – addition operator (+) on Python built-in types
17. Magic Methods in Python
18. Program: Demo2 on Operator Overloading - addition operator (+) on user-defined objects
19. Program: Demo3 on Operator Overloading – overloading (>) operator
20. Abstract methods and their need
21. Program: Demo1 on Abstract method and abstract class
22. Program: Demo2 on Abstract method and abstract class
23. Some assignments

Chapter-13 (Exception Handling)


1. Program: Exception Handling in Python - using try-except blocks
2. Program: Demo on try-except blocks
3. Program: To handle different types of exceptions in different ways
4. Program: Demo on finally block
5. Program: Demo on User-defined exceptions

Chapter-14 (File Handling)


1. Program: File Handling – reading lines from a text file
2. Program: File Handling – To know whether a file exists or not
3. Program: File Handing – writing
4. Program: File Handling - Writing a list of lines to a file at once
5. The File Opening Modes
6. Program: File Handling - to append data to an existing file and then displaying the entire file
7. Program: File Handling – usage of “with” keyword
8. Program: File Handling – To count number of lines, total words and number of words in each line
in a text file
9. Program: File Handling – Working with Binary Files – read and write images/audio files
10. Serialization and Deserialization
11. Program: File Handling – Serialization of an object in Python
12. Program: File Handling – Deserialization of an object in Python

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

Chapter-15 (Turtle Graphics Programming)


1. Introduction
2. Turtle Motion methods/functions
3. Pen Control methods
4. Turtle state methods
5. Event methods
6. Special Turtle methods
7. Methods of TurtleScreen/Screen
8. Program: Creating a Canvas / Drawing window
9. Program: To move forward and backward
10. Program: To move right and left
11. Program: To draw a Square
12. Program: To draw a Rectangle
13. Program: Drawing a Circle
14. Program: To draw a semicircle
15. Program: Circle with steps (Hexagon)
16. Program: Drawing a Dot
17. Program: Changing the screen size and screen background color
18. Program: Adding image on the screen and setting screen title
19. Program: Changing pen size
20. Program: Fill color
21. Program: Drawing Polygons
22. Program: To draw a star

Chapter-16 (Regular Expressions in Python)


1. Introduction
2. Program: Regular Expression Ex1 - using compile(), search() & group()
3. Program: Regular Expression Ex2 - search()
4. Program: Regular Expression Ex3 – findall()
5. Program: Regular Expression Ex4 – match()
6. Program: Regular Expression Ex6 – split()
7. Program: Regular Expression Ex 7– sub()
8. Sequence Characters in Regular Expression
9. Program: Sequence Characters in Regular Expression – Ex1
10. Program: Sequence Characters in Regular Expression – Ex2
11. Program: Sequence Characters in Regular Expression – Ex3
12. Program: Sequence Characters in Regular Expression – Ex4
13. Program: Sequence Characters in Regular Expression – Ex5
14. Program: Sequence Characters in Regular Expression – Ex6
15. Quantifiers in Regular Expression

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

Chapter-17 (Date & Time)


1. Program: The beginning of a time
2. Program: Finding current Date and Time
3. Program: Demo on now()
4. Program: Combining Date and Time
5. Formatting Date & Time – codes
6. Program: Demo on Formatting Date – ex1
7. Program: Demo on Formatting Date – ex2
8. Program: Formatting Time
9. Program: To accept a date from the keyboard and display the day of the week
10. Program: Finding difference between two dates
11. Program: Finding difference between two times
12. Program: To display the next 30 days
13. Program: Comparing two dates
14. Program: Sorting dates
15. Program: Delaying program’s execution
16. Program: Knowing program’s efficiency
17. Program: Using “calendar” module – Ex1
18. Program: Using “calendar” module – Ex2
19. Program: Using “calendar” module – Ex3

Chapter-18 (Miscellaneous topics)


1. Program: Demo on enumerate() to get both the indices and elements from a list
2. Program: Demo on generating random numbers
3. Program: Demo on Converting the first letter of a string to uppercase
4. Program: Demo on picking a random item from a list or tuple?
5. How is Memory Management done in Python
6. Namespaces in Python
7. Demo on Enclosing Scope
8. nonlocal keyword
9. Demo on Python Closures
10. Generators in Python
11. Program: Demo on generators
12. What is the difference between “return “ and “yield”
13. Program: Demo1 on Multiple Inheritance in Python
14. Program: Demo2 on Multiple Inheritance in Python – no ambiguity unlike in C++

DATAPRO COMPUTERS 9

9
DATAPRO COMPUTERS 10

10
Chapter-1: What is Python and why is it important today

Python is a general purpose mul paradigm ery


high le el programming language created by uido an
Rossum

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

Why should one write a Program/Code?

Ans: To create a software

DATAPRO COMPUTERS 23

23
Different Programming languages

C, C++, Java, C#.Net, Python etc.

Examples of Programs in different Programming languages

DATAPRO COMPUTERS 24

24
11

12

DATAPRO COMPUTERS 25

25
1

What is Raptor Tool

RAPTOR is a flowchart-based programming environment, designed specifically to help students visualize


their algorithms

Download and Install Raptor

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.

Step2. Save the file

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”

Enter the prompt message and variable name

Note: The prompt message must be enclosed within double quotation marks

DATAPRO COMPUTERS 30

30
nd click “Done”

It changes to:

Step5. To accept another number:

DATAPRO COMPUTERS 31

31
It changes to:

DATAPRO COMPUTERS 32

32
Step6. Now we need assignment (sum of two numbers)

or that drag and drop the “assignment” symbol

lick “Done”

It changes to:

DATAPRO COMPUTERS 33

33
Step7. Now we have to display the output:

Drag and drop the “output” symbol

Right click inside it → Edit

Here we have to combine/join/concatenate the message and the ariable using the “+” sign

DATAPRO COMPUTERS 34

34
It changes to:

Step8. To execute the flow chart

DATAPRO COMPUTERS 35

35
Click again:

DATAPRO COMPUTERS 36

36
Click again:

Notice the stored value:

DATAPRO COMPUTERS 37

37
Click again:

Notice the 2nd value:

DATAPRO COMPUTERS 38

38
Click again:

Notice the result in the output variable

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)

Step1. Create a new file


DATAPRO COMPUTERS 41

41
Drag and drop the “input” symbol and dit it

Step2.

Drag and drop the “selection” symbol

tep Right click inside the “Diamond” shape of the “selection” symbol and edit it

DATAPRO COMPUTERS 42

42
It appears as:

tep Now place the “output” symbol at both the ends

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

Why the name Python?

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

Installing Python on your Destkop

Step1. Go to python.org:

tep2 lick “Downloads” button

It would be around 28MB

tep Double lick on the setup file and click “Run”

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.

Note: Python program runs directly from the source code.

Program: Demo on Numbers and Arithmetic (using Python shell as calculator)

Note: // is for integer division

Program: Demo on exponential operator

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.

Note: while defining a variable, assigning a value is must:

Program. Taking input from the user

DATAPRO COMPUTERS 52

52
Note: Underscores are allowed in a variable name.

Program: Typecasting demo

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

Notice that we get list of available built-in functions in a module

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

Step1. Click File menu → New File

Edit it and save it

Step2. To Run:

lick “Run” menu

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:

input("Press enter key to quit...")

…so that the user can iew the result

Step2. Go to the location where we have saved the file:

Double click the file icon

Different ways of executing a Python Program

There are three ways of executing a Python program:

• Using Python’s ommand Line window


• Using Python’s IDL graphics window
• Directly from System/Command prompt

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

Step2. Now type the instructions

Note: type exit() to terminate the PVM and close the window

Method2: ’ E

Step1. To open

Step2. Now type the instructions

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

Once the code is written completely, then Run → Run Module

Method3: Directly from System prompt

Note: This is similar to as we do it for a Java Program

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

These are of five types

• 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

Program: Demo on complex datatype

Note: complex number is a no that is written in the form of “a + bj”


Here “a” represents “real part” alue “b” represents “imaginary part” alue

User-defined datatypes

In Python, arrays, classes and modules are user-defined datatypes. We shall see how to create them in
the upcoming topics

Keywords/reserved words in Python

DATAPRO COMPUTERS 60

60
Operators in Python

You have seen operators in C, C++ and Java language, similarly Python also has got some operators.

One classification is based on number of operands an operator can have


Unary operators: if an operator acts on a single operand
Binary operators: if an operator acts on two operands
Ternary operators: if an operator acts on three operands

Another classification is based on their nature:

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

Operator Example Meaning


And x and y If “x” is alse it returns “x” otherwise it returns “y”
Or x or y If “x” is alse it returns “y” otherwise it returns “x”
Not not x If “x” is False, it returns True, otherwise returns False

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.

But Exponent operator ** has right-to-left associativity in Python.

Program: Demo on exponential operator - to prove its associativity

Output:

DATAPRO COMPUTERS 63

63
Chapter-4: Control Structures

Introduction to Control Structures

Control Structures are used to control the flow of execution of the program.

These are of two types:


• Decision Control Structures
• Loop Control Structures

Decision Control Structures

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”

These are of three types:


• Uni-Directional Decision Control Structures
• Bi-Directional Decision Control Structures
• Multi-Directional Decision Control Structures

You will understand each one of them when you see the programs.

Loop Control Structures

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.

These are of two types:


• for loop
• while loop

Let’s begin with programs on Decision Control Structures.

: “ ”

Note: indentation is mandatory in the next line of “if”

Note: Parentheses are optional for the condition.

DATAPRO COMPUTERS 64

64
Output:

: “ ” “ ”

Note: indentation is mandatory in the next line of “if” and “else”

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:

Program: Demo on elif and string comparision

DATAPRO COMPUTERS 65

65
Program: Demo on logical operators

(a)

Output:

(b)

Output:

(c)

DATAPRO COMPUTERS 66

66
Output:

Program: Demo on boolean operators

: ( “ ” 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:

Note: We shall see the usage of remaining operators as we progress…

Program: “for” loop demo

he “for” loops iterate over a given sequence of elements.

Ex1:

Note: range() generates numerical values between the min(including) and max(excluding) values

Output:
DATAPRO COMPUTERS 68

68
Ex2:

Output:

Program: “ ” loop demo

he “while” loops repeat as long as a certain boolean condition is met

Note: we can’t say a++ unlike in “ ” language

Output:

Note: print() automatically places the cursor in the next line

DATAPRO COMPUTERS 69

69
Program: To display odd numbers from 1 to 10 using range()

Output:

Program: To display numbers from 10 to 1 in descending order

Output:

Program: Multiplication table

Output:

DATAPRO COMPUTERS 70

70
Program: Reversing an integer

Output:

Program: Finding whether a given number is an Armstrong number or not

Output:

DATAPRO COMPUTERS 71

71
Program: Nested Loops

Output:

Program: Multiple Multiplication tables using nested loops

Output:

DATAPRO COMPUTERS 72

72
Program: Finding factorial of a given number

Output:

Program: Finding whether a given number is a strong number or not

Output:

DATAPRO COMPUTERS 73

73
Program: Display Fibonacci Series

Output:

Program: Infinite Loop

Note: Press Ctrl + C to terminate the execution

Introduction to Jump Statements

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

In Python, these are of two types:


• break
• continue

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: To find max among a set of numbers

Program: continue statement

Note: to print all numbers between 1 to 100 except the multiple of 9

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:

Program: Finding whether a given number is a Prime number or not

Output:

DATAPRO COMPUTERS 76

76
Program: LCM of two numbers

Output:

Program: GCF of two numbers

Output:

DATAPRO COMPUTERS 77

77
Program: Pyramid Ex1

To enter a number and generate the following pyramid shape:

Requirement:

Code:

Program: Pyramid Ex2

Requirement:

Code:

DATAPRO COMPUTERS 78

78
Program: Pyramid Ex3

To display stars in Right angled triangular form

Requirement:

Code:

Program: Pyramid Ex4

Requirement:

Code:

DATAPRO COMPUTERS 79

79
Program: Demo on pass statement

Note: “ ” . It is used with “if” statement or inside a loop to


represent no operation. j ( ) “ ” .

Output:

Note: only semicolon is not allowed in place of “pass” line

:“ ”

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:

Notice that there is no difference in the 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:

Notice that now the output is different compared to that of Case3.

Program: assert statement Demo

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

To assert that the user enters a no. greater than zero:

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

Program: Strings demo1

Output:

Program: String Concatenation

Program: Strings concatenation Ex2

Note: tring and numeric types can’t be joined using “+”

Output:

Program: Printing formatted string using %

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

Note: There should not be any spaces within the braces.

Note: A better example to know its advantage:

Program: String indexing (String slicing)

Program: String library functions – demo

DATAPRO COMPUTERS 84

84
Note: Default Delimiter is space, try s.split(',') as well.

Note: The split() returns a list of strings.

Program: Evaluating an expression entered from keyboard

Output:

Program: To nullify the effect of escape characters - demo

Program: Demo on accessing each element of a string in forward and reverse orders using while loop

DATAPRO COMPUTERS 85

85
Output:

Program: Demo on String slicing

Note: s[-4:] means last four characters

Program: Demo on repeating the strings

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:

Program: Demo1 on Comparing strings

Output:

Program: Demo2 on comparing strings

DATAPRO COMPUTERS 87

87
Output:

Program: Demo on strip(), lstrip(), rstrip()

Note: These functions are used to remove unnecessary whitespaces in the beginning and/or ending of a
string

Output:

Program: Finding position of a sub string – Demo

Output:

Note: if we use index() instead of find() index() returns “Value rror” exception when the sub string is
not found.

Program: To display all positions of a substring – Demo

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:

Note: find() performs a case-sensitive search.

Program: Counting substrings in a string

Strings are Immutable

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.

Program: Strings are Immutable – Demo1

Program: Strings are immutable – Demo2, also covers id()

Program: Demo on replace()

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.

Program: Demo2 on splitting a string

Program: Demo on joining the strings

Program: Demo on changing case of a string

Program: Demo on startswith() and endswith()

DATAPRO COMPUTERS 91

91
Program: Demo on testing the nature of characters in a String

Program: Demo on sorting of strings

Note: Notice that here the original list got sorted

For Reverse sorting:

s3 = sorted(s1, reverse=True)

(OR)

s1.sort(reverse=True)

Program: Demo on f-strings

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

Creating an array and Typecodes

Syntax:
arrayname = array(typecode, [the elements])

Typecode:

Typecode Description Size in bytes


‘b’ signed byte integer 1
‘ ’ unsigned byte integer 1
‘i’ signed integer 2
‘I’ (capital i) unsigned integer 2
‘l’ (small el) signed long integer 4
‘L’ unsigned long integer 4
‘f’ floating point 4
‘d’ double precision floating point 8
‘u’ unicode character 2

: “ ”

(a) Without any import

DATAPRO COMPUTERS 94

94
(b) import method1

Output:

(c) import method2

Note: Here the advantage is we could use shortname

(d) import method3

Note: Here the advantage is no need to prefix with the module name

(e) import method4

DATAPRO COMPUTERS 95

95
Note: Here the advantage is all classes/functions of array module can be used directly without any
prefixing

Note: o list the members of a particular module g: “math” module:

import math
dir(math)

for “array” module

import array
dir(array)

Program: Creating floating type array

Output:

To print 2 digit precision only:

DATAPRO COMPUTERS 96

96
Output:

Program: Creating character type array

Output:

Program: Creating one array from another array

Output:

DATAPRO COMPUTERS 97

97
Program: Retrieve the elements of an array using array index

Note: Here range(5) is equivalent to range(0, 5) which gives 0, 1, 2, 3, 4


0 is the default min value.

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]

Note: end value is excluding

Program: Demo on slicing an array

DATAPRO COMPUTERS 98

98
Output:

Also try:

Note: get the last 8 elements, then in the original array, upto index 4 (excluding)

Program: Demo on using various methods of array class

DATAPRO COMPUTERS 99

99
Output:

:R ’ j average marks

Method1:

Output:

DATAPRO COMPUTERS 100

100
Method2:

Note: Recollect that array processing is faster. If all the elements are of same type, then better put
them in an array.

Note: split( ) returns a list of strings

Output:

: R ’

DATAPRO COMPUTERS 101

101
Output:

Program: Demo on bubble sorting of integer array

DATAPRO COMPUTERS 102

102
Output:

Program: Types of arrays

These are of two types: Single dimensional arrays, multi-dimensional arrays

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

DATAPRO COMPUTERS 103

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.

Python Programming using Visual Studio Code Editor

Step1.

Step2. Create a new folder where you want to save all your Python Programs

Eg:

DATAPRO COMPUTERS 104

104
Step3. Open Visual Studio Code Editor

Step4. Now create a Python file (first.py) in the current folder

DATAPRO COMPUTERS 105

105
Note: If the Python extensions are already installed, they will be loaded, otherwise install them when
suggested.

Step5. Install the Python Extensions

Step6. Edit the Program as follows:

DATAPRO COMPUTERS 106

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

Program: Lists Demo1

DATAPRO COMPUTERS 107

107
Note: If we give a high index than the no. of elements, we get: IndexError: list index out of range

Output:

DATAPRO COMPUTERS 108

108
Program: Lists Demo2

Note: Remember that we get only the copy of the list (ages) but not its address.

Note: append() updates/adds new elements to the list

Note: use tab for auto-completion of code.

Output:

Program. Lists Demo3 - Slicing in python

Note: to get part of a list

DATAPRO COMPUTERS 109

109
It is like substring() in Java Strings

Output:

Program: Lists Demo4 – slicing Ex2

Output:

Program: Lists Demo5 – inserting, sorting, removing and reversing

DATAPRO COMPUTERS 110

110
Output:

Note: To remove elements via slicing:

del holidaySpots[0:10]
with step value: del holidaySpots[0:10:2]

Note: To remove all elements:

holidaySpots.clear()

Program: Lists demo6 – dealing with mapping collection

Mapping Collection

Ex: Seller Registration Form at OLX App

Keys values

sellername
village/area
mandal/town
District
State
Phonenumber

DATAPRO COMPUTERS 111

111
Output:

Note: len(maps) → gives no. of elements(key-value pairs) in the mapping collection


Items() → gives both key-value pairs

Note: If we say print(maps): all they key-values pairs would be printed


Note: if key is not found, it gives error

Note: clear() is valid to remove all elements in a list as well.

Program: Lists demo7 - Nested Lists

: “ ”

Output:

Note: to print() new output on same line:

DATAPRO COMPUTERS 112

112
Output:

Program: To convert the generated values using range() into a list

Program: Concatenation of two lists

Output:

Program: Repetition of lists

Output:

Program: Membership in Lists

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:

Program: Aliasing of lists

Note: i ing a new name to an existing list is called “aliasing” he new name is called “alias” name

Output:

Program: Cloning of lists

Note: If the programmer wants two independent lists, then he/she should go for cloning/copying
instead of aliasing.

DATAPRO COMPUTERS 114

114
Output:

Program: Finding biggest and smallest elements in a list

Note: max() and min() can’t be applied for nested lists e en though they are of same type

Output:

Program: Count number of occurrences of an element in the list

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

Program: Demo1 on List comprehensions

DATAPRO COMPUTERS 115

115
Note: List comprehensions represent creation of new lists from an iterable object that satisfies a given
condition.

Without list comprehension:

Output:

With list comprehension

Note: List comprehensions contain very compact code usually a single statement.

Output:

Program: Demo2 on List comprehensions

Note: Get squares of integers from 1 to 20 and take only the even numbers from the result.

Output:

Program: Demo3 on List comprehensions

DATAPRO COMPUTERS 116

116
Note: convert each word into uppercase and store the resultant words into another list

Output:

Lists vs Tuples

Tuples are fixed size in nature whereas lists are dynamic.


In other words, a tuple is immutable whereas a list is mutable.

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

Program: Demo on Tuples

Note: Notice that we use parenthesis for tuples whereas we use square brackets for lists.

Output:

Program: Tuples – Ex2 – Tuple unpacking

DATAPRO COMPUTERS 117

117
Note: In the above two examples, all the tuples must contain same no. of elements.

Program: Demo on some basic operations of a Tuple

Output:

DATAPRO COMPUTERS 118

118
Program: To find the first occurrence of an element in a tuple, also covers converting list to tuple

Output:

Note: If not found, it gives ValueError exception.

Program: Demo on nested tuples

Note: It can represent details of a collection of employees (table in a database)

Output:

Program: To sort a tuple with nested tuples

DATAPRO COMPUTERS 119

119
Output:

Program: Inserting elements into a tuple

:R ’ . We have to follow 3 steps:

Step1. 1st of all copy the elements of “x” from 0th position to pos-1 position into “y”

Step2. Concatenate the new element to the new tuple “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”

DATAPRO COMPUTERS 120

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:

Solution: put it inside square brackets

Program: Modifying elements in a tuple

DATAPRO COMPUTERS 121

121
Output:

Program: Deleting elements from a tuple

Output:

Program: Dictionary Ex1

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

DATAPRO COMPUTERS 122

122
Program: Dictionary Ex2 – List as a value

Program: Dictionary – ex3 – A Dictionary nested inside another Dictionary

Program: Dictionary – ex4 – finding length, adding & removing

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.

: ’ ;

DATAPRO COMPUTERS 123

123
Note: if we say players[name] and if the key is not found, then, we get error

Output:

Note: If keys are duplicated alue gets updated like in “Ja a”

Program: Using for loop to retrieve elements of a dictionary in different ways

DATAPRO COMPUTERS 124

124
Output:

Program: Sorting the elements of a dictionary with Lambdas

Output:

Program: Converting Lists into Dictionary

Note: When we have two lists, it is possible to convert them into a dictionary.

Output:

DATAPRO COMPUTERS 125

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.

Program: Demo on converting a string to dictionary

Output:

Program: Demo on ordered dictionary

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.

DATAPRO COMPUTERS 126

126
Output:

Note: To concatenate two dictionaries

Program: Sets Demo

Note: A Set is a collection of unique elements

Converting a list into a Set

Program: Demo on fronzenset

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

DATAPRO COMPUTERS 127

127
Note: To add a single element, use the add() but not append()

Program: Finding common elements in two lists using sets – Ex1

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:

Note: to concatenate two sets:


set3 = set1.union(set2)

Program: Finding common elements in two lists using sets – Ex2

DATAPRO COMPUTERS 128

128
Output:

DATAPRO COMPUTERS 129

129
Chapter-8: Functions

Introduction to creating user defined functions

What is a Function

A function is a set of instructions which performs a particular task within a program.

Types of Functions

1. Library functions
2. User-defined functions

Why should we create user-defined functions?

For code reusability

Program: Demo on creating user-defined functions

Program: Demo on creating a docstring in a function and referring to it while calling the function

Step1. Write the following script:

tep2 Now run it using “Run” Menu

DATAPRO COMPUTERS 130

130
In the Python prompt, invoke the function.

Step3. In the console:

Note: Notice that it shows the documentation of the function (docstring)

(or) we can even say help(mySquare)

Program: Returning multiple values from a function Demo1

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.

Note: The values are returned as a “tuple”

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.

Program: Returning multiple values from a function Demo2

DATAPRO COMPUTERS 131

131
Output:

Functions are also objects in Python

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

We shall see examples on all of these in the upcoming topics

Program: Assigning a function to a variable

Ex1:

Output:

Ex2:

DATAPRO COMPUTERS 132

132
Program: Nesting of functions

Note: It is also known as inner functions

Output:

Program: Passing function as parameter to another function

Note: test without using parenthesis while passing the “question” function
print(wish(question)))

Output:

Program: Demo on returning a function from another function

DATAPRO COMPUTERS 133

133
Output:

Function call mechanisms in Python

In Java, C#.Net etc we have:


Call by value / Pass by value
Call by reference / Pass by reference

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.

Neither of these two concepts is applicable in Python. In Python:


• Integers, floats, strings and tuples are immutable – they behave alike
• Lists, sets and dictionaries are mutable – they behave alike

The following programs demonstrates the style of function call mechanisms in Python

Program: Passing an integer to a function and modifying it

Output:

DATAPRO COMPUTERS 134

134
Program: Passing a list to a function and modifying it – Demo1

Output:

Program: Passing a list to a function and modifying it – Demo2

Note: Here we shall demonstrate that a new object inside the function does not modify outside/original
object

Output:

Types of actual arguments

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

Program: Demo on positional arguments

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.

DATAPRO COMPUTERS 135

135
Output:

Program: Demo on keyword arguments

Note: These are similar to named parameters in C#.Net

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:

Program: Demo1 on default arguments

Note: his is nothing but “ ” ++ “ ” #.

Note: These too are very heavily used in Python Data Analytics and Visualizations

Output:

Program: Demo2 on default arguments

DATAPRO COMPUTERS 136

136
Output:

Program: Demo1 on variable length arguments

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:

def add(otherParameters, *args):

Output:

Program: Demo2 on variable length arguments

Output:

DATAPRO COMPUTERS 137

137
Note: The variable length argument parameter must be the last parameter the function definition.

“*”

Program: Demo3 on Variable length arguments

Output:

Note: We could have said: print("My name:" + name)


But could not have said: print("My courses:" + courses);

TypeError: Can't convert 'tuple' object to str implicitly

“*”

Program: Demo4 on Variable length arguments

Note: Passing collections into a variable length arguments parameter

Note: The *args is a tuple type of parameter

Output:

DATAPRO COMPUTERS 138

138
To get the output as per expectation – i.e., each element on a separate line:

Output:

Program: Demo on keyword variable length argument

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:

def fun(otherParameters, **kwargs):

Note: “x” is dict type

Output:

DATAPRO COMPUTERS 139

139
: “**” -value pairs can be passed

Program: Demo on local Vs Global variables

Output:

Note: Here, only the access is allowed, modification is not allowed. To modify it we have to redeclare
it inside the “ ”

Program: Demo on globals()

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:

DATAPRO COMPUTERS 140

140
Program: Demo on recursive functions Ex1

Note: If a function calls itself, then it is known as recursive function call.

Output:

Program: Demo on recursive functions Ex2

Output:

Lambda Expressions in Python

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.

DATAPRO COMPUTERS 141

141
Note: They are used very heavily in Data Analytics

Program: Lambda Expressions – Ex1

Without Lambda Expression:

Output:

With Lambda Expression:

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:

Note: If we check type of sum, it is a function.

print(type(sum))

Output:

Program: Using Lambdas with filter() – Ex1

DATAPRO COMPUTERS 142

142
Output:

Program: Using Lambdas with filter() – Ex2

Note: Here we are going to filter list of dictionaries

Output:

Program: Using Lambdas with map() – Ex1

DATAPRO COMPUTERS 143

143
Syntax:

Without Lambda Expression:

Output:

With Lambda Expression:

Note: the whole point of anonymous functions is: what is there in the name, all that matter is its
functionality.

Output:

Program: Using Lambdas with map() – Ex2

DATAPRO COMPUTERS 144

144
Note: Here, each i^th element of list_a and list_b will be passed as arguments to the lambda function.

Output:

Program: Using Lambdas with reduce() – Ex1

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

from functools import reduce

Program: Using Lambdas with reduce() – Ex2

DATAPRO COMPUTERS 145

145
Output:

Program: reduce() with operator module functions

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:

Program: Demo on accumulate()

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:

Program: Function Decorators – Ex1

DATAPRO COMPUTERS 146

146
Note: A decorator is a function that takes a function as its only parameter and returns a function. This
is helpful to “ ” .

Note: Common use cases of decorators: Timing, logging etc

Note: In this program, we shall measure the performance of two functions

Without Decorator

Output:

Note: The problem with the above code is: 2

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)

• So, there is lot of duplication


• It makes code unreadable due to unnecessary code

With Decorator

(It acts as a wrapper for your original function)

DATAPRO COMPUTERS 147

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:

Note: Decorator solves two issues:

• Code duplication
• Cluttering (filling with unnecessary code) main logic of a function with additional functionality
(i.e., timing in our example)

Program: Function Decorators – Ex2

Without decorator

DATAPRO COMPUTERS 148

148
Output:

With decorator

Output:

Special variable __name__

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.

Program: Demo1 on special variable __name__

DATAPRO COMPUTERS 149

149
Output:

Program: Demo2 on special variable __name__

Step1. Create a file myModule1.py

Step2. Create another file program2.py (make sure that both the files are in the same location)

Step3. Run the file program2.py

Output:

Note: he imported module’s global code gets executed 1st and the functions are executed when they
are invoked from the main program.

DATAPRO COMPUTERS 150

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.

Program: Modules in Python (creating and using them)

Step1. 1st create a file rajudiwalimodule1.py and save it some location, say: E:\team\fruit

Step2. Edit it as:

Step3. Now using the above function from another file – useModule1.py, this file can be saved
anywhere, say: D:\Raju\MyPythonPrgs\MyModulePrgs

Step4. Run this program:

Reason for error: because the imported file is not present in the current working directory

Solution1: Place the imported file in the current working directory

Is there a better solution?

Yes, there is a better solution:

Step5. Place it in the “ ” of the Python installation location:

C:\Users\bvraju\AppData\Local\Programs\Python\Python37\Lib

DATAPRO COMPUTERS 151

151
To know this location:

Is this the best solution?

No!

Step6. The best solution is put it a subfolder of “Lib”

Module Vs Package

A Module is simply a file containing Python code – classes, functions etc.


Eg: datetime, time, socket, threading, xml, json, email, array, calendar
They are usually present in: C:\Users\bvraju\AppData\Local\Programs\Python\Python37\Lib

A Package is a collection of related modules. Packages are installed.


eg: seaborn, scikit-learn, cx_Oracle, tweepy
They are usually installed in: C:\Users\bvraju\AppData\Local\Programs\Python\Python37\Lib\site-
packages

: “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

:“ ”

Step1. Create a python file – rajuModule2.py and edit it as:

tep2 Now let’s use the abo e module:

DATAPRO COMPUTERS 152

152
Method1:

Note: Here we must prefix with module name

Output:

Method2:

Note: Here we should not prefix with module name

Output:

Notice that myFun2() is not accessible as we have imported specifically myFun1() only

DATAPRO COMPUTERS 153

153
Chapter-10: Command Line arguments

What are command line arguments

These are the arguments that we pass to the program/main function from the command line/command
prompt.

Program: Passing two command line arguments and using them

Step1. Create a python file - cla1.py

Step2. Now run the program by passing two arguments

Note: The values are passed as list of strings

Program: Passing any number of command line arguments and using them

Step1.

DATAPRO COMPUTERS 154

154
Note: “args” would be a list type

Step2.

DATAPRO COMPUTERS 155

155
Chapter-11: OOP Basics using Python

Introduction to OOP

Python is a multi-paradigm programming language. It supports different programming approaches.


We have seen Procedural programming. We have functional programming. Now we shall see OOP as
well.

• OOP is very heavily used in GUI Programming


• OOP is very heavily used in Game Programming
• OOP is very heavily used in Big projects like Banking, E-Commerce, Medical

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

Eg: If you want to create a Sell and Buy Application

Ex1: Seller is a separate Entity


→with its own data: name, address, phonenumber etc
→with its own functionalities like: sellerregistration(), login() etc

Ex2: Product is a separate Entity


→data: productname, category, price etc
→functionalities: productRegistration, editProduct(), deleteProduct() etc

Ex3: Payment Gateway is a separate Entity


→data: sellerAccount, paymentMethod, amount etc
→functionalities: addToCart(), buy(), paymentSuccess() paymentFailure() etc

Program: Demo on creating a class, some member functions, creating an instance and invoking the
member functions

Step1.

DATAPRO COMPUTERS 156

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.

Note: There is “ ” for creating objects/instances unlike in C++/Java/C#.NET

• A class is a template for an object.


• An object is a collection of specific data and shared functions.

Step2. Run the program

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”

Program: Constructor Ex1

• A constructor is used to initialize an object.


• It gets invoked as soon as an object of its class get created.
• The __init__() acts as a constructor in Python.

DATAPRO COMPUTERS 157

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:

Program: Constructor Ex2 - Default argument constructor

Program: Demo on private data / Encapsulation

Ex1: Without private data

DATAPRO COMPUTERS 158

158
Output:

Ex2: With Private data

Output:

Note: two underscores indicate private data


Note: The parameters names can be anything
Note: one underscore indicates protected data (we shall see its details in Inheritance topic)

Ex3: With setters and getters

DATAPRO COMPUTERS 159

159
Output:

Program: To print an object directly

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

Program: Instance variables/fields and static variables/fields demo

Note: In Python, the variables which we write inside a class are of two types:
• Instance variables and
• class/shared variables

DATAPRO COMPUTERS 160

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.

With instance variable

Output:

With static variable

DATAPRO COMPUTERS 161

161
Output:

Note: static variable is like ’ j

Types of Methods in Python

In Python, methods can be classified as:


• Instance methods: Till now we have been using instance methods only. These are bound to
instances/objects (instancename.methodname()). Since instance variables are available in the
instance, instance methods need to know the memory address of the instance. This is provided
ia “self” ariable (“this” in ++ and Ja a) implicitly passed as 1st argument to the instance
method.

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

DATAPRO COMPUTERS 162

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.

Program: Class Methods Demo

Output:

Program: Static Methods Demo

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.

Program: Inner classes demo

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.

DATAPRO COMPUTERS 163

163
Output:

DATAPRO COMPUTERS 164

164
Chapter-12: Inheritance and Polymorphism

What is Inheritance

Inheritance is a mechanism of deriving new classes from existing ones.

Ex1: Deriving a Frame class


Ex2: Deriving an Activity class

Ex3: Deriving a Dialog class


Ex4: Deriving a Vehicle class while creating a Car class or a Bus class

So, it is the Reusability feature of OOP.

Program: Demo on Inheritance

Output:

Note: Like in Java and C#.Net, in Python too all classes are implicitly derived from “ j ” lass.

Program: Demo on method overriding

DATAPRO COMPUTERS 165

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.

Invoking the base class constructor

Output:

Types of Inheritance in Python

• Single Inheritance
DATAPRO COMPUTERS 166

166
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

Single Inheritance

Multiple Inheritance

Multilevel Inheritance

DATAPRO COMPUTERS 167

167
Hierarchical Inheritance

Hybrid Inheritance

DATAPRO COMPUTERS 168

168
Program: Demo on Multiple Inheritance

Output:

Program: Demo on Multi-level Inheritance

DATAPRO COMPUTERS 169

169
Output:

Program: Demo on Hierarchical Inheritance

Output:

Program: Demo on Hybrid Inheritance

DATAPRO COMPUTERS 170

170
Output:

Runtime Polymorphism

Runtime/Dynamic polymorphism (also known as late binding) is a process in which a call to an


overridden method is resolved at runtime that’s why it is called 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

We may say: “Same interface – different Implementation”

Ex1: Bike gear lever

Ex2: Pen drives

DATAPRO COMPUTERS 171

171
Ex3: Printers

DATAPRO COMPUTERS 172

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.

Program: Polymorphism in Operators

DATAPRO COMPUTERS 173

173
Program: Polymorphism in built-in functions

Program: Polymorphism in user-defined methods

Output:

Program: Demo on Polymorphism and Inheritance

DATAPRO COMPUTERS 174

174
Another way:

Note: Here, the for loop iterates through a tuple of objects.

Output:

Program: Demo on NotImplementedError() – without using it

DATAPRO COMPUTERS 175

175
Output:

Note: Notice that if we don’t o erride the draw() in any of the subclasses the base class implementation
gets invoked.

Program: Demo on NotImplementedError() – with using it (abstract methods in Java/C#.NET)

Note: now it becomes mandatory to implement the draw() method in its subclasses.

DATAPRO COMPUTERS 176

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:

Magic Methods in Python

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:

DATAPRO COMPUTERS 177

177
Program: Demo2 on Operator Overloading - addition operator (+) on user-defined objects

Without magic method:

Output:

DATAPRO COMPUTERS 178

178
Note: Notice that the Python interpreter could not know what to do

With magic method:

Output:

Note: Remember that b1 + b2 gives an integer but not another book

Program: Demo3 on Operator Overloading – overloading (>) operator

Output:

Program: Abstract methods and their need

Let’s consider the following ex:

DATAPRO COMPUTERS 179

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

Program: Demo1 on Abstract methods and abstract classes

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

DATAPRO COMPUTERS 180

180
Output:

Program: Demo2 on Abstract methods and abstract classes

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.

DATAPRO COMPUTERS 181

181
Output:

DATAPRO COMPUTERS 182

182
DATAPRO COMPUTERS 183

183
Chapter-13: Exception Handling

Introduction

What is Exception Handling

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:

• Dividing an integer with zero


• Reading from a file which is not available
• Writing to Database Server which is not yet started
• Converting a String to integer
etc.

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

Program: Exception Handling in Python - using try-except blocks

Output:
Case1: if input is 4 and 2:

DATAPRO COMPUTERS 184

184
Case2: if input is 4 and 0:

Note:
Just except: means any type of exception can be handled

Program: To handle different types of exceptions in different ways

Program: Demo on finally block

Note: It is similar to “finally” block in Ja a

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.

Without raise of an exception:

DATAPRO COMPUTERS 185

185
Output:

Verify:

With raise of an exception:

DATAPRO COMPUTERS 186

186
Output:

Program: Demo on User-defined exceptions

Note: The concept is similar to that of Java and C#.Net, main difference is instea “ ”
“ ”

Output:

DATAPRO COMPUTERS 187

187
DATAPRO COMPUTERS 188

188
Chapter-14: File Handling

What is File Handling

1. Storing the output of a program to a file on the hard disk.


2. Taking input for the program from a file on the hard disk.

Program: File Handling – reading lines from a text file

Note: By default, the open() function opens the file in read mode.
readlines() returns a list of strings/elements/lines

Output:

DATAPRO COMPUTERS 189

189
Program: File Handling – To know whether a file exists or not

Output:

If file doesn’t exist:

If file exits:

Program: File Handling - writing to a file

DATAPRO COMPUTERS 190

190
Step1.

: “ ”

Output:

Step2. Now open the file - pythondemo.txt (from the location: e:\team\fruit)

Program: File Handling - Writing a list of elements to a file at once

Note: All the elements would be written on a single line itself.

The File Opening Modes

File Open Mode Description


w (write) To write data into a file. If file already exists, it would be overwritten.
r (read) To read data from a file. As soon as the file is opened, the file pointer is
positioned at the beginning of the file.
a (append) To add data to the end of the existing content. The file pointer is placed at
the end of the file If the file doesn’t exist a new file gets created
w+ (write and read) To write and read data - both operations are allowed. If file already exists it
would be overwritten.

DATAPRO COMPUTERS 191

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

tep1 Let’s consider the following file – courses.txt:

Step2. Write the following program to append some content to the above file

Note: seek() takes two arguments:


1st arg: offset (how many bytes to move)
2nd arg: fromwhere

Note: the 2nd arg. can be:


0: means seek relati e to the files’ start position
1: means seek relative to the current position
2: means seek relative to the file's end position.

Step3. Run the program

Step4. Check the file – courses.txt

DATAPRO COMPUTERS 192

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:

DATAPRO COMPUTERS 193

193
Output:

Program: File Handling – Working with Binary Files – read and write images/audio files

Serialization and DeSerialization in Python

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.

This process of serializing an object is also called deflating or marshalling an object.

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.

In Python this process is called as pickling an object and unpickling an object.

DATAPRO COMPUTERS 194

194
In Python, we use the pickle module to accomplish it.

Eg: pickle.dump(object, file)

Program: File Handling - Serializing an object in Python

Step1. Write the following program

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

Step2. Run the program

Output:

Step3. Take a look at the file student.obj

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.

Program: File Handling De-Serializing an object in Python

Step1. Write the following program

DATAPRO COMPUTERS 195

195
Note: This class name and these field names must exactly match with that of the previous example.

Step2. Run the program

Output:

Program: File Handling – Writing Records in Binary Mode

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:

DATAPRO COMPUTERS 196

196
Program: File Handling – Reading Records in Binary Mode

Output:

Program: File Handling - Zipping files

Step1.

DATAPRO COMPUTERS 197

197
Note: ZIP_DEFLATED: The numeric constant for the usual ZIP compression method. No other
compression methods are currently supported.

:“ ” directory

Step2. Run the program

Output:

Note: Now delete the original folder – CSSFiles, as we are going to get it back via extraction/unzipping

Program: File Handling - UnZipping a file to extract its contents

Step1.

Step2. Run the program

Step3. Verify:

DATAPRO COMPUTERS 198

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:

DATAPRO COMPUTERS 199

199
Program: File Handling - To create a sub directory

Output:

Verify:

Note: If any of the directories already exists, we get an error:

Program: File Handling - To remove a directory

DATAPRO COMPUTERS 200

200
Note: If the directory is not empty:

Note: To remove a non-empty directory:

Output:

DATAPRO COMPUTERS 201

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.

Turtle Motion methods/functions

Move and draw

Setting and Measurement

DATAPRO COMPUTERS 202

202
Pen Control methods

Drawing State

Color control

Filling

More drawing control

Turtle state methods

Visibility

Appearance

DATAPRO COMPUTERS 203

203
Event methods

Special Turtle methods

Methods of TurtleScreen/Screen

Window control

Animation control

Using screen events

DATAPRO COMPUTERS 204

204
Settings and special methods

Input methods

Methods specific to screen

DATAPRO COMPUTERS 205

205
Program: Creating a Canvas / Drawing window

Step1.

(OR)

Step2. Run the Program

Program: To move forward and backward

Step1.

DATAPRO COMPUTERS 206

206
(OR)

Step2. Run the program

DATAPRO COMPUTERS 207

207
DATAPRO COMPUTERS 208

208
Program: To move right and left

Step1.

Step2. Run the program

DATAPRO COMPUTERS 209

209
Program: To draw a Square

Step1.

Step2. Run the Program

DATAPRO COMPUTERS 210

210
Method2:

Step1.

Step2. Run the program

DATAPRO COMPUTERS 211

211
Program: To draw a Rectangle

Step1.

Step2. Run the program

DATAPRO COMPUTERS 212

212
Program: Drawing a Circle

Step1.

Step2. Run the program

DATAPRO COMPUTERS 213

213
Program: To draw a semicircle

Step1.

Step2. Run the program

Program: Circle with steps (Hexagon)

Step1.

Step2. Run the program

DATAPRO COMPUTERS 214

214
Program: Drawing a Dot

Step1.

Step2.

Program: Changing the screen size and screen background color

Step1.

DATAPRO COMPUTERS 215

215
Step2. Run the program

Note: Notice the horizontal and vertical scrollbars

Program: Adding image on the screen and setting screen title

Step1. Place an image (parrot1.gif) in the current working directory

Step2.

DATAPRO COMPUTERS 216

216
Step3. Run the program

Program: Changing pen size

Step1.

Step2. Run the program

DATAPRO COMPUTERS 217

217
Program: Fill color

Step1.

Step2. Run the program

DATAPRO COMPUTERS 218

218
Program: To draw Polygons

Note: angle = 360 / sides

Step1.

Step2. Run the program

DATAPRO COMPUTERS 219

219
Hexagon:

Only change is:

numberOfSides = 6 #Hexagon

Octagon:

Only change is:

numberOfSides = 8 #Octagon

DATAPRO COMPUTERS 220

220
Program: To draw a star

Step1.

Step2.

DATAPRO COMPUTERS 221

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:

Search & find some information

A Regular Expression is also called simply “ x”.

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.

Program: Regular Expression Ex1 - using compile(), search() & group()

Output:

Note: Notice that search() gives the 1st occurrence value only

#print("result: ", result) #returns a "Match" type


#print("type of result:", type(result))

Program: Regular Expression Ex2 - search()

Note: Without using the compile()


DATAPRO COMPUTERS 223

223
Output:

Program: Regular Expression Ex3 – findall()

Note: findall() returns all resultant strings as a list

Output:

Program: Regular Expression Ex4 – match()

Note: match() returns the resultant string only if it found at the beginning of the string

Output:

DATAPRO COMPUTERS 224

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:

Program: Regular Expression Ex6– sub()

Note: sub() is used to find a string and replace it with a new string

Output:

DATAPRO COMPUTERS 225

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

Note: Let’s consider the R : [\w]*

“*”
[\w]* represents 0 or more alphanumeric characters

Program: Sequence Characters in Regular Expression – Ex1

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:

DATAPRO COMPUTERS 226

226
Output:

Program: Sequence Characters in Regular Expression – Ex2

Requirement: To retrieve all words enclosed within single quotes in the given string

Output:

Program: Sequence Characters in Regular Expression – Ex3

Requirement: to retrieve all words starting with a digit

DATAPRO COMPUTERS 227

227
Output:

Program: Sequence Characters in Regular Expression – Ex4

Requirement: To retrieve all words having 5 characters length

Output:

Program: Sequence Characters in Regular Expression – Ex5

Requirement: To retrieve all words having at least 4 characters length

Output:

DATAPRO COMPUTERS 228

228
Program: Sequence Characters in Regular Expression – Ex6

Requirement: o retrie e the last word of a string if it starts with “t”

Output:

Note: o retrie e the first word of a string if it starts with “o”

'\Ao[\w]*'

Quantifiers in Regular Expression

Note: In RE, some characters represent more than one character to be matched in the string. Such
characters are called quantifiers.

g: “+” represents 1 or more repetitions of the preceding character

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”

Program: Quantifiers in Regular Expression – Ex1

Requirement: to retrieve the phone number of a person

DATAPRO COMPUTERS 229

229
Output:

Exactly 10 digits only:

Program: Quantifiers in Regular Expression – Ex2

Requirement: To retrieve details except phone number

Output:

Note: result1 would be: ['Sachin Tendulkar, ', ', Mumbai']

Program: Quantifiers in Regular Expression – Ex3

Requirement: to find all words starting with “raj” or “rak”

DATAPRO COMPUTERS 230

230
Output:

Program: Quantifiers in Regular Expression – Ex4

Requirement: to retrieve date of births from a string

Output:

Special Characters in Regular Expression

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 “ ”

Program: Special Characters in Regular Expression – Ex1

Requirement: to check whether a string starts with “He”

DATAPRO COMPUTERS 231

231
Output:

Note:

Program: Special Characters in Regular Expression – Ex2

Requirement: o check whether a string ends with “jpg” or “jpeg”

Output:

Note: There is no operator for “and” the solution is:

Program: Special Characters in Regular Expression – Ex3

Requirement: Whether the strings starts with “He” and ends with “er”
DATAPRO COMPUTERS 232

232
Note: he result would be “None” or a “Match”

Program: Special Characters in Regular Expression – Ex4

Requirement: using “I N R ”

Output:

Program: Special Characters in Regular Expression – Ex5

Requirement: o retrie e students’ marks and their names separately from a gi en string

Output:

DATAPRO COMPUTERS 233

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.

Requirement: read all email-ids from a text file

Let’s consider the following text file:

The Program:

Output:

DATAPRO COMPUTERS 234

234
Program: Using Regular Expressions on Files – Ex2

Let’s consider the following text file:

Requirement: to retrieve only employee ids and their corresponding salaries data

Output:

Program: Using Regular Expressions to get data from a HTML table

Let’s consider the following H ML file:

DATAPRO COMPUTERS 235

235
Requirement: To retrieve employees names and corresponding salaries from the HTML file

Output:

DATAPRO COMPUTERS 236

236
Chapter-17: Date & Time

Program: The beginning of a 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:

Note: shortcut way:

Output:

DATAPRO COMPUTERS 237

237
Program: Finding current Date and Time

Output:

Note: Notice that we have not mentioned the epoch time

Program: Demo on now()

Output:

Program: Combining Date and Time

Note: we can create “datetime” class object by combining date class object and time class objects using
combine()

Output:

DATAPRO COMPUTERS 238

238
Formatting Date & Time – codes

Note: Examples are based on the date: 2013, 9, 30 and time: 7, 6, 5

Code Meaning Example

%a Weekday as locale’s abbreviated name. Mon

%A Weekday as locale’s full name. Monday

%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 1

%d Day of the month as a zero-padded decimal number. 30

%-d Day of the month as a decimal number. (Platform specific) 30

%b Month as locale’s abbreviated name. Sep

%B Month as locale’s full name. September

%m Month as a zero-padded decimal number. 09

%-m Month as a decimal number. (Platform specific) 9

%y Year without century as a zero-padded decimal number(year with last 2 13


digits).

%Y Year with century as a decimal number(4 digits year). 2013

%H Hour (24-hour clock) as a zero-padded decimal number. 07

%-H Hour (24-hour clock) as a decimal number. (Platform specific) 7

%I Hour (12-hour clock) as a zero-padded decimal number. 07

%-I Hour (12-hour clock) as a decimal number. (Platform specific) 7

%p Locale’s equivalent of either AM or PM. AM

%M Minute as a zero-padded decimal number. 06

%-M Minute as a decimal number. (Platform specific) 6

%S Second as a zero-padded decimal number. 05

%-S Second as a decimal number. (Platform specific) 5

%f Microsecond as a decimal number, zero-padded on the left. 000000

%z UTC offset in the form +HHMM or -HHMM (empty string if the the object
is naive).

%Z Time zone name (empty string if the object is naive).

%j Day of the year as a zero-padded decimal number. 273

%-j Day of the year as a decimal number. (Platform specific) 273

DATAPRO COMPUTERS 239

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.

%c Locale’s appropriate date and time representation. Mon Sep 30


07:06:05 2013

%x Locale’s appropriate date representation. 09/30/13

%X Locale’s appropriate time representation. 07:06:05

%% A literal '%' character. %

Program: Demo on Formatting Date – ex1

Output:

Program: Demo on Formatting Date – ex2

Output:

DATAPRO COMPUTERS 240

240
Program: Formatting Time

sOutput:

Program: To accept a date from the keyboard and display the day of the week

Output:

Program: Finding difference between two dates

DATAPRO COMPUTERS 241

241
Output:

Program: Finding difference between two times

Note: Here we shall use “datetime()”

Output:

Program: To display the next 30 days

DATAPRO COMPUTERS 242

242
Output:

Program: Comparing two dates

DATAPRO COMPUTERS 243

243
Output:

Program: Sorting dates

Note: we shall store a group of dates into a list and then apply list’s sort() method

Output:

Program: ’ x

DATAPRO COMPUTERS 244

244
Output:

ame as that of pre ious programs’ output only difference is each line would be displayed with 5
seconds delay

Note: To delay in milliseconds, give the value in fractions

Eg: sleep(0.1) for 1/10th of a sec


sleep(0.001) for 1/1000th of a sec

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

perf_counter(): It includes the time elapsed during sleep of the processor.


_ (): ’ .

DATAPRO COMPUTERS 245

245
Output:

Note: replace perf_counter() with process_time(), then output:

: “ ” – Ex1

Requirement: find whether a given year is leap year

Output:

: “ ” – Ex2

Requirement: display calendar of given month of the year

DATAPRO COMPUTERS 246

246
Output:

: “ ” – Ex3

Requirement: To display a calendar for all the months of an entire year

Output:

DATAPRO COMPUTERS 247

247
DATAPRO COMPUTERS 248

248
Chapter-18: Miscellaneous topics

Program: Demo on enumerate() to get both the indices and elements from a list

Program: Demo on generating random numbers

Program: Demo on picking a random item from a list or tuple?

How is Memory Management done in Python

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:

DATAPRO COMPUTERS 249

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:

DATAPRO COMPUTERS 250

250
Output:

Note: Recall that integers are immutable.

Function call stack:

Garbage Collector

DATAPRO COMPUTERS 251

251
Namespaces in Python

Note: It is different from namespaces concept in C++ and C#.Net

It defines the scope of variables.

The Rule is LEGB (Priority wise least to highest):

• 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

DATAPRO COMPUTERS 252

252
Demo on using __file__ built-in variable name

Step1. Create a python file – namespace1.py

Step2. Run the program

Output:

Note: The LEGB Rule applies when variables in two different scopes have same names.

Demo on Enclosing Scope

DATAPRO COMPUTERS 253

253
Output:

nonlocal keyword

tep1 Write the following program (without “nonlocal” keyword)

Step2. Run the Program

Note:

If we want to modify a non-local variable inside a nested function, then it must be declared with
nonlocal keyword

Step3. Edit it as follows

DATAPRO COMPUTERS 254

254
Step4. Re-Run the Program

Output:

Demo on Python Closures

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.

Step1. Write the following program

DATAPRO COMPUTERS 255

255
Step2. Run it

Output:

Step3. Edit the program

Step4. Re-run it

Output

Requirements for creating closures in Python

• There must be a nested function.


• The nested function must refer to a variable defined in its enclosing function.
• The enclosing function must return the nested/inner function.

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.

Creating Generators in Python

Note: If a function contains at least one yield statement, it becomes a generator function.

Program: Demo on generators

ype of the ariable “gen” : generator

Output:

Note:

Even after returning a value to us, “” x the


function is called and then increases its value by one. So, the next time this function is invoked, it will
pick up right where it has left off.

“ “ “ ”

Both “return” and “yield” will return some value from a function.

The difference is:


A “return” statement terminates a function entirely where as a “yield” statement pauses the function
saving all its states and later continues from there - on successive invocations.

DATAPRO COMPUTERS 257

257
Note:
Q: Is Multiple Inheritance available in Python

Ans: Yes, it is possible

Program: Demo1 on Multiple Inheritance in Python

Program: Demo2 on Mutiple Inheritance in Python – no ambiguity unlike in C++

Output:

o in oke ase2’s fun():

Base2.fun(d)

DATAPRO COMPUTERS 258

258

You might also like