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

Final Notes Python

The document outlines a syllabus for a Python course, detailing various units and topics to be covered over multiple days, including installation, basics of Python, and its applications. It also highlights the advantages and disadvantages of Python, its history, and various frameworks. Additionally, it contains review questions to assess understanding of the material presented.

Uploaded by

roasterbyte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Final Notes Python

The document outlines a syllabus for a Python course, detailing various units and topics to be covered over multiple days, including installation, basics of Python, and its applications. It also highlights the advantages and disadvantages of Python, its history, and various frameworks. Additionally, it contains review questions to assess understanding of the material presented.

Uploaded by

roasterbyte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 609

1

PYTHON : BCC-302 ST1:Page no: 587


ST2:Page no:593
SYLLABUS: PAGE NO-611
ST3:Page no:603
UNIT: 1 PAGE NO: 2
UNIT : 2 PAGE NO: 216
UNIT: 3 PAGE NO: 317
UNIT: 4 PAGE NO: 505
UNIT: 5 PAGE NO: 536

ST1+ST2+ST3
Include: coding questions and last years
question papers with unit wise question bank

BY
TARUN KUMAR GAUTAM
CSE-DS

1 1 1
Quality Content for Outcome based Learning
4

UNIT:1
1.1 Getting started with Python
Day 1

4 4 4

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


General Guideline 5

© (2021) ABES Engineering College.

This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.

5 5 5
2
Copyright © 2021, ABES Engineering College
Topics Covered 6

Day 1 Day 2 Day 3 Day 4


1.1 Getting started 1.1 Getting started with 1.2 Python Installation 1.3 Basics of Python
with Python Python Guide • 1.3.1 Python keywords
• 1.1.1 Introduction • 1.1.6 Advantages of • 1.2.1 Introduction to • 1.3.2 Python Statement
to programming Python python IDE – IDLE
and Comments
and coding • 1.1.7 Disadvantages of • 1.2.2 Setting Up Your
Environment • 1.3.3 Python Literals
• 1.1.2 Why choose Python
Python • 1.2.3 Installation of • 1.3.4 Data Types
• 1.1.8 Applications of
• 1.1.3 Scope of Python Python and Anaconda • 1.3.5 Variables
Python • 1.1.9 Different Flavors of Navigator • 1.3.6 type (), dir (),ID
• 1.1.4 Python Python • 1.2.4 Quick Tour of command
History • 1.1.10 Different Python Jupyter Notebook
• 1.1.5 Python Frameworks • 1.2.5 Python vs. IPython
Features • 1.1.11 Python in contrast • 1.2.6 Online compilation
with other programming support
languages • 1.2.7 Running python
script using command
prompt
6 6 6
3
Copyright © 2021, ABES Engineering College
Topics Covered 7

Day 5 Day 6

1.3 Basics of Python 1.3 Basics of Python


• 1.3.7 Type • 1.3.9 Operators
conversion: implicit • 1.3.10 Precedence
and explicit and associativity
• 1.3.8 Basic I/O • 1.3.11 Python 2 vs
Operations: input (), Python 3
print ()

7 7 7
4
Copyright © 2021, ABES Engineering College
Session Plan - Day 1 8

1.1Getting started with Python


1.1.1 Introduction to programming and coding
1.1.2 Why choose Python
1.1.3 Scope of Python
1.1.4 Python History
1.1.5 Python Features

8 8 8
5
Copyright © 2021, ABES Engineering College
Introduction 9

Python is a Popular
Programming language

?
https://www.wordclouds.com/
9 9 9
6
Copyright © 2021, ABES Engineering College
10

Some Areas where it is Popular

Application Development
Web Development
Artificial Intelligence
Data Science

10 10 10
7
Copyright © 2021, ABES Engineering College
11

Why choose Python : Lets Discuss More

Simple and Easier to learn


Good Readability
Free and Open Source
Python is a platform-independent language
High Level and Interpreted language
Extensive libraries: Python has a vast number of libraries.

11 11 11
8
Copyright © 2021, ABES Engineering College
12

Scope of Python
Python Language provides promising and rewarding career in the IT industry
Various Job roles advanced in Python with high paying jobs:
Research Analyst
DevOps Engineer
Python Developer
Data Analyst
Software Developer
Game Developer
Web Scrapper

12 12 12
9
Copyright © 2021, ABES Engineering College
Python History 13

Python was written in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI)

13 13 13
10
Copyright © 2021, ABES Engineering College
Python Features 14

14 14 14
11
Copyright © 2021, ABES Engineering College
15

Review Questions

 In which year was the Python language developed?


 1995
 1972
 1981
 1989

 Who developed the Python language?


 Zim Den
 Guido van Rossum
 Niene Stom
 Wick van Rossum

15 15 15
12
Copyright © 2021, ABES Engineering College
16

Review Questions

 How many keywords are there in python 3.7?


 32
 33
 35
 30
 Which one of the following is the correct extension of the Python
file?
 .py
 .python
 .p
 None of these
16 16 16
13
Copyright © 2021, ABES Engineering College
Session Plan - Day 2 17

1.1Getting started with Python


1.1.6 Advantages of Python
1.1.7 Disadvantages of Python
1.1.8 Applications of Python
1.1.9 Different Flavors of Python
1.1.10 Different Python Frameworks
1.1.11 Python in contrast with other programming languages

17 17 17
14
Copyright © 2021, ABES Engineering College
18

Advantages of Python

18 18 18
15
Copyright © 2021, ABES Engineering College
19

Contd..

Write a Program using any language to print “ HELLO WORLD “.

Java Program : C++ Program :

public class Hello #include <iostream><br>


{ int main()
public static void main(String argv[]) {
{ cout << "Hello World" << endl;
return 0;
System.out.println(“Hello, World!”); }

}
}

19 19 19
16
Copyright © 2021, ABES Engineering College
20

Contd..

In Python

print ( "Hello World")

20 20 20
17
Copyright © 2021, ABES Engineering College
21

Disadvantages of Python
Python code is executed line by line since Python is interpreted as slower
in runtime than other programming languages like C++, Java, and PHP.
Python takes a lot of memory due to the flexibility of the data types, so it
is not a desirable choice for memory-intensive tasks.
Although Python serves as an excellent server-side programming
language, it is less commonly used to build intelligent phone-based
Applications.
Python is rarely used in Enterprise development because Python has
some limitations with Database Access compared to primarily other used
technologies like JDBC (Java Database Connectivity and ODBC (Open
Database Connectivity) as Python Language Database layers are
underdeveloped.

21 21 21
18
Copyright © 2021, ABES Engineering College
22

Your Future….!!!

22 22 22

Copyright © 2021, ABES Engineering College


23

Applications of Python
Web and Internet Development
Game Development
Desktop GUI Applications
Artificial Intelligence and Machine Learning
Data Science and Data Visualization
Web Scraping Applications
Desktop Applications
Business Applications
Image Processing and Computer Graphics
Language Development
Popular Applications Built on Python
23 23 23
20
Copyright © 2021, ABES Engineering College
24

Different Flavors of Python


Cpython
Jpython
Active Python
Anaconda Python
PyPy
Win Python
Python Portable

24 24 24
21
Copyright © 2021, ABES Engineering College
25

Different Python Frameworks


Full-Stack Frameworks
Non-Full Stack Frameworks
Asynchronous Frameworks

25 25 25
22
Copyright © 2021, ABES Engineering College
26

Review Questions

 How to output the string “May the odds favor you” in Python?
 print(“May the odds favor you”)
 echo(“May the odds favor you”)
 System.out(“May the odds favor you”)
 printf(“May the odds favor you”)

 In which year was the Python 3.0 version developed?


 2005
 2000
 2010
 2008

26 26 26
23
Copyright © 2021, ABES Engineering College
27

Review Questions

 Python is often described as a:


 Batteries excluded language
 Gear included language
 Batteries included language
 Gear excluded language

 What do we use to define a block of code in Python language?


 Indentation
 Key
 Brackets
 None of these

27 27 27
24
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
28

1.2 Python Installation Guide


Day 3

28 28 28

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


Session Plan - Day 3 29

1.2 Python Installation Guide


 1.2.1 Introduction to python IDE – IDLE
 1.2.2 Setting Up Your Environment
 1.2.3 Installation of Python and Anaconda Navigator
 1.2.4 Quick Tour of Jupyter Notebook
 1.2.5 Python vs. IPython
 1.2.6 Online compilation support
 1.2.7 Running python script using command prompt

29 29 29
26
Copyright © 2021, ABES Engineering College
30
1.2 Python Installation Guide

Before you start, you will need Python on your computer.


Installing Python on your computer is the first step to becoming a Python
programmer.
Python has two main versions:
• Python 2
• Python 3
However, Python installation differs among different operating systems. The
use of Python 3 is highly preferred over Python 2.

30 30 30
27
Copyright © 2021, ABES Engineering College
31
Contd..
For the installation process, go to the official website of Python, i.e.,
www.python.org. Refer to the current stable version 3.9.4 as of date 13 April
2021.You will get the installer for Python 3.7 or Python 3.9. (at the time of
writing). You may even have it with a 32-bit or 64-bit processor versions.

31 31 31
28
Copyright © 2021, ABES Engineering College
32
1.2.1 Introduction to python IDE – IDLE

If you have recently installed Python on your computer, you might have seen a
new IDLE program.
"What is this software doing on my computer?" you might be curious. I did not
download that!"
Though you might not have downloaded IDLE on your own, it is included with
any Python installation. It is there to help you get acquainted with the language
right away.

Any Python installation includes an Integrated Development and Learning


Environment, abbreviated IDLE or even IDE.

32 32 32
29
Copyright © 2021, ABES Engineering College
33

Contd..

In a graphical user interface (GUI) desktop environment, the installation process


puts an icon on the desktop or an object in the desktop menu system that
launches Python.
In Windows, for example, there will be a category in the Start menu called
Python 3.7. Under it, a menu item labeled Python 3.7.4 (32-bit).

33 33 33
30
Copyright © 2021, ABES Engineering College
34

Contd..
Alternate way: You can also open a terminal window and run the interpreter
from the command line.
It is known as Command Prompt in Windows. It can be renamed terminal in
macOS or Linux.
You can type Windows key+ R and type cmd to open Command Prompt.
Then, type python to execute python programs.

34 34 34
31
Copyright © 2021, ABES Engineering College
35

Contd..
Start working with Python shell.
To print () to display the string "ABES Engineering College" on your computer.
Enter the command one at a time, and Python returns the results of each
command.

35 35 35
32
Copyright © 2021, ABES Engineering College
36

Contd..
From this menu bar, you can restart the shell. It will behave as if you had
launched a new instance of Python IDLE. The shell will forget anything from its
former state.
If you want to exit the interpreter, then type exit () and press Enter.

36 36 36
33
Copyright © 2021, ABES Engineering College
37

Python IDLE Editor


Python IDLE includes a full-featured file editor, allowing you to write and run
Python programs. The built-in file editor also supplies many tools to speed up
your coding workflows, such as code completion and automated indentation.
Select File “New File” from the menu bar to begin a new Python file

37 37 37
34
Copyright © 2021, ABES Engineering College
38

Contd..
When you are ready to work on a file, click the Edit button. You can save the file
as Demo-Python.py (.py is an extension to save python scripts files) in the
specified default location "C:\Users\Aatif\AppData\Local\Programs\Python."

38 38 38
35
Copyright © 2021, ABES Engineering College
39

Contd..
When you want to run a file, you must first ensure that it has been saved,
remember to check for asterisks * around the filename at the top of the file
editor window to see whether the file was correctly saved.

But do not panic if you forget! When you want to run an unsaved file in Python
IDLE, it will prompt you to save it.
Click the F5 key on your keyboard to run a file in IDLE. You can also use the
menu bar to choose Run Module
39 39 39
36
Copyright © 2021, ABES Engineering College
40

1.2.2 Setting Up Your Environment

The route(path that lists the directories in which the OS (Operating System)
looks for executables) is saved in an environment variable called a string.This
variable holds knowledge that the command shell and other programs can use.

In Unix, the path variable is known as PATH, and in Windows, it is known as


Path (Unix is case sensitive; Windows is not).
Following are the steps are taken for setting up the environment:
• Step 1 – Install Python 3.7 (Latest Version) from python.org.
• Step 2-- Add the Python 3.7 Directory to your System Path Environment Variable

40 40 40
37
Copyright © 2021, ABES Engineering College
41

Contd..

So, navigate to
Control Panel –> System
–> Advanced System
Settings–> Environment
Variables and choose
the PATH variable

41 41 41
38
Copyright © 2021, ABES Engineering College
42

Contd..
Add the Python path to the end of the string, this is where the package
management software, unit testing tools, and other command line-accessible
Python programs can live.
C:\Users\Aatif\AppData\Local\Programs\Python\Python37-32\Scripts\

42 42 42
39
Copyright © 2021, ABES Engineering College
43

1.2.3 Installation of Anaconda Navigator


Anaconda Navigator is a desktop graphical user interface that comes with
Anaconda, which allows you to open programs and control conda packages,
environments, and networks without needing to use a command-line interface.

For the installation process, go to the


official website of anaconda navigator
https://docs.anaconda.com/anaconda
/navigator/.
Latest version:
Anaconda3-2020.11-Windows-x86_64.exe

43 43 43
40
Copyright © 2021, ABES Engineering College
44

Contd..
Click on install and Choose destination folder for installation.

44 44 44
41
Copyright © 2021, ABES Engineering College
45

1.2.4 Quick Tour of Jupyter Notebook


In an earlier topic, we have seen the installation of the Anaconda package.
Jupyter comes by default with this package

The Jupyter Notebook


is a fantastic platform
for creating basic and
advanced level
programs.

45 45 45
42
Copyright © 2021, ABES Engineering College
46

Contd..
Alternate way: If you type 'Jupyter notebook' into your command prompt, it will
open the Jupyter dashboard for you

46 46 46
43
Copyright © 2021, ABES Engineering College
47

Contd..
You might have found that the URL for the dashboard is
https://localhost:8888/tree while Jupyter Notebook is open in your window. The
term "localhost" does not refer to a website, but to the fact that the content is
served from your own devices.

47 47 47
44
Copyright © 2021, ABES Engineering College
48

Contd..
If you want to create your first file, then you must click on new and then python3.
When you return to the dashboard, you can see the new file Untitled18.ipynb
with green boundary in cell.
A cell is a container for the text that will be viewed in the notebook or code that
the notebook's kernel will execute.

48 48 48
45
Copyright © 2021, ABES Engineering College
49

Contd..
Every ipynb file stands for a single notebook, which means that each time you
create a new notebook, a new.ipynb file is generated .You should be aware of
kernel that are unfamiliar to you.
A kernel is a kind of "computational engine" that runs the code in a notebook
paper.

49 49 49
46
Copyright © 2021, ABES Engineering College
50

Contd..
Shift + Enter is the shortcut command to run your cell.
The green boundary over the cell shows the editable mode, and the Blue
boundary over the cell shows the command mode.

50 50 50
47
Copyright © 2021, ABES Engineering College
51

1.2.5 Python vs. IPython


IPython's interactive shell is known as Ipython.
IPython is a Python graphical command-line terminal founded by Fernando
Perez in 2001. IPython supplies an improved read-eval-print loop (REPL)
environment that is particularly well suited to scientific computing.

51 51 51
48
Copyright © 2021, ABES Engineering College
52

Contd..
IPython is interactive, and it gives some relaxation to the eyes of coders by
introducing some colors. Some useful commands are not present with the
existing Python idle.
The following are the valuable commands:
• %pwd
• %ls
• %History

52 52 52
49
Copyright © 2021, ABES Engineering College
53

Contd..
We can also check methods associated with data structures by pressing the tab
over the keyboard.

53 53 53
50
Copyright © 2021, ABES Engineering College
54

1.2.6 Online compilation support


Assume your machine lacks the necessary resources to install, but you need to
learn Python or run code to try something.

What if you could run Python online in your browser?

That is very great. Isn't that, right?

You will need a browser, which you already have. Using online IDEs saves yor
time in the configuration process.

54 54 54
51
Copyright © 2021, ABES Engineering College
55

Contd..

w3schools(https://www.w3schools.com/python/python_compiler.asp)

55 55 55
52
Copyright © 2021, ABES Engineering College
56

Contd..

Onlinegdb (https://www.onlinegdb.com/online_python_compiler)

56 56 56
53
Copyright © 2021, ABES Engineering College
57

Contd..

One compiler (https://onecompiler.com/python/3wukez6hf)

57 57 57
54
Copyright © 2021, ABES Engineering College
58

Review Questions

 Which version of Python is currently up to date?


 Python1
 Python2
 Python4
 Python3

 The version of Python (if any) that comes pre-installed on your


operating system is called _.
 Onboard Python
 Monty Python
 Easy Python
 System Python

58 58 58
55
Copyright © 2021, ABES Engineering College
59

Review Questions

 In a Python context, the acronym IDLE stands for:


 Integrated Development and Learning Environment
 Interpretive Dance Lessons
 Interstellar Dust Laser Explorer
 None of the above

 When you see >>> inside IDLE, it means that:


 An error has occurred
 Your computer is having an existential crisis
 Python is waiting for you to give it some instructions
 Python is upset

59 59 59
56
Copyright © 2021, ABES Engineering College
Session Plan - Day 4 60

1.3 Basics of Python


1.3.1 Python keywords
1.3.2 Python Statement and Comments
1.3.3 Python Literals
1.3.4 Data Types
1.3.5 Variables
1.3.6 type (), dir (),ID command

60 60 60
57
Copyright © 2021, ABES Engineering College
61
Python keywords

Python keywords are special reserved words that have specific meanings
and purposes.

These reserve words cannot be used as a –

 function name
 variable name
 identifiers

Note - As of python 3.9.2, there are 35 reserved words in Python.

61 61 61
58
Copyright © 2021, ABES Engineering College
62

Contd..

The list of such keywords is mentioned below –


True False class def except
if elif else try is
raise finally for in lambda

not from import global continue

nonlocal pass while break del


and with as yield

or assert None return

62 62 62
59
Copyright © 2021, ABES Engineering College
63

Python Statement and Comments


Python Statement –
 In Python Programming, any executable instruction, that tell the computer to perform a specification
action is refer to as statements.

 Program statement can be an

 input-output statements,

 arithmetic statements,

 control statements,

 simple assignment statements

 and any other statements

 it can also includes comments.

63 63 63
60
Copyright © 2021, ABES Engineering College
64

Python Literals

Literals are the type of data that is used to store in a variable or constant.

Types of python literals:


 String literals
 Numeric Literals
 Integer Literals
 Float Literals
 Complex Number Literals
 Boolean Literals
 Special literals
 Literal Collections

64 64 64
61
Copyright © 2021, ABES Engineering College
65

String literals
When set of character are enclosed in quotes ( single quotes or double quotes)
then it formed a string literals.
'abes' 'rate_of_interest' '123', '12.5'
Example -
"ABESEC" "Simple_interest" "A1" "456 "

In Python we can also create multi-line literals by using ‘\’.

Example -
'ABES Engineering College \ "ABES Engineering College \
NH-24 Delhi Hapur Bypass \ NH-24 Delhi Hapur Bypass \
Near Crossing Republic' Near Crossing Republic"

65 65 65
62
Copyright © 2021, ABES Engineering College
66

Numeric Literals
Numeric literals are of multiple types based on the number type. The types
of numeric literals are integer, float (decimal numbers), and complex
numbers.

Integer Literals - They can be either positive or negative.

Example – 12, 23000000, -45, 0 , -23987

Float Literals - These are basically real numbers that consist of both integer
as well as fractional parts.

Example - -12.45, 12.90, 100.0

66 66 66
63
Copyright © 2021, ABES Engineering College
67

Numeric Literals

Complex Number Literals - The numerals will be in the form of a + bj,


where ‘a‘ is the real part and ‘b‘ is the complex part.

Python allows us to specify complex numbers like any other variable.

Example -
10j , 1 + 0j , 10 + 2J, 12 – 5j

67 67 67
64
Copyright © 2021, ABES Engineering College
68

Boolean Literals , Special literals


Boolean Literals - True or False are the values to be used as the Boolean
values.

Example - True, False

In Python, True represents the Non-zero value and False represents the
value as Zero.

Special literals - Python has a special literal named None.

Note - None is used to signify the NULL value.

68 68 68
65
Copyright © 2021, ABES Engineering College
69

Literal Collections
List Literals – List is a set of values of different types. The values are
separated by comma (,) and enclosed within square brackets( [ ]).

[ 1, 23, 23.4, 100]


Example –
[ 'Blue', 'red', 123, 23.5 ]

Tuple literals – A tuple is a set of values of different types. The values are
separated by comma(,) and enclosed within parentheses “ ( ) “. It is
immutable.
Example -
( 1, 23, 23.4, 100 )

( 'Blue', 'red', 123, 23.5 )


69 69 69
66
Copyright © 2021, ABES Engineering College
70

Literal Collections
Dictionary literals – It is in form of key-value pair. It is enclosed by curly-
braces “{ }” and each key-value pair is separated by commas (,) .

Example – { 'name':'BOB', 'age':24, 'marks':59.4 }

Set literals – Set is a collection of values of different types. The values are
separated by comma (,) and enclosed within curly-braces “{ }”. It is
unordered and contains only unique value.

{ 1, 23, 45, 56, 67 }


Example -
{ 'Ram', 'Rajesh', 12, 34.5 }
70 70 70
67
Copyright © 2021, ABES Engineering College
71

Variables
Variable are the names given by the users to the memory locations to store
the data values.
In Python, variable need not to be declared or defined in advances, as we
do in many other programming language.

To create a variable, we just assign it a value and start using it.

Example – a = 23
Here ‘a’, ‘name’ and ‘Marks’ are variable which
name = 'Ram'
refer an integer value 23, a string ‘Ram’ and float
Value 23.5.
Marks = 23.5
71 71 71
68
Copyright © 2021, ABES Engineering College
72

Variables
Rules for variable name –
 Variables can be named with an alpha-numeric combination, started with
an alphabet or underscore.
 Variable name can’t start with digit.
 Multi- word space separated name can’t be used as a variable name.
 The reserved words(keywords) cannot be used naming the variable.

Valid Variable Names In-Valid Variable Names


Name, num1,
rate_of_interest, for, 123b, rate of
_abc, marks interest, marks-math

72 72 72
69
Copyright © 2021, ABES Engineering College
73
Can you answer these questions?

1. Select all Valid variable names -

1) age

2) _age

3) -age

4) age_*

5) Item-Number-1

73 73 73
70
Copyright © 2021, ABES Engineering College
74

type() command
type () command helps in finding the type of the specific declared variable
or a value.

Example –

74 74 74
71
Copyright © 2021, ABES Engineering College
75

id() command
id () command gives the unique id for a given objects / variable / values.

Note - The unique id is the memory address and will be different each time
when you run for variable or values.

Example –

Unique Identity

75 75 75
72
Copyright © 2021, ABES Engineering College
76

dir() command
dir () command is a vital function that returns all the properties and
methods associated with given objects.

Example –

Note – Detailed description will be


explain in OOPs

76 76 76
73
Copyright © 2021, ABES Engineering College
Session Plan - Day 5 77

1.3 Basics of Python


1.3.7 Type conversion: implicit and explicit
1.3.8 Basic I/O Operations: input (), print ()

77 77 77
74
Copyright © 2021, ABES Engineering College
78

Type conversion
The process of converting the value of one data type (e.g. integer, string,
float, etc.) to another data type is called type conversion.

Example -
12.5  12 ( float to integer )
'123'  123 ( string to integer )
12  12.0 ( integer to float )

Python has two types of type conversion –

 Implicit Type Conversion


 Explicit Type Conversion
78 78 78
75
Copyright © 2021, ABES Engineering College
79

Type conversion : Implicit Type Conversion

Implicit Type Conversion – In this Python interpreter itself converts one


type of data to another data type as per the performed operation.

This type conversion happens automatically without any user intervention.

Example –

Note - Python promotes the conversion of the lower data type (integer) to
the higher data type (float) to avoid data loss.
79 79 79
76
Copyright © 2021, ABES Engineering College
80

Type conversion : Explicit Type Conversion

Explicit Type Conversion – In this, user converts the data type of variable
of value to needed data type.

Example –

int()  for Integer


float() for Float
str()  for string
Note – There should be valid Numbers while converting any
string to Numbers.
Complex  for complex

80 80 80
77
Copyright © 2021, ABES Engineering College
81
Can you answer these questions?

1. What will be the output of the following -

a) 12 (20+0j) 123.45

b) 12 20 123.45

c) Error

81 81 81
78
Copyright © 2021, ABES Engineering College
82

Basic I/O Operations

In python, various built-in functions are present.

The two important standard input-output functions in python are:

 input() : to take the input from the user

 print() : to show the output on the console

82 82 82
79
Copyright © 2021, ABES Engineering College
83

Basic I/O Operations : input()


Syntax –
input(prompt='')
Prompt - A String, representing a default message
before the input.

Example –

Note – It return value as a string. So you need to typecast it.


83 83 83
80
Copyright © 2021, ABES Engineering College
84

Basic I/O Operations : input()


Syntax –
input(prompt='')
Prompt - A String, representing a default message
before the input.

Example –

84 84 84
81
Copyright © 2021, ABES Engineering College
85

Basic I/O Operations : input()


When we take input using input() function, it return value in string data type.

Example –

As we can see in the above example type of “a” is string

Note – We have to typecast input


value into desired type.

85 85 85
82
Copyright © 2021, ABES Engineering College
86

Basic I/O Operations : print()


print () is a built-in standard function used to print the output to the console.

Syntax – print(value, ..., sep='', end='\n’)

 value – Can be of any literals, variable, expression, statements

 sep - (optional), Specify how to separate the values, if there is more than
one. Default is ' '.

 end - (optional), Specify what to print at the end. Default is '\n‘

Note – We can assign any set of character into sep.


86 86 86
83
Copyright © 2021, ABES Engineering College
87

Basic I/O Operations : print()


Example –

In the above example value of a and b is separated by space i.e. default

Here separator is sep='--', so both value is


separated by '--‘ as shown in output.

87 87 87
84
Copyright © 2021, ABES Engineering College
88

Basic I/O Operations : print()


Example – Write a Python program that takes two integer as input from
user and print sum of both.

88 88 88
85
Copyright © 2021, ABES Engineering College
Session Plan - Day 6 89

1.3 Basics of Python


1.3.9 Operators
1.3.10 Precedence and associativity
1.3.11 Python 2 vs Python 3

89 89 89
86
Copyright © 2021, ABES Engineering College
90

Operators
Operators are symbol, used to perform mathematical and logical
operation.

In python operators are categorized


into six categories -

90 90 90
87
Copyright © 2021, ABES Engineering College
91

Arithmetic operators
There are seven arithmetic operators, and these are of:
Operator Meaning Example
Add two operands or x+y
+ unary plus +2
Subtract right operand from the left or x-y
- unary minus -2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ float)
x/y
Modulus - remainder of the division of left operand by the
% right
x % y (remainder of x/y)
Floor division - division that results into whole number
// adjusted to the left in the number line
x // y

** Exponent - left operand raised to the power of right x**y (x to the power y)
91 91 91
88
Copyright © 2021, ABES Engineering College
92

Arithmetic operators
Example of all mentioned arithmetic operators

92 92 92
89
Copyright © 2021, ABES Engineering College
93

Comparison (Relational) Operators

Operator Meaning Example


The comparison operators
are used for comparisons. Greater than -> True if left operand is
> x>y
greater than the right
Less than -> True if left operand is less than
< x<y
Comparison operators the right
compare two values and == Equal to -> True if both operands are equal x == y
evaluate down to a single Not equal to -> True if operands are not
!= x != y
Boolean value ( True / False equal
). >=
Greater than or equal to -> True if left
x >= y
operand is greater than or equal to the right
Less than or equal to -> True if left operand
<= x <= y
is less than or equal to the right
93 93 93
90
Copyright © 2021, ABES Engineering College
94

Comparison (Relational) Operators

Example of all mentioned


comparison operators

It always gives answer either


True or False depending upon
relation.

94 94 94
91
Copyright © 2021, ABES Engineering College
95

Comparison (Relational) Operators

Example –

Note - The == and != operators can actually work with values of any data
type.
95 95
92
95

Copyright © 2021, ABES Engineering College


96

Bitwise Operators

Bitwise operators act on the bits and performs bit by bit operation on
the operands.
Operator Meaning
Example – Evaluate 2 & 7 & Bitwise AND
| Bitwise OR
How it works - ~ Bitwise NOT
Step 1 – Convert 2 in binary  0010 ^ Bitwise XOR
Step 2 – Convert 7 in binary  0111 >> Bitwise right shift
Step 3 – Perform Bitwise & operation
Step 4 – Convert the result back to << Bitwise left shift
decimal

96 96 96
93
Copyright © 2021, ABES Engineering College
97

Bitwise Operators – Cont..

Truth Table

Bitwise NOT
A B A&B A|B A^B A ~A
0 1
0 0 0 0 0
1 0
0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

97 97 97
94
Copyright © 2021, ABES Engineering College
98

Bitwise Operators – Bitwise AND (&)

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 4 – Convert the result (0001)


Step 2 – Convert 3 in binary  0011 back to decimal  1
Step 3 –
1001
0011
0001
98 98 98
95
Copyright © 2021, ABES Engineering College
99

Bitwise Operators – Bitwise OR( | )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 4 – Convert the result (1011)


Step 2 – Convert 3 in binary  0011 back to decimal  11
Step 3 –
1001
0011
1011
99 99 99
96
Copyright © 2021, ABES Engineering College
100

Bitwise Operators – Bitwise XOR ( ^ )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 4 – Convert the result (1010)


Step 2 – Convert 3 in binary  0011 back to decimal  10
Step 3 –
1001
0011
1010
100 100 100
97
Copyright © 2021, ABES Engineering College
101

Bitwise Operators – Bitwise Left shift ( << )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 3 – Convert the result (10010)


Step 2 – Shift 1001 towards left by one back to decimal  18
position and place Zero at end.
1001
10010

101 101 101


98
Copyright © 2021, ABES Engineering College
102

Bitwise Operators – Bitwise Right Shift ( >> )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 3 – Convert the result (100)


Step 2 – Shift 1001 towards right by one back to decimal  4
position.
1001
100
10 01
1 will discarded
102 102 102
99
Copyright © 2021, ABES Engineering College
103

Assignment operators
Assignment operators are used to Operator Example Equivalent to
assign the values to the variables. = x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
a = 5 is a simple assignment
*= x *= 5 x=x*5
operator that assigns the value 5 on
/= x /= 5 x=x/5
the right to the variable a on the
%= x %= 5 x=x%5
left.
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
There are various compound
&= x &= 5 x=x&5
operators in Python like a += 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
103 103 103
100
Copyright © 2021, ABES Engineering College
104

Logical Operators
Logical operators perform Logical AND, Logical OR and Logical NOT operations.

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Truth Table – x y x and y x or y


x not x
T T T T
T F
T F F T F T
F T F T
F F F F
104 104 104
101
Copyright © 2021, ABES Engineering College
105

Logical Operators

Example –

105 105 105


102
Copyright © 2021, ABES Engineering College
106

Identity Operators
Identity Operators – is and is not are the identity operators in Python.

They are used to check if two values (or variables) are located on the same part
of the memory or not.
Operator Meaning
is Gives True if the operands are identical (refer to the same ID or Memory)
is not Gives True if the operands are not identical (do not refer to the ID or Memory)

Example

106 106 106


103
Copyright © 2021, ABES Engineering College
107

Membership Operators
in and not in are the membership operators in Python.

They are used to test whether a value or variable is found in a sequence (string,
list, tuple, set and dictionary) or not.
Operator Meaning
in Gives True if value/variable is found in the sequence otherwise False
not in Gives True if value/variable is not found in the sequence otherwise True

Example

107 107 107


104
Copyright © 2021, ABES Engineering College
108

Precedence and associativity


Operator precedence and associativity decide the priorities of the operator.

 Operator Precedence: This is used in an expression with more than one


operator with different precedence to figure out which operation to perform
first.

 Operator Associativity: If an expression has two or more operators with


the same precedence, then Operator Associativity is used to find. It can
either be Left to Right or from Right to Left.

108 108 108


105
Copyright © 2021, ABES Engineering College
109

Cont..
Precedence and Associativity Table –

109 109 109


106
Copyright © 2021, ABES Engineering College
110

Python 2 vs Python 3

 Python has started its journey in 1989-1990 when people started


implementation on it.
 In year 2000, python 2.0 came with new features and have a healthy support
to python.
 Memory management was the major part evolved in python 2.0.
 But in 2008, python has changed in a revolutionary manner to python 3.0.
 There was no support of backward compatibility in python 3.0.

110 110 110


107
Copyright © 2021, ABES Engineering College
111

Python 2 vs Python 3

Let us have a look to the differences between Python 2 and Python 3.

 In Python 2, print is a statement syntax, but in python 3, print is a built-in


function.
 In python 2, the input was taken from the user by using raw_input() function.
In python 3, input () function is used to take input instead of raw_input().
 When we divide two numbers in python 2, the output is the nearest whole
number. Like 7/2 is 3. In python 3, the fractional numeric value will be shown
as 7/2 is 3.5.
111 111 111
108
Copyright © 2021, ABES Engineering College
112

Python 2 vs Python 3

Let us have a look to the differences between Python 2 and Python 3.

 In for loop, the iterations are used using a xrange function in python 2, which
is replaced by range function in python3.
 Some of the libraries which are available in python 2 are not moved in python
3.
 Similarly, now the developers are making new libraries for python 3 which are
incompatible to python 2.

112 112 112


109
Copyright © 2021, ABES Engineering College
113
Python Programming cycle

 The programming cycle in Python, like in most programming languages, involves several key
steps that developers follow to create, test, and maintain Python programs. Here are the
main phases of the Python programming cycle:
 1. **Problem Definition*
 At the beginning of the programming cycle, you need to clearly define the problem you
want to solve with your Python program. This involves understanding the requirements,
gathering information, and defining the goals and objectives of the program.
 2. **Algorithm Design
 Once you have a clear understanding of the problem, you can design an algorithm to solve
it. An algorithm is a step-by-step plan that outlines the logic and operations your program will
perform. You may use flowcharts, pseudocode, or other tools to represent your algorithm
 3. **Coding
 Coding is the process of translating your algorithm into Python code. You write the actual
program by creating functions, classes, and variables, and implementing the logic to perform
the desired operations. This is where you write the Python statements and expressions that
make
113 up your program. 113 113
110
Copyright © 2021, ABES Engineering College
114

 4. **Testing:After coding, you need to thoroughly test your Python program to


ensure that it works as intended and handles different scenarios and inputs
correctly. Testing involves both unit testing (testing individual functions or
components) and integration testing (testing how different parts of the
program work together)
 5. **Debugging: During testing, you may encounter errors or bugs in your
code. Debugging is the process of identifying and fixing these issues. Python
provides various debugging tools and techniques, such as print statements,
debugging libraries like `pdb`, and integrated development environments
(IDEs) with debugging features.
.

114 114 114


111
Copyright © 2021, ABES Engineering College
115

6. **Optimization:After you have a working program, you can optimize it to improve performance
and efficiency. This may involve refactoring code, using data structures and algorithms more
effectively, and reducing resource consumption.
7. **Documentation: Proper documentation is crucial for maintaining and sharing your Python
code. Document your code by adding comments, docstrings, and README files to explain its
purpose, usage, and any important considerations for other developers.
8. **Version Control:Using a version control system like Git is essential for tracking changes to
your code, collaborating with others, and maintaining a history of your project. You can use
platforms like GitHub or GitLab to host your Python project repositories.
9. **Deployment: If your Python program is meant for production use, you'll need to deploy it to
a server, cloud platform, or other computing environment. This step involves configuring the
necessary infrastructure and ensuring that the program runs smoothly in a production
environment.
10. **Maintenance:Software maintenance is an ongoing process that involves fixing bugs,
adding new features, and adapting the program to changing requirements. Regularly update
and115improve your Python code as needed 115 115
112
Copyright © 2021, ABES Engineering College
Memory Management in Python: 116

 Memory management in Python is primarily handled by the Python memory


manager, which is responsible for allocating and deallocating memory for
objects in your Python programs. Python uses a combination of techniques
for memory management, including:
Reference Counting: Python keeps track of how many references there are to
an object. When an object's reference count drops to zero, it means the object
is no longer accessible, and Python can reclaim the memory used by that
object.
Garbage Collection: In addition to reference counting, Python uses a cyclic
garbage collector to identify and collect objects that are no longer reachable,
even if they have circular references (references to each other).

116 116 116


113
Copyright © 2021, ABES Engineering College
117

 Memory Pools: Python uses a system of memory pools for small objects to
reduce memory fragmentation and improve memory allocation efficiency.
 Dynamic Typing: Python's dynamic typing means that objects can change
their type during runtime, which can have implications for memory
management since objects might need to be reallocated if their type
changes.
 Memory Optimizations: Python includes various memory optimization
techniques, such as interning small integers and string literals, to reduce
memory overhead.

117 117 117


114
Copyright © 2021, ABES Engineering College
118
PEP 8:

 PEP 8 is the Python Enhancement Proposal 8, titled "Style Guide for Python
Code." It is a document that provides guidelines and recommendations for
writing Python code that is readable and consistent. PEP 8 covers topics
such as naming conventions, code layout, indentation, whitespace, and
more. Following PEP 8 helps make your Python code more understandable
and maintainable, especially when working on projects with multiple
contributors.

118 118 118


115
Copyright © 2021, ABES Engineering College
119
Some key points from PEP 8 include:

 Use 4 spaces per indentation level.


 Limit all lines to a maximum of 79 characters (or 72 for
docstrings/comments).
 Use blank lines to separate functions, classes, and blocks of code inside
functions.
 Use lowercase with underscores for function and variable names (e.g.,
my_function, my_variable).
 Use CapitalizedWords (CamelCase) for class names (e.g., MyClass).
 Import modules in separate lines and put them at the top of the file.
 Avoid extraneous whitespace.
 Use consistent naming conventions for constants (e.g., MAX_LENGTH)

119 119 119


116
Copyright © 2021, ABES Engineering College
Python is called as dynamic and strongly typed 120

language?
 Python is called a dynamic and strongly typed language due to the way it
handles data types and variable binding during runtime. Let's break down
these two characteristics:
 1. **Dynamic Typing**: In Python, variable types are not explicitly declared when you define
a variable. Instead, the data type of a variable is determined dynamically at runtime based on
the value it holds. This means that you can assign different types of values to the same
variable during the execution of your program. For example:
 ```python
 x = 5 # x is an integer
 x = "Hello" # x is now a string
 Python's dynamic typing offers flexibility and simplifies the coding process because you don't
need to declare the data type of a variable explicitly. The interpreter determines the
appropriate data type based on the value assigned to the variable.

120 120 120


117
Copyright © 2021, ABES Engineering College
121

 2. **Strong Typing: Python is also considered a strongly typed language


because it enforces strict rules regarding type compatibility and type
conversion. In strongly typed languages, operations between incompatible
data types are either prohibited or require explicit type conversion.
For example, in Python, you cannot directly concatenate a string and an integer
without converting the integer to a string:
 ```python
 x = "Hello"
 y=5
 result = x + y # This will raise a TypeError

121 121 121


118
Copyright © 2021, ABES Engineering College
122

 To perform this operation, you need to explicitly convert the integer to a string:
 ```python
 x = "Hello"
 y=5
 result = x + str(y) # Now it works
 Python's strong typing helps prevent unintended type-related errors and promotes code
safety.
 In summary, Python's dynamic typing allows for flexibility in variable assignments by
determining types at runtime, while its strong typing ensures that type-related operations are
well-defined and explicit, reducing the likelihood of subtle bugs and errors. These
characteristics contribute to Python's reputation as a language that is both flexible and safe.

122 122 122


119
Copyright © 2021, ABES Engineering College
123
Mutable and immutable data type

 In Python, data types are categorized into two main groups: mutable and
immutable. These categories describe how the data stored in variables of
these types can be modified. Here's a breakdown of the differences between
mutable and immutable data types:
 **Immutable Data Types**:
 1. **Immutable** means that once an object of an immutable data type is
created, it cannot be changed or modified. Any operation that appears to
modify the data actually creates a new object with the modified value.
 2. Immutable objects are hashable, meaning they can be used as keys in
dictionaries and elements in sets because their value will not change.
 Examples of immutable data types in Python include `int`, `float`, `str`,
`tuple`, and `frozenset`.
123 123 123
120
Copyright © 2021, ABES Engineering College
124

 Examples of Immutable Data Types:


 ```python
 # Immutable data types
 x = 42 # int
 y = 3.14 # float
 s = "Hello" # str
 t = (1, 2, 3) # tuple

124 124 124


121
Copyright © 2021, ABES Engineering College
125

 Mutable Data Types**:


 1. **Mutable** means that objects of these data types can be changed after
they are created. You can modify their contents, add or remove elements,
etc., without creating a new object.
 2. Mutable objects are not hashable, so they cannot be used as dictionary
keys or elements in sets.
Examples of mutable data types in Python include `list`, `dict`, and `set`.
 Examples of Mutable Data Types:
 # Mutable data types
 lst = [1, 2, 3] # list
 dct = {"a": 1, "b": 2} # dict
 st = {1, 2, 3} # set
125 125 125
122
Copyright © 2021, ABES Engineering College
126
Why Immutability Is Important**:

 1. **Predictable Behavior**: Immutable objects provide predictability in your code because


you can trust that once you create them, their value won't change. This predictability
simplifies debugging and reasoning about your code.
 2. **Hashability**: Immutable objects can be used as keys in dictionaries and elements in
sets because their hash value remains constant. This is essential for data structures that rely
on efficient hash-based lookups.
 3. **Safety in Concurrency**: In multithreaded or multiprocessing environments, immutable
objects are safer to work with because you don't have to worry about other threads or
processes modifying the same object concurrently.
 4. **Functional Programming**: Immutability aligns well with functional programming
principles, making it easier to write functional-style code in Python.
 5. **Caching**: Because immutable objects have constant values, they can be cached and
reused, which can improve performance in certain situations.

126 126 126


123
Copyright © 2021, ABES Engineering College
127

Summary
 Python is an open-source, high level, interpreter- based language that can be used for scientific
and non-scientific computing purposes.
 Comments are non-executable statements in a program.
 An identifier is a user defined name given to a variable or a constant in a program.
 Datatype conversion can happen either explicitly or implicitly.
 Operators are constructs that manipulate the value of operands.
 Python has input() function for taking user input.
 Python has print() function to output data to a standard output device.
 There are several data types in Python — integer, boolean, float, complex, string, list, tuple, sets,
None and dictionary.

127 127 127


124
Copyright © 2021, ABES Engineering College
References 128

1. https://docs.python.org/3/tutorial/controlflow.html

2. Think Python: An Introduction to Software Design, Book by Allen B. Downey

3. Head First Python, 2nd Edition, by Paul Barry

4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna Jablonski,
Fletcher Heisler

5. https://www.fullstackpython.com/turbogears.html

6. https://www.cubicweb.org

7. https://pypi.org/project/Pylons/

8. https://www.upgrad.com/blog/python-applications-in-real-world/

9. https://www.codementor.io/@edwardbailey/coding-vs-programming-what-s-the-difference-yr0aeug9o
128 128 128
125
Copyright © 2021, ABES Engineering College
129

Thank You

129 129 129


126
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
130

UNIT:2
Control Flow System
Day 1

130 130 130

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


General Guideline 131

© (2021) ABES Engineering College.

This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.

131 131 131


2
Copyright © 2021, ABES Engineering College
Objective of Control Flow System 132

To understand the purpose and syntax of decision control statements.

To understand the purpose and syntax of Iterative/looping statements and jump statements.

To develop python programs with conditions and loops.

To apply the knowledge of conditions, loops and jump in solving real time problems.

To create python programs with decision ,looping and jump statements.

132 132 132


3
Copyright © 2021, ABES Engineering College
Topics Covered 133

Day 1 Day 2 Day 3 Day 4

2.1 Introduction 2.3 Iterative/ Looping 2.3 Iterative/ Looping 2.4 Jump Statements
2.2 Selection / Statements Statements • Break
Decision control • While loop • Range() • Continue
• Nested While Function
statement
•Simple If statement
loop • For loop 2.5 Else with Loop
• Nested for • While with else
•If Else statement
loop • For with else
•If-Elif statement
•Nested If Else
statement

133 133 133


4
Copyright © 2021, ABES Engineering College
Session Plan - Day 1 134

2.1. Introduction to Decision Control Statements


2.2. Selection / Decision control statement
• Simple If Statements
• If Else Statements
• If ..elif..else statements
• Nested If Else Statements
• Examples
• Review questions
• Summary

134 134 134


5
Copyright © 2021, ABES Engineering College
135
Introduction

Control flow of the program is:

The order in which the code of the program executes.


Regulated by:

Conditional statements.
Iterative/looping statements.

135 135 135


6
Copyright © 2021, ABES Engineering College
136
Contd..
 Conditional statement examples: Based on certain conditions, we take decisions
in our daily life.
• Darkness in the room: Turn on lights. • Weather is Cold: Drink Coffee
• No Darkness: Do Nothing • Weather is not Cold: Softdrink

136 136 136


7
Copyright © 2021, ABES Engineering College
137
Contd..
 Iterative Looping statements examples: For taking decisions we perform various
actions and repeat the same action many times.

Real Life Scenario:

 Suppose you want to buy a new t-shirt, visit


the shop.
 If you do not found a shirt of your choice, visit
to the new shop.
 Until your desired shirt is found, action is
performed again and again.
 This is called looping.

137 137 137


8
Copyright © 2021, ABES Engineering College
138

Selection/decision control statements


 It is used to control the flow of execution of program depending upon
condition:

 if the condition is true then the code block will execute


 if the condition is false then code block will not execute.

Real Life Scenario:


Consider the grading system for students:
 Excellent : Above 95%.
 Good: Greater than 80% & less than
equal to 95%.
 Average: Greater than 60% & less than
equal to 80%.
 Below average: Less than 60%

138 138 138


9
Copyright © 2021, ABES Engineering College
139

Revision of Flowchart

Used for start and stop.


Used for decision making.

Used for input/output.

Used for processing statement.

Connector / flow

139 139 139


10
Copyright © 2021, ABES Engineering College
140

Flowchart of the grading system

On the basis of the conditions, corresponding block of the


code will be executed or not.

Consider the grading system for students:

 Excellent :Above 95%.


 Good :Greater than 80% &less than equal t 95%.
 Average : Greater than 60% & less than equal to 80%.
 Below average: Less than 60%

140 140 140


11
Copyright © 2021, ABES Engineering College
141

Types of decision/selection control statements:

 Simple if

 if-else

 if..elif..else

 Nested...if…else

141 141 141


12
Copyright © 2021, ABES Engineering College
142

Simple if statement
 if evaluates whether a condition is:
True
False.

 if block is executed:
if and only if the value of its condition expression is
true.

Note: As we use curly braces in ‘C’ Language to define the scope of conditions and loops; in
the same manner we use colon (:) and indentation in Python.

142 142 142


13
Copyright © 2021, ABES Engineering College
143

Syntax of Simple if

143 143 143


14
Copyright © 2021, ABES Engineering College
144

Examples
 Print whether a number is even or not.
Case-1 : When n is even. Case-2 : When n is not even

144 144 144


15
Copyright © 2021, ABES Engineering College
145

Examples
 A program to increment a number if it is positive.

Explanation:
 The condition x>0 is True for value of x = 10 so the statements in the block of code will be
executed.
 The statement x = x+1 will increment the value of x by 1 i.e. x = 10 + 1; x = 11 and statement
print (x) will print x value as 11.
145 145 145
16
Copyright © 2021, ABES Engineering College
146

if else Statement
 It checks whether a condition is true or false.

 If a condition is true,

 The if statement executes


 Otherwise, the else statement executes.

146 146 146


17
Copyright © 2021, ABES Engineering College
147

Syntax of if else Statement

147 147 147


18
Copyright © 2021, ABES Engineering College
148

Example
 A program to print “Excellent” if marks is greater than 95 otherwise print “Not
Excellent”

Explanation:
 For input 68, condition marks > 95 is False. Therefore, else statement print (“Not Excellent”) is
executed and output will be “Not Excellent”.
148 148 148
19
Copyright © 2021, ABES Engineering College
if..elif..else statement 149

Extension of the if-else statement

For a multiple conditional statements


 We use if-elif statement.

Note: The conditional expression of if-elif-else are executed from top to bottom in a sequential manner. An elif
statements are known as elif Ladder.
149 149 149
20
Copyright © 2021, ABES Engineering College
150

Syntax of if..elif..else statement

150 150 150


21
Copyright © 2021, ABES Engineering College
151

Example

Explanation:
 For input 88, condition marks > 95 is False & control goes to next elif statement (marks>80 and
marks<=95), which is True and statement print (“Good”) will be executed.
 The output will be “Good”.
151 151 151
22
Copyright © 2021, ABES Engineering College
Nested if-else statement 152

 When an if-else statement is present inside the body of another “if” or “else” then
this is called nested if else.

152 152 152


23
Copyright © 2021, ABES Engineering College
153

Syntax of Nested if..else statement

153 153 153


24
Copyright © 2021, ABES Engineering College
154

Example

 A program to take age as input from user and print “You are less than 18” if age is less
than 18, otherwise print “You are above 18”.Also check that age could not be less than 0.
If so then print “Age could not be less than 0”.

154 154 154


25
Copyright © 2021, ABES Engineering College
155

Example

 A program to take age as input from user and print

 “You are less than 18” if age is less than 18

 otherwise print “You are above 18”.

 Also check that age could not be less than 0.

 If so then print “Age could not be less than 0”.

155 155 155


26
Copyright © 2021, ABES Engineering College
156
Can you answer these questions?

1. Which one of the following is a valid Python if statement :

A) if a>=2 :

B) if (a >= 2)

C) if (a => 22)

D) if a >= 22

156 156 156


27
Copyright © 2021, ABES Engineering College
157

3.Which of following is not a decision-making statement?

A) if-elif statement

B) for statement

C) if -else statement

D) if statement

157 157 157


28
Copyright © 2021, ABES Engineering College
158

4.Predict the output of the following code:

A) No output

B) okok

C) ok

D) None of above

158 158 158


29
Copyright © 2021, ABES Engineering College
159

5. What is the output of the following code snippet?

A) Launch a Missile

B) Let's have peace

C) 0.3

D)None

159 159 159


30
Copyright © 2021, ABES Engineering College
160

6. Which of the following is true about the code below?

A) x will always equal 0 after this code executes for any value of x

B) if x is greater than 2, the value in x will be doubled after this code executes

C) if x is greater than 2, x will equal 0 after this code executes

160 160 160


31
Copyright © 2021, ABES Engineering College
161
Summary

 Control statement are statements that control the flow of execution of statements so that
they can be executed repeatedly and randomly.

 The if statement executes a group of statements depending upon whether a condition is


true or false.

 The if..else statement executes a group of statements when a condition is true;


Otherwise, it will execute another group of statements.

 The if..elif statement is an extension of the if-else statement. When we have multiple
conditional statements, then we use if-elif statement.

 When an if..else statement is present inside the body of another “if” or “else” then this is
called nested if else.
161 161 161
32
Copyright © 2021, ABES Engineering College
Session Plan - Day 2 162

2.3 Iterative looping Statements


• While loop
• Nested While loop
• Examples
• Review Questions
• Summary

162 162 162


33
Copyright © 2021, ABES Engineering College
163
Iterative/Looping Statements
Sometimes we need to perform certain operations
again and again.

Real Life Scenario:

 A teacher decide to grade 75 students on the basis of


marks.
 He/she wants to do this for whole class.
 Teacher would repeat grading procedure for each student
in the class.
 This is called iterative/ looping.

163 163 163


34
Copyright © 2021, ABES Engineering College
164
Types of loops in Python

 While loop

 Nested While loop

 For loop

 Nested for loop

164 164 164


35
Copyright © 2021, ABES Engineering College
While loop 165

 It is used to repeat a block of code as long as the given condition is true.

165 165 165


36
Copyright © 2021, ABES Engineering College
Syntax of While loop 166

 Boolean expression is checked first.

 The body of the loop is entered only if the


Boolean expression evaluates to True.

 After one iteration, the Boolean expression


is checked again.

 This process continues until the Boolean


expression evaluates to False.

166 166 166


37
Copyright © 2021, ABES Engineering College
Example 167

Write a Python Program to print 4 Natural Numbers using i.e. 1,2,3,4 using While
loop.

167 167 167


38
Copyright © 2021, ABES Engineering College
Nested While loop 168

 Nested while loop is called when we use


while loop inside a while loop.

 We can use any number of while loop inside


a while loop.

 Main while loop as outer while loop and


nested while loop as inner while loop.

168 168 168


39
Copyright © 2021, ABES Engineering College
Syntax of Nested While loop: 169

 Outer while loop runs m number of times.

 Inner while loop runs n number of times.

 The total no. of iterations would be m*n.

169 169 169


40
Copyright © 2021, ABES Engineering College
Example of Nested While loop: 170

 Write a program to demonstrate While loop.

170 170 170


41
Copyright © 2021, ABES Engineering College
171

1. What will be the output of the following code snippet?

Options

A. None

B. Python

C. Ppppp

D. PPPPP

171 171 171


42
Copyright © 2021, ABES Engineering College
172

2. What will be the output of the following code snippet?

A. 0 1 2

B. 2 3

C. 0 1 2 0

D. None of the above

172 172 172


43
Copyright © 2021, ABES Engineering College
173

3. What should be the value of the variables num1 and num2 in the code snippet
below if the output expected is 4?

A. 16,6

B. 12,5

C. 8,2

D. 16,2

173 173 173


44
Copyright © 2021, ABES Engineering College
174
Summary:

 While loop is used to iterate block of codes repeatedly until given condition is
True
 While loop present inside another while loop it is called as nested while loop.
 The nested while loop is while statement inside another while statement.

174 174 174


45
Copyright © 2021, ABES Engineering College
Session Plan - Day 3 175

2.3 Iterative looping Statements


• Range()
• For loop
• Nested for loop
• Examples
• Review Questions
• Summary

175 175 175


46
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
176

Introduction to Iterative/looping
statements:

176 176 176

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


177

ABES Engineering College, Ghaziabad


Affiliated to Dr. A.P.J Abdul Kalam Technical University, Lucknow
Department of CSE-Data Science

Assignment No.1

Subject: Python (BCC-302)

Submission Date 10/10/2023

Faculty Name: Tarun Kumar Gautam Sem & Section: 2rd A,B
C

Note: Attempt any Four Question 5*4=20

Q. N. Question Statement Bloom


Level
1 How memory is management in python and Write a Program to print even length words
In string? K2
2 Discuss why python is called as dynamic and strongly typed languages? K2

3 Explain the Programming python cycle in python. K2

4 Define operator associativity with its type. What are factors for expression evaluations?K2

5 Can we make multiple comments in python? Do we need to declare variables with data
type in python? K2

177 177 177


Printed Page: 1 of 2
178
Subject Code: KNC302
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM III) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 50
Note: Attempt all Sections. If you require any missing data, then choose suitably.

SECTION A
1. Attempt all questions in brief. 2*5 = 10
Qno Questions CO
(a) Explain the Programming Cycle for Python in detail. 1
(b) What will be the output of the following Python code? 2
i=0
while i< 3:
print(i)
i += 1
else:
print(0)
(c) What will be the output of the following Python code? 3
def cube(x):
return x * x * x

1
x = cube(3)

13
0
print x
29

(d) How do we define an Interface for an ADT? 4

2.
2_

24
(e) How do you perform a search in Python? 5
2P

5.
SECTION B

.5
P2

2. Attempt any three of the following: 5*3 = 15


17
Qno Questions CO
Q

|1

(a) What do you mean by Python IDE? Explain in detail. 1


(b) How can you randomize the items of a list in place in Python? 2
36

(c) Explain Tuples and Unpacking Sequences in Python Data Structure. 3


:
25

(d) What are File input and output operations in Python Programming? 4
(e) Solve the Tower of Hanoi problem for n= 3 disk and show all the steps. 5
:
13

SECTION C
2
02

3. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
-2

(a) Write a program in Python to execute the Selection sort algorithm. 5


ar

(b) Explain why python is considered an interpreted language. 1


M
2-

4. Attempt any one part of the following: 5 *1 = 5


|2

Qno Questions CO
(a) Write a Python program to construct the following pattern, using a 2
nested for loop.

*
**
***
****
*****
178 178 178
QP22P2_290 | 22-Mar-2022 13:25:36 | 117.55.242.131
Printed Page: 2 of 2
179
Subject Code: KNC302
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

BTECH
(SEM III) THEORY EXAMINATION 2021-22
PYTHON PROGRAMMING
****
***
**
*
(b) Write a program to produce Fibonacci series in Python. 4

5. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) Write a Python program to change a given string to a new string where 3
the first and last chars have been exchanged.
(b) Write a Python program to add an item in a tuple. 3

6. Attempt any one part of the following: 5*1 = 5


Qno Questions CO
(a) How to create and import a module in Python? 4
(b) Explain the algorithm Sieve of Eratosthene used in Python 4
Programming.

1
13
0
29

7. Attempt any one part of the following: 5*1 = 5

2.
2_

Qno Questions CO

24
(a) Write a Recursive function in python BinarySearch(Arr,l,R,X) to 5
2P

5.
search the given element X to be searched from the List Arr having R

.5
P2

elements, where l represent slower bound and R represents the upper


17
bound.
Q

|1

(b) Explain the terms Merge List and Merge Sort in Python Programming. 5
: 36
: 25
13
2
02
-2
ar
M
2-
|2

179 179 179


QP22P2_290 | 22-Mar-2022 13:25:36 | 117.55.242.131
Printed Page: 1 of 4
Subject Code: KNC302
180

0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

B.TECH
(SEM III) THEORY EXAMINATION 2020-21
PYTHON PROGRAMMING
Time: 3 Hours Total Marks: 100
Note: 1. Attempt all Sections. If require any missing data; then choose suitably.

SECTION A
1. Attempt all questions in brief.
Q no. Question Marks CO
a. What is the use of “raise” statement? Describe with an example. 2 5

b. Write a recursive Python function “rprint” to print all elements in a 2 3


list in reverse.
rprint([]) prints nothing
rprint([1,2,3]) prints 3 2 1

c. Describe the behavior of “range (s, e)” in Python. 2 3

d. Explain the use of “with” construct in Python with an example 2 5

P
program.
0Q

1
13
e. Which of the following statements produce an error in Python? 2 1
29

x, y, z = 1,2,3 # s1

2.
0E

a, b = 4,5,6 # s2

24
P2

u = 7,8,9 # s3

5.
(List all the statements that have error.)
_Q

.5
f. Explain the role of precedence with an example. 17 2 1
TU

g. How do you read an input from a user in Python to be used as an integer 2 5


|1

in the rest of the program? Explain with an example.


AK

56

h. Consider the program: 2 1


7:
:0

x = ['12', 'hello', 456]


14

x[0] *= 3
x[1][1] = 'bye'
1
02

Explain why this program generates an error.


-2
ar

i. What is the output of the following program? 2 5


M

(lambda x,y : y - 2*x) (1, 11)


2-
|1

j. Explain the use of lt function in a class Python? 2 5

180 180 180


AKTU_QP20E290QP | 12-Mar-2021 14:07:56 | 117.55.242.131
Printed Page: 2 of 4
Subject Code: KNC302
181
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

SECTION B
2. Attempt any three of the following:
Q no. Question Marks CO
a. Write a Python function removekth(s, k) that takes as input a 10 5
string s and an integer k>=0 and removes the character at index k. If k
is beyond the length of s, the whole of s is returned. For example,

removekth(“PYTHON”, 1) returns “PTHON”


removekth(“PYTHON”, 3) returns “PYTON”
removekth(“PYTHON”, 0) returns “YTHON”
removekth(“PYTHON”, 20) returns “PYTHON”

b. Write a Python function average to compute the average of a list of 10 3


numbers. The function must use try-except to handle the case
where the input list is empty. Further, in that case the average for the
empty list should be set to 0.0 using the except block.

c. Describe the differences between a linear search and a binary search? 10 5

P
d. Write a function lessthan(lst, k) to return list of numbers less 10
0Q 4
than k from a list lst. The function must use list comprehension.

1
13
Example:
29

lessthan([1, -2, 0, 5, -3], 0) returns [-2, -3]

2.
0E

24
e. Write a program factors(N) that returns a list of all positive divisors 10 2
P2

5.
of N (N>=1). For example:
_Q

.5
factors(6) returns [1,2,3,6] 17
factors(1) returns [1]
TU

factors(13) returns [1,13]


|1
AK

56

SECTION C
7:

3. Attempt any one part of the following:


:0

Q no. Question Marks CO


14

a. How can you create Python file that can be imported as a library as well 10 5
1

as run as a standalone script?


02
-2

b. Describe the difference between 10 5


ar

import library
and
M
2-

from library import *


when used in a python program. Here library is some python
|1

library.

181 181 181


AKTU_QP20E290QP | 12-Mar-2021 14:07:56 | 117.55.242.131
Printed Page: 3 of 4
Subject Code: KNC302
182
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

4. Attempt any one part of the following:


Q no. Question Marks CO
a. Write a function makePairs that takes as input two lists of equal 10 2
length and returns a single list of same length where k-th element is the
pair of k-th elements from the input lists. For example,

makePairs([1,3,5,7],[2,4,6,8])
returns [(1,2),(3,4),(5,6),(7,8)]
makePairs([],[])
returns []

b. Show an example where both Keyword arguments and Default 10 4


arguments are used for the same function in a call. Show both the
definition of the function and its call.

5. Attempt any one part of the following:

P
Q no. Question 0Q Marks CO
a. Explain why Python is considered an interpreted language. 10 1

1
13
29

b. What is short circuit evaluation? What is printed by the following 10 1

2.
0E

Python program?

24
a = 0
P2

5.
b = 2
_Q

.5
c = 3 17
x = c or a
TU

print(x)
|1
AK

56
7:
:0
14
1
02
-2
ar
M
2-
|1

182 182 182


AKTU_QP20E290QP | 12-Mar-2021 14:07:56 | 117.55.242.131
Printed Page: 4 of 4
Subject Code: KNC302
183
0Roll No: 0 0 0 0 0 0 0 0 0 0 0 0 0

6. Attempt any one part of the following:


Q no. Question Marks CO
a. Write a Python program, triangle(N), that prints a right triangle 10 3
having base and height consisting of N * symbols as shown in these
examples:

triangle(3) prints:
*
**
***

triangle(5) prints:
*
**
***
****
*****

b. Write a Python program, countSquares(N), that returns the count 10 4


of perfect squares less than or equal to N (N>1). For example:

P
countSquares(1) returns 1
0Q

1
# Only 1 is a perfect square <= 1

13
29

countSquares(5) returns 2

2.
# 1, 4 are perfect squares <= 5
0E

24
countSquares(55) returns 7
P2

# 1, 4, 9, 16, 25, 36, 49 <= 55

5.
_Q

.5
17
7. Attempt any one part of the following:
TU

|1

Q no. Question Marks CO


AK

a. Write a Python function, alternating(lst), that takes as 10 4


56

argument a sequence lst. The function returns True if the elements


7:

in lst are alternately odd and even, starting with an even number.
:0

Otherwise it returns False. For example:


14

alternating([10, 9, 9, 6]) returns False


alternating([10, 15, 8]) returns True
1
02

alternating([10]) returns True


alternating([]) returns True
-2

alternating([15, 10, 9]) returns False


ar
M
2-

b. Write a Python function, searchMany(s, x, k), that takes as 10 3


argument a sequence s and integers x, k (k>0). The function returns
|1

True if there are at most k occurrences of x in s. Otherwise it returns


False. For example:
searchMany([10, 17, 15, 12], 15, 1) returns True
searchMany([10, 12, 12, 12], 12, 2) returns False
searchMany([10, 12, 15, 11], 17, 18) returns True

183 183 183


AKTU_QP20E290QP | 12-Mar-2021 14:07:56 | 117.55.242.131
184

184 184 184


185

185 185 185


186

CODING OF UNIT 1 AND UNIT 2

UNIT:1
C:\Users\Tarun\AppData\Local\Programs\Python\Python310

anconda: http://localhost:8889/notebooks/Untitled1.ipynb?kernel_name=python3

1:

a=10

print ("value of a:", a)

a = int (input ("enter value of a"))

b = str (input ("name of student"))

a = float (input ("enetr value of a"))

2:

print ("Welcome to Guru99")

print (8 * "\n")

print ("Welcome to Guru99")

out:

Welcome to Guru99

186 186 186


187

3:

p = float(input ("enter money lent:"))

r = float(input ("enter rate of intrest:"))

t = float(input ("enter times in yr:"))

SI = (p*r*t)/100

amountpay = p+SI

print ("total ampunt pay:",amountpay)

4:

n = int (input("how many times ?"))

print ("good morning"*n)

5:

import math

m = float (input ("enter mass:"))

c = 3*pow(10,8)

e = m*c*c

print ("energy:",e)

6:

Welcome to Guru99

a="Guru"

b = 99

print(a+str(b))

out:Guru99

187 187 187


188

7:

a=2

b=3

c=a+b

print (c)

8:

x=10

print (x)

x= "i m student of ABES"

print (x)

9:

name= input ("enter name :")

print ("ABES STUDENT :",name)

10:

n1 =input ("enter number 1:")

n2= input ("enter number 2:")

n3 =input ("enter number 3:")

print ("original numbers:",n1,n2,n3)

11:

n1 = 10

188 188 188


189

n2 = 20

n3 = 30

print ("original numbers:",n1,n2,n3)

out:

original numbers: 10 20 30

after swapping: 20 30 10

12:

n1,n2,n3=n2,n3,n1

print ("after swapping:",n1,n2,n3)

n1 =input ("enter number 1:")

n2= input ("enter number 2:")

n3 =input ("enter number 3:")

print ("original numbers:",n1,n2,n3)

n1,n2,n3=n2,n3,n1

print ("after swapping:",n1,n2,n3)

13:

x,y=7,2

x,y=y,x+1

print (x,y)

output: 2 8

189 189 189


190

14:

x=20

y=40

print ("enter no x, y:", x,y)

x=x-5

y=y-6

print ("new nuber:", x,y)

15:

x=20

y=40

print ("enter no x, y:", x,y)

x=y

y=x

print ("after swapping", x,y)

20 40

40 40

16:

x=20

y=40

c=5

print ("enter no x, y,c:", x,y,c)

190 190 190


191

x=y

y=c

c=x

print ("after swapping", x,y,c)

20 40 5

40 5 40

17:

x=20

y=40

c=5

print ("enter no x, y,c:", x,y,c)

k=x

x=y

y=c

c=x

x=k

print ("after swapping", x,y,c)

out:

enter no x, y,c: 20 40 5

after swapping 20 5 40

18:

num = int (input ("enter number:"))

cube = num*num*num

print ("number is :",num)

print ("its cube is :",cube)

191 191 191


192

19:

L = float (input ("enter length of rectangle:"))

B= float (input ("enter breath of rectangle:"))

area = L*B

print ("length is :",L)

print ("Breath is :",B)

print ("area is :",area)

20:

mile = int (input ("enter miles"))

km = mile/0.6

print ("miles :",mile)

print ("kilometer :", km)

21:

x = int (input ("enter x"))

y = int (input ("enter y"))

z = int (input ("enter z"))

avg = (x+y+z)/3

print ("value of x,y,z :",x,y,z)

print ("avarage :",avg)

22:

string :

192 192 192


193

print ("enetr the value")

print (‘ram \ shyam \ ramu’)

23:

numerical literals

a= 10

b =23.6

c = 10+5j

print (a)

print (b)

print (c)

24:

list and tuple

c =[1,2,3,4]

b =(1,2,3,4)

print (c)

print (b)

d =['am','bt','red']

e =('am','bt','red')

print (d)

print (e)

25:

a = 10

b = 23.5

print (a,b,sep='--')

26:

193 193 193


194

a = 10

b = 23.5

print (a,b,sep='\n')

27:

x=4

y=5

print ("x+y:",x+y)

print ("x-y:",x-y)

print ("x*y:",x*y)

print ("x //y:",x//y)

print ("x**y:",x**y)

Unit 2:
1: string :

print ("enetr the value")

print (‘ram \ shyam \ ramu’)

2: numerical literals

a= 10

b =23.6

c = 10+5j

print (a)

print (b)

print (c)

3: list and tuple

c =[1,2,3,4]

b =(1,2,3,4)

print (c)

194 194 194


195

print (b)

d =['am','bt','red']

e =('am','bt','red')

print (d)

print (e)

4: a = 10

b = 23.5

print (a,b,sep='--')

5:

a = 10

b = 23.5

print (a,b,sep='\n')

6:

x=4

y=5

print ("x+y:",x+y)

print ("x-y:",x-y)

print ("x*y:",x*y)

print ("x //y:",x//y)

print ("x**y:",x**y)

1: odd/ even

n= int (input ("enter no"))

if (n%2==0):

print ("even")

else:

195 195 195


196

print ("odd")

2: less or greater

n= int (input ("enter no"))

if (n>0):

n =n+1

print ("value of no",n)

else:

print ("value of n is less than 0")

3:

n= int (input ("enter no"))

if (n>95):

print ("exellent",n)

else:

print ("not exellent")

4:

marks= int (input ("enter your percentage"))

if (marks>95):

print ("exellent")

elif(marks>80 and marks <=95):

print ("good")

elif(marks>60 and marks <=80):

print ("average")

else:

print ("below average")

5:

marks = int (input ("enter your age in years"))

if marks>95:

print ("exellent")

elif marks>80 and marks <=95:

196 196 196


197

print ("good")

elif marks>60 and marks <=80:

print ("average")

else:

print ("below average")

6:

age = int (input ("enter your age in years"))

if age>0:

if age<18:

print ("your age is less than 18")

else:

print ("you are above 18")

else:

print ("age could not be less thyan 0")

7:

x =3

if (x>2 or x<5) and x==6:

print ("ok")

else:

print ("no output")

8:

y =0.3

if y!=0.3:

print ("lunch missile")

else:

print ("let have peace")

197 197 197


198

9:

x=3

if (x>2):

x =x*2;

if (x>4):

x=0;

print (x)

10:

i =1

while (i<5):

print (i)

i=i+1

11:

condition1 =1

while (condition1<=3):

print (condition1,"outer loop executed")

condition2=1

while condition2<=3:

print (condition2,"inner loop executed")

condition2+=1

condition1+=1

13:

i=0

while i<3:

print(i)

i+=1

else:

198 198 198


199

print (0)

14:

num1=16

num2=6

while (num1>=2):

if(num1>num2):

num1=num1/2

else:

print(num1)

break

15: range

print (list(range(5)))

print (list(range(1,5)))

print (list(range(1,20,2)))

print (list(range(100,20,-2)))\

16:

for i in range (10):

print (i)

17:

num = range (10)

for i in num:

print (i)

18:

num =5

for i in range (1,11):

print (i,"*5=",i*5)

19:

199 199 199


200

var=10

for i in range (10):

for j in range (2,10,1):

print (i,j)

20:

for i in range (2):

for j in range (3):

print (i,j)

20:

string ="TECHNOLOGY"

for j in range(len(string)):

print (string[4])

21:

num1 = 5

num2 = 4

while ( num2>=1):

print ('&')

for index in range (1,num1+1):

print ('+')

num2= num2-1

print ('*')

22:

for i in range (0,51):

if (i%2!=0 and i%3!=0):

print (i)

23:

i=1

while i<5:

200 200 200


201

if i==3:

break

print (i)

i=i+1

print ("ALL DONE")

24:

i=1

while i<5:

if i==3:

i=i+1

continue

print (i)

i=i+1

print ("ALL DONE")

25:

condition=1

while (condition<5):

print (condition)

condition=condition+1

else:

print ("else part executed")

26:

condition=1

while (condition<5):

print (condition)

condition=condition+1

if (condition==3):

break

201 201 201


202

else:

print ("else part executed")

27:

for i in range (5):

print (i)

else:

print ("loop finished")

28:

for i in range (11):

if (i==5):

break

print (i)

else:

print ("loop finished")

29:

color_name=['Red','Green','Blue','Pink']

name=input("Enter color name to be search")

for c in color_name:

if name==c:

print(f"Color_name{c} found in List")

break

else:

print("color name not found in list")

30:

n=int(input("Enter any positive number"))

for i in range (2,n):

if n%i==0:

print(f"{n} is not prime number")

break

202 202 202


203

else:

print(f"{n} is a prime number")

31:

for i in range (6):

if (i==3):

continue

print (i)

32:

for i in range (10):

print(i)

if (i==7):

print ("break")

break

203 203 203


204

G
TK
BY

204 204 204


205

G
TK
BY

205 205 205


206

G
TK
BY

206 206 206


207

G
TK
BY

207 207 207


208

G
TK
BY

208 208 208


209

G
TK
BY

209 209 209


210

G
TK
BY

210 210 210


211

G
TK
BY

211 211 211


212

G
TK
BY

212 212 212


213

G
TK
BY

213 213 213


214

G
TK
BY

214 214 214


215

G
TK
BY

215 215 215


216

INDEX:
S.NO TOPIC PAGE
NO
1. NOTES OF UNIT-2 2
2. QIESTION BANK OF UNIT-2 90
3. SOLUTION OF QUESTION BANK OF 92
UNIT -2
4. NOTES OF UNIT-3 101
5. QIESTION BANK OF UNIT-3 258
6. SOLUTION OF QUESTION BANK OF 260
UNIT -3
7. IMPORTANT PROGRAMMING 281
QUESTION FROM LAST YEAR
QUESTION PAPERS

216 216 216


Quality Content for Outcome based Learning
217

Control Flow System


Day 1

217 217 217

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


General Guideline 218

© (2021) ABES Engineering College.

This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.

218 218 218


2
Copyright © 2021, ABES Engineering College
Objective of Control Flow System 219

To understand the purpose and syntax of decision control statements.

To understand the purpose and syntax of Iterative/looping statements and jump statements.

To develop python programs with conditions and loops.

To apply the knowledge of conditions, loops and jump in solving real time problems.

To create python programs with decision ,looping and jump statements.

219 219 219


3
Copyright © 2021, ABES Engineering College
Topics Covered 220

Day 1 Day 2 Day 3 Day 4

2.1 Introduction 2.3 Iterative/ Looping 2.3 Iterative/ Looping 2.4 Jump Statements
2.2 Selection / Statements Statements • Break
Decision control • While loop • Range() • Continue
• Nested While Function
statement
•Simple If statement
loop • For loop 2.5 Else with Loop
• Nested for • While with else
•If Else statement
loop • For with else
•If-Elif statement
•Nested If Else
statement

220 220 220


4
Copyright © 2021, ABES Engineering College
Session Plan - Day 1 221

2.1. Introduction to Decision Control Statements


2.2. Selection / Decision control statement
• Simple If Statements
• If Else Statements
• If ..elif..else statements
• Nested If Else Statements
• Examples
• Review questions
• Summary

221 221 221


5
Copyright © 2021, ABES Engineering College
222
Introduction

Control flow of the program is:

The order in which the code of the program executes.


Regulated by:

Conditional statements.
Iterative/looping statements.

222 222 222


6
Copyright © 2021, ABES Engineering College
223
Contd..
 Conditional statement examples: Based on certain conditions, we take decisions
in our daily life.
• Darkness in the room: Turn on lights. • Weather is Cold: Drink Coffee
• No Darkness: Do Nothing • Weather is not Cold: Softdrink

223 223 223


7
Copyright © 2021, ABES Engineering College
224
Contd..
 Iterative Looping statements examples: For taking decisions we perform various
actions and repeat the same action many times.

Real Life Scenario:

 Suppose you want to buy a new t-shirt, visit


the shop.
 If you do not found a shirt of your choice, visit
to the new shop.
 Until your desired shirt is found, action is
performed again and again.
 This is called looping.

224 224 224


8
Copyright © 2021, ABES Engineering College
225

Selection/decision control statements


 It is used to control the flow of execution of program depending upon
condition:

 if the condition is true then the code block will execute


 if the condition is false then code block will not execute.

Real Life Scenario:


Consider the grading system for students:
 Excellent : Above 95%.
 Good: Greater than 80% & less than
equal to 95%.
 Average: Greater than 60% & less than
equal to 80%.
 Below average: Less than 60%

225 225 225


9
Copyright © 2021, ABES Engineering College
226

Revision of Flowchart

Used for start and stop.


Used for decision making.

Used for input/output.

Used for processing statement.

Connector / flow

226 226 226


10
Copyright © 2021, ABES Engineering College
227

Flowchart of the grading system

On the basis of the conditions, corresponding block of the


code will be executed or not.

Consider the grading system for students:

 Excellent :Above 95%.


 Good :Greater than 80% &less than equal t 95%.
 Average : Greater than 60% & less than equal to 80%.
 Below average: Less than 60%

227 227 227


11
Copyright © 2021, ABES Engineering College
228

Types of decision/selection control statements:

 Simple if

 if-else

 if..elif..else

 Nested...if…else

228 228 228


12
Copyright © 2021, ABES Engineering College
229

Simple if statement
 if evaluates whether a condition is:
True
False.

 if block is executed:
if and only if the value of its condition expression is
true.

Note: As we use curly braces in ‘C’ Language to define the scope of conditions and loops; in
the same manner we use colon (:) and indentation in Python.

229 229 229


13
Copyright © 2021, ABES Engineering College
230

Syntax of Simple if

230 230 230


14
Copyright © 2021, ABES Engineering College
231

Examples
 Print whether a number is even or not.
Case-1 : When n is even. Case-2 : When n is not even

231 231 231


15
Copyright © 2021, ABES Engineering College
232

Examples
 A program to increment a number if it is positive.

Explanation:
 The condition x>0 is True for value of x = 10 so the statements in the block of code will be
executed.
 The statement x = x+1 will increment the value of x by 1 i.e. x = 10 + 1; x = 11 and statement
print (x) will print x value as 11.
232 232 232
16
Copyright © 2021, ABES Engineering College
233

if else Statement
 It checks whether a condition is true or false.

 If a condition is true,

 The if statement executes


 Otherwise, the else statement executes.

233 233 233


17
Copyright © 2021, ABES Engineering College
234

Syntax of if else Statement

234 234 234


18
Copyright © 2021, ABES Engineering College
235

Example
 A program to print “Excellent” if marks is greater than 95 otherwise print “Not
Excellent”

Explanation:
 For input 68, condition marks > 95 is False. Therefore, else statement print (“Not Excellent”) is
executed and output will be “Not Excellent”.
235 235 235
19
Copyright © 2021, ABES Engineering College
if..elif..else statement 236

Extension of the if-else statement

For a multiple conditional statements


 We use if-elif statement.

Note: The conditional expression of if-elif-else are executed from top to bottom in a sequential manner. An elif
statements are known as elif Ladder.
236 236 236
20
Copyright © 2021, ABES Engineering College
237

Syntax of if..elif..else statement

237 237 237


21
Copyright © 2021, ABES Engineering College
238

Example

Explanation:
 For input 88, condition marks > 95 is False & control goes to next elif statement (marks>80 and
marks<=95), which is True and statement print (“Good”) will be executed.
 The output will be “Good”.
238 238 238
22
Copyright © 2021, ABES Engineering College
Nested if-else statement 239

 When an if-else statement is present inside the body of another “if” or “else” then
this is called nested if else.

239 239 239


23
Copyright © 2021, ABES Engineering College
240

Syntax of Nested if..else statement

240 240 240


24
Copyright © 2021, ABES Engineering College
241

Example

 A program to take age as input from user and print “You are less than 18” if age is less
than 18, otherwise print “You are above 18”.Also check that age could not be less than 0.
If so then print “Age could not be less than 0”.

241 241 241


25
Copyright © 2021, ABES Engineering College
242

Example

 A program to take age as input from user and print

 “You are less than 18” if age is less than 18

 otherwise print “You are above 18”.

 Also check that age could not be less than 0.

 If so then print “Age could not be less than 0”.

242 242 242


26
Copyright © 2021, ABES Engineering College
243
Can you answer these questions?

1. Which one of the following is a valid Python if statement :

A) if a>=2 :

B) if (a >= 2)

C) if (a => 22)

D) if a >= 22

243 243 243


27
Copyright © 2021, ABES Engineering College
244

3.Which of following is not a decision-making statement?

A) if-elif statement

B) for statement

C) if -else statement

D) if statement

244 244 244


28
Copyright © 2021, ABES Engineering College
245

4.Predict the output of the following code:

A) No output

B) okok

C) ok

D) None of above

245 245 245


29
Copyright © 2021, ABES Engineering College
246

5. What is the output of the following code snippet?

A) Launch a Missile

B) Let's have peace

C) 0.3

D)None

246 246 246


30
Copyright © 2021, ABES Engineering College
247

6. Which of the following is true about the code below?

A) x will always equal 0 after this code executes for any value of x

B) if x is greater than 2, the value in x will be doubled after this code executes

C) if x is greater than 2, x will equal 0 after this code executes

247 247 247


31
Copyright © 2021, ABES Engineering College
248
Summary

 Control statement are statements that control the flow of execution of statements so that
they can be executed repeatedly and randomly.

 The if statement executes a group of statements depending upon whether a condition is


true or false.

 The if..else statement executes a group of statements when a condition is true;


Otherwise, it will execute another group of statements.

 The if..elif statement is an extension of the if-else statement. When we have multiple
conditional statements, then we use if-elif statement.

 When an if..else statement is present inside the body of another “if” or “else” then this is
called nested if else.
248 248 248
32
Copyright © 2021, ABES Engineering College
Session Plan - Day 2 249

2.3 Iterative looping Statements


• While loop
• Nested While loop
• Examples
• Review Questions
• Summary

249 249 249


33
Copyright © 2021, ABES Engineering College
250
Iterative/Looping Statements
Sometimes we need to perform certain operations
again and again.

Real Life Scenario:

 A teacher decide to grade 75 students on the basis of


marks.
 He/she wants to do this for whole class.
 Teacher would repeat grading procedure for each student
in the class.
 This is called iterative/ looping.

250 250 250


34
Copyright © 2021, ABES Engineering College
251
Types of loops in Python

 While loop

 Nested While loop

 For loop

 Nested for loop

251 251 251


35
Copyright © 2021, ABES Engineering College
While loop 252

 It is used to repeat a block of code as long as the given condition is true.

252 252 252


36
Copyright © 2021, ABES Engineering College
Syntax of While loop 253

 Boolean expression is checked first.

 The body of the loop is entered only if the


Boolean expression evaluates to True.

 After one iteration, the Boolean expression


is checked again.

 This process continues until the Boolean


expression evaluates to False.

253 253 253


37
Copyright © 2021, ABES Engineering College
Example 254

Write a Python Program to print 4 Natural Numbers using i.e. 1,2,3,4 using While
loop.

254 254 254


38
Copyright © 2021, ABES Engineering College
Nested While loop 255

 Nested while loop is called when we use


while loop inside a while loop.

 We can use any number of while loop inside


a while loop.

 Main while loop as outer while loop and


nested while loop as inner while loop.

255 255 255


39
Copyright © 2021, ABES Engineering College
Syntax of Nested While loop: 256

 Outer while loop runs m number of times.

 Inner while loop runs n number of times.

 The total no. of iterations would be m*n.

256 256 256


40
Copyright © 2021, ABES Engineering College
Example of Nested While loop: 257

 Write a program to demonstrate While loop.

257 257 257


41
Copyright © 2021, ABES Engineering College
258

1. What will be the output of the following code snippet?

Options

A. None

B. Python

C. Ppppp

D. PPPPP

258 258 258


42
Copyright © 2021, ABES Engineering College
259

2. What will be the output of the following code snippet?

A. 0 1 2

B. 2 3

C. 0 1 2 0

D. None of the above

259 259 259


43
Copyright © 2021, ABES Engineering College
260

3. What should be the value of the variables num1 and num2 in the code snippet
below if the output expected is 4?

A. 16,6

B. 12,5

C. 8,2

D. 16,2

260 260 260


44
Copyright © 2021, ABES Engineering College
261
Summary:

 While loop is used to iterate block of codes repeatedly until given condition is
True
 While loop present inside another while loop it is called as nested while loop.
 The nested while loop is while statement inside another while statement.

261 261 261


45
Copyright © 2021, ABES Engineering College
Session Plan - Day 3 262

2.3 Iterative looping Statements


• Range()
• For loop
• Nested for loop
• Examples
• Review Questions
• Summary

262 262 262


46
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
263

Introduction to Iterative/looping
statements:

263 263 263

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


264
Range() Function,
Optional
Optional default value =
Required
default value = 0 +1

range (start value, stop value, step value)

Range() is a built in function in Python

It gives the sequence of numbers.

264 264 264


48
Copyright © 2021, ABES Engineering College
265
Range Function Example:

range (1,5,1)

 It will generate a sequence starting from value 1 up to value 4

 (5 is not included) and step by 1

 So, the output of the above gives us the sequence 1,2,3,4.

Note: Range()Function returns the range object, you must typecast range function into
collections.

265 265 265


49
Copyright © 2021, ABES Engineering College
Range 266

 Range () Function with one Program to generate sequence


argument. numbers 0 to 4.

 Single value is considered as the


stop value.

 It means the start value is


considered as 0, and step value is
considered as 1.

266 266 266


50
Copyright © 2021, ABES Engineering College
Range 267

 Range () with two argument:


Program to generate sequence of numbers
1 to 4.
 This means the start value and stop
value is mentioned.

 The step values is considered as 1


by default.

267 267 267


51
Copyright © 2021, ABES Engineering College
Range 268

 Range() with three arguments: Program to generate a sequence of


alternate natural number starting from 1
 It has start value, stop value and the
to 12.
step value, all three values are given
inside range ().
 Here first start value is 1, stop value 12
and step value is 2. That’s why the
output is [1, 3, 7, 9, 11].

268 268 268


52
Copyright © 2021, ABES Engineering College
Example 269

 Write a program to generate a sequence of starting from 10 to 2.

269 269 269


53
Copyright © 2021, ABES Engineering College
270

For loop
Syntax of For loop:
 For loop is used when we want to
run a part of our program multiple
times.

 It is also used to traverse


sequences in python like lists, tuple
etc.

270 270 270


54
Copyright © 2021, ABES Engineering College
For loop: 271

Flowchart of For loop:

 In this flowchart the statements


which we want to run multiple times
would keep on running till, we have
elements in the sequence.

 As no element left, it will come out


from loop.

271 271 271


55
Copyright © 2021, ABES Engineering College
Example: 272

Example1: Example2:
For loop with range function: Table of number 5 is printed using for loop

272 272 272


56
Copyright © 2021, ABES Engineering College
Nested For loop: 273

 Nested for loop is called when we use for loop Syntax of Nested For loop:

inside a for loop.


 In python we can use any number of for loop
inside a for loop.
 Generally, we call main for loop as outer for loop
and nested for loop as inner for loop.
 If outer loop running m times and inner loop
running n times, then total iterations would be
m*n.

273 273 273


57
Copyright © 2021, ABES Engineering College
Flowchart of Nested For loop: 274

274 274 274


58
Copyright © 2021, ABES Engineering College
Example 275

 We have used two for loops.

 Outer loop is running for two


values-0 and 1 and inner loop is
running for three values-0,1 and 2
and total print statements we are
getting 2*3=6.

275 275 275


59
Copyright © 2021, ABES Engineering College
Can you answer these questions? 276

1. What is the output of the following code snippet??

a. b.

A. N
How many time special character print?
B. n A. 11
B. 8
C. H
C. 10
D. h
D. 6

276 276 276

Copyright © 2021, ABES Engineering College 60


277

3. Which of the below programs will print all integers that aren’t divisible by
either 2 or 3 and lies between 1 and 50?

A. B.

C. D.

277 277 277


61
Copyright © 2021, ABES Engineering College
278
Summary:

 Range function () returns a sequence of numbers.

 A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

 Nested for loop allows us to create one for loop inside another for loop.

278 278 278


62
Copyright © 2021, ABES Engineering College
Session Plan - Day 5 279

2.4 Jump statements


• Break
• Continue

2.5 Else With Loop


• While with else statement
• For with else statement
• Examples
• Review questions
• Summary

279 279 279


63
Copyright © 2021, ABES Engineering College
280

Jump Statements

 It is used to :-
 Jump, skip or terminate the iteration or loop from the running program
 Interrupt loops
 Also known as early exit from loop.
 Jump statements are of two types:-
 Break
 Continue

280 280 280


64
Copyright © 2021, ABES Engineering College
281

Break

 It terminates the execution of loop immediately

 Execution will jump to the next statements.

281 281 281


65
Copyright © 2021, ABES Engineering College
282

Syntax

282 282 282


66
Copyright © 2021, ABES Engineering College
283

Example

Explanation :-

 when value of I would be 3 break


statement will be executed and
loop will be terminated and control
moves outside the while loop to
print “All done”.

 If there would have no break, then


loop would had run for i=1 to 4.

283 283 283


67
Copyright © 2021, ABES Engineering College
284

Continue

 It is used to :-
 Skip ongoing iteration

 continues remaining iterations of loop.

 Jump to the next iteration by skipping the existing one.

284 284 284


68
Copyright © 2021, ABES Engineering College
285

Syntax

Note: In break statement,


the whole loop will end; and
in continue statement, only
the specific iteration will end.

285 285 285


69
Copyright © 2021, ABES Engineering College
286

Example

Explanation:-
 The continue statement will
interrupt the on-going iteration
for i=3 and skip all the
statements of current iteration
which are mentioned after the
continue statement like print(i).
 The control goes back to the
while loop for next iteration and
loop moves on.

286 286 286


70
Copyright © 2021, ABES Engineering College
287

Else with Loop

 While with else statement

 For with else statement

287 287 287


71
Copyright © 2021, ABES Engineering College
288

While with else Statement

In python the while statement may have an exceptional else clause.

If the condition in the while loop evaluates to


False, the else portion of the code runs.

 if break statement is used in while loop then


else section is not taken into consideration.

288 288 288


72
Copyright © 2021, ABES Engineering College
289

Flowchart of While with else loop

The else clause will be executed


when the condition becomes False
and the loop runs normally.

The else clause, on the other hand,


will not execute if the loop is
terminated early by a break or
return statement.

289 289 289


73
Copyright © 2021, ABES Engineering College
290

Example

 Without Break Statement

 While loop will execute normally up to a given condition. No early exit is there so else block
will be executed.

290 290 290


74
Copyright © 2021, ABES Engineering College
291

Example

 With Break Statement

 While loop will get terminated when value of condition variable = 3, So else
block will not be executed.

291 291 291


75
Copyright © 2021, ABES Engineering College
292

For with else statement

Python allows else with for loop.

 When all the iteration of for loop


are finished normally, then control
goes to else part.

 If loop has a break statement, then


.
else part would not execute.

292 292 292


76
Copyright © 2021, ABES Engineering College
293

Syntax of for with else

293 293 293


77
Copyright © 2021, ABES Engineering College
294

Flow chart of for with else

294 294 294


78
Copyright © 2021, ABES Engineering College
295

Example

 Program to demonstrate for loop with else.

.
 For loop has been used with else, we can clearly see that, first all the elements
of sequence get executed and when all values from 0 to 4 gets printed, control
goes to else part of the program.
295 295 295
79
Copyright © 2021, ABES Engineering College
296

Example

 Program to demonstrate for loop with break and else.

.
 We have used break statement with the condition for i=5, so in the output we
are getting values from 0 to 4 and then no else part executed.
296 296 296
80
Copyright © 2021, ABES Engineering College
297

Example

 Write a program to search a given color name in list of colors. Use Linear/Sequential Search
Techniques.

Test case - 1 For the input value ‘Blue’, output will be –

Enter the color name to be search Blue


Color name Blue found in list

Test case - 2 For the input value ‘Yellow’, output will be –

Enter the color name to be search Yellow


Color name not found in list

297 297 297


81
Copyright © 2021, ABES Engineering College
298

Example

 Write a program to find a given number is prime or not. A number is prime number if it is
divisible only by itself and 1.
Approach:

 Every number is divisible by 1 and itself, so


in the below code we check that a given
number is divisible by 2 to n-1 or not.

 If divisible means not a prime number Test case - 1 For the input value 11, output will be –
otherwise a prime number. Enter any positive number11
11 is a prime number

. Test case - 2 For the input value 12, output will be –


Enter any positive number12
12 is not a prime number

298 298 298


82
Copyright © 2021, ABES Engineering College
299
Note:

expression f"{n}" is used to create a formatted string, often referred to as an f-string.


It is a way to embed the value of the variable n within a string. Here's how it works:
•The f character before the opening double-quote indicates that this is an f-string.
•Inside the string, you can place curly braces {} that enclose a
• Python expression or variable name.
•it's {n}, which means you want to
• insert the value of the variable n into the string.
For example, if n is equal to 42, then
f"{n}" would result in the string "42".
It effectively converts the value of n to a string and includes it within the string.

299 299 299


83
Copyright © 2021, ABES Engineering College
300
Can you answer these questions?
1:-what will be the output of following code:-

A) 0 B) 0 C) 0 D) NONE
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7
BREAK

300 300 300


84
Copyright © 2021, ABES Engineering College
301

2:- What will be the output of following code:-

A) 0 B) 0 C) 0 D) NONE
1 1
1 2
2
2 3
4
3 4
5
4 5
5 6
continue continue

301 301 301


85
Copyright © 2021, ABES Engineering College
302
Summary

 Jump statements in python are used to alter the flow of a loop like you want to
skip a part of a loop or terminate a loop.

 Break Statement in Python is used to terminate the loop.

 Continue Statement in Python is used to skip all the remaining statements in the
loop and move controls back to the top of the loop.

302 302 302


86
Copyright © 2021, ABES Engineering College
References 303

 https://docs.python.org/3/tutorial/controlflow.html

 Think Python: An Introduction to Software Design, Book by Allen B. Downey

 Head First Python, 2nd Edition, by Paul Barry

 Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader,


Joanna Jablonski, Fletcher Heisler

 https://fresh2refresh.com/python-tutorial/python-jump-statements/

 https://tutorialsclass.com/python-jump-statements/

303 303 303


87
Copyright © 2021, ABES Engineering College
304

Thank You

304 304 304


88
Copyright © 2021, ABES Engineering College
305

305 305 305


89
Copyright © 2021, ABES Engineering College
306

ABES ENGINEERING COLLEGE, GHAZIABAD

Unit-2
QUESTION BANK
SUBJECT NAME: PYTHON PROGRAMMING
SUBJECT CODE: BCC-302

Q.No Description CO BL
What is the purpose of the elif statement in Python? How does it differ from if
1 CO2 K2
and else, and why is it important for handling multiple conditions?
Discuss the basic structure of a for loop and for-else in Python. How do you
2 CO2 K2
iterate over a sequence or collection using a for loop?
Develop a Python program that uses a while loop to simulate a basic guessing
game. The program should generate a random number, and the user should guess
3 CO2 K3
it. The game should provide feedback on whether the guess is too high or too low
until the correct number is guessed.
Explain how the continue statement works in a loop. Provide an example of how
4 CO2 K1
you might use continue to skip certain iterations.
Describe the role of the pass statement in Python loops. In what situations would
5 CO2 K2
you use it, and how does it affect program flow?
Create a Python program that checks if a given year is a leap year or not. Use
6 CO2 K3
conditional statements to determine the leap year criteria.
Write a Python program that calculates the sum of all even numbers from 1 to 100
7 using a for loop. CO2 K3

Create a program that takes a list of numbers as input and calculates their product
8 CO2 K3
using a for loop.
Write a Python program that repeatedly asks the user for a number until they enter
9 0. Afterward, calculate and print the sum of all entered numbers using a while CO2 K3
loop.
Create a program that prints all even numbers between 1 and 20 using a for loop,
10 CO2 K3
but skips the number 10 using the continue statement.
Write a Python program that asks the user to enter a series of numbers. Use a
11 while loop to continue prompting for input until the user enters the number 42. CO2 K3
When 42 is entered, terminate the loop using the break statement.
Implement a program that checks whether a given list contains a specific value. If
12 CO2 K3
the value is found, print a message and exit the loop early using the else clause.
Develop a program that takes a string input from the user and counts the number
13 CO2 K3
of vowels (a, e, i, o, u) in the string using a for loop.
Create a program that generates and prints the first N prime numbers, where N is
14 CO2 K3
input by the user.
Implement the Sieve of Eratosthenes algorithm to generate all prime numbers up to
15 CO2 K3
a given limit. Print the prime numbers.
Create a Python program to find the nth Fibonacci number using both recursion
16 and an iterative approach. Compare the efficiency of the two methods for large CO2 K3
values of n.
Write a Python program to print a pattern of asterisks in the shape of a right-
17 CO2 K3
angled triangle. Allow the user to input the height of the triangle.
18 Implement a program that prints the following pattern: CO2 K3

306 306 306


307

ABES ENGINEERING COLLEGE, GHAZIABAD

Create a program that prints a pattern of numbers in the form of a Pascal's


19 triangle. Allow the user to input the number of rows for the triangle.
CO2 K3

Develop a program to print the following pattern:

20 CO2 K3

307 307 307


308

Python programming (BCC302)


UNIT-2
QUESTION BANK SOLUTIONS
1. 'Elif' stands for 'else if' and is used in Python programming to test multiple conditions. It is
written following an if statement in Python to check an alternative condition if the first
condition is false. The code block under the elif statement will be executed only if its
condition is true. ELSE IF is more efficient because the computer only has to check
conditions until it finds a condition that returns the value TRUE. By using multiple IF-
conditions the computer has to go through each and every condition and thus multiple IF-
conditions require more time.
2. Syntax:
for iterator_var in range ():
statements(s)
for iterator_var in range():
statements(s)
else:
statements(s)
Iteration of for loop in sequence
for iterator_var in sequence:
statements(s)
3.

4. Continue is used to skip the ongoing iteration and continues the remaining iterations of
loop. Use of continue statement is to jump to the next iteration by skipping the existing
one.

308 308 308


309

5. The Python pass statement is a null statement. But the difference between pass
and comment is that comment is ignored by the interpreter whereas pass is not ignored.
If we do not use pass or simply enter a comment or a blank here, we will receive
an IndentationError error message.
Here are a few scenarios where you might use the pass statement in loops:

for item in collection:


# TODO: Implement functionality here
Pass

while condition:
if some_condition:
# No action needed in this case
pass
else:
# Perform some action
do_something()

309 309 309


310

6.

7. total = 0 #defined total


for number in range(1,101):
if number %2 == 0:
total = sum(int(number))
print(total)
8.

def calculate_product(numbers):
product = 1
for num in numbers:
product *= num
return product

# Get input from the user


input_str = input("Enter a list of numbers separated by spaces: ")
numbers_list = list(map(float, input_str.split()))

# Calculate product using the function


result = calculate_product(numbers_list)
print("The product of the numbers is:", result)

310 310 310


311

9. for i in range(1, 21):

if i%2==0:
print(i)
if i=10:
continue
else:
print(i, end=" ")

10.

311 311 311


312

Q11 Ans
while True:
user_input = input("Enter a number (or enter 42 to terminate): ")

# Check if the user entered 42


if user_input == "42":
print("Terminating the loop. You entered 42.")
break
This program continuously prompts the user to enter a number. It keeps running until the
user enters the number 42. Once the user inputs 42, the program prints a message and
breaks out of the loop, ending the program

Q12Ans
a.
lst=[ 1, 6, 3, 5, 3, 4 ]
#checking if element 7 is present
# in the given list or not
i=7
# if element present then return
# exist otherwise not exist
if i in lst:
print("exist")
else:
print("not exist")
b.
# python program check a list contain specific value. using for else loop
def check_value_in_list(my_list, target_value):
for element in my_list:
if element == target_value:
print(f"{target_value} found in the list.")
break
else:
print(f"{target_value} not found in the list.")

# Example usage:
my_list = [1, 2, 3, 4, 5]
target_value = int(input("Enter number to found"))

check_value_in_list(my_list, target_value)

Q13Ans
#take user input
String = input('Enter the string :')
count = 0
#to check for less conditions
#keep string in lowercase

312 312 312


313

String = String.lower()
for i in String:
if i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':
#if True
count+=1
#check if any vowel found
if count == 0:
print('No vowels found')
else:
print('Total vowels are :' + str(count))

Q14Ans
# Python3 program to display Prime numbers till N
#function to check if a given number is prime
def isPrime(n):
#since 0 and 1 is not prime return false.
if(n==1 or n==0): return False
#Run a loop from 2 to n-1
for i in range(2,n):
#if the number is divisible by i, then n is not a prime number.
if(n%i==0):
return False
#otherwise, n is prime number.
return True

# Driver code
N = 100;
#check for every number from 1 to N
for i in range(1,N+1):
#check if current number is prime
if(isPrime(i)):
print(i,end=" ")

Q15 Ans
# Define a function named 'prime_eratosthenes' that generates prime numbers using the Sieve
of Eratosthenes algorithm
def prime_eratosthenes(n):
prime_list = [] # Create an empty list to store prime numbers
# Iterate through the numbers from 2 to 'n'
for i in range(2, n+1):
if i not in prime_list:
# If 'i' is not in the 'prime_list,' it's a prime number; print it
print(i)

# Mark all multiples of 'i' as non-prime by adding them to 'prime_list'

313 313 313


314

for j in range(i*i, n+1, i):


prime_list.append(j)
# Call the 'prime_eratosthenes' function with 'n' set to 100 to generate prime numbers
# The function does not have a return value, so it prints the prime numbers directly
n=int(input("Enter the number"))
prime_eratosthenes(n)

Q16 Ans
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

# Python Program for n-th Fibonacci number Using recursion


# Function for nth Fibonacci number
def Fibonacci(n):
if n<= 0:
print("Incorrect input")
# First Fibonacci number is 0
elif n == 1:
return 0
# Second Fibonacci number is 1
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)

314 314 314


315

# Driver Program
print(Fibonacci(10))

Q17 Ans.
#Print right angle triangle in Python
x=int(input("Enter row number=\n"))
for i in range(x):
for j in range(i+1):
print("*",end='')
print("")

Q18 Ans.
# 1-22-333-4444 Pattern up to n lines
n = int(input("Enter number of rows: "))
for i in range(1,n+1):
for j in range(1, i+1):
print(i, end="")
print()

Q 19 Ans.
# Print Pascal's Triangle in Python
from math import factorial

# input n
n=5
for i in range(n):
for j in range(n-i+1):

# for left spacing


print(end=" ")

for j in range(i+1):

# nCr = n!/((n-r)!*r!)
print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")

# for new line


print()

315 315 315


316

20 Ans.
# Reading number of rows
row = int(input('Enter how many lines? '))
# Generating pattern
for i in range(1,row+1):
# for space
for j in range(1, row+1-i):
print(' ', end='')
# for increasing pattern
for j in range(1,i+1):
print(j, end='')
# for decreasing pattern
for j in range(i-1,0,-1):
print(j, end='')
# Moving to next line
print()

316 316 316


Quality Content for Outcome based Learning
317

UNIT-3
3.Python Collections and Sequences

317 317 317

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


General Guideline 318

© (2021) ABES Engineering College.

This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.

318 318 318


2
Copyright © 2021, ABES Engineering College
Objective of Collections/Sequences 319

To describe the importance of list , string, tuple , dictionary and set in python

To uses to store multiple data values.

To use the index to update, add, and remove items

To use the data structures with out indexes

To explain the difference among different Collections

To select collections built-in functions in Python to write programs in Python.

319 319 319


3
Copyright © 2021, ABES Engineering College
Topics Covered 320

Day 1 Day 2 Day 3 Day 4

3.1 Introduction 3.2 String 3.3 List 3.3 List


• 3.2 String • Updation • Creation • Loops
• Creation of • Deletion • Accessing • Nested List
String • Built-in- • Update • List
• Accessing the methods • Built in Comprehensi
String • Operations methods ons
• String
Formatters
• Loops with
Strings

320 320 320


4
Copyright © 2021, ABES Engineering College
Topics Covered 321

Day 5 Day 6 Day 7 Day 8

3.4 Tuple 3. 5 Dictionary 3.5 Dictionary 3.6 Set


• Creation • Creation • Built in • Creation
• Accessing • Accessing Methods • Assessing
• Modification • Modification • Loops and • Modification
Conditions • Built in
• Built in
Methods methods
• Operations • Operators
• Loops
• Frozen set

321 321 321


5
Copyright © 2021, ABES Engineering College
Session Plan - Day 1 322

3 Introduction to Python Collections and Sequences


3.1 String
 Creation of String
 Assessing of String
 Updation of String
 Examples
 Review Questions

322 322 322


6
Copyright © 2021, ABES Engineering College
323
Introduction

In real life we need to store data like-


 Name of students – A sequence of alphabet character
 Marks of n students – A sequence of either integer or float value
 Student’s record – A sequence of name, branch, roll number, address etc
So to represent these type of data in python provides us some built in collections.

323 323 323


7
Copyright © 2021, ABES Engineering College
324
Contd…
Representation of Python Collections with the help of Figure:

 If data is the combination of


numeric data, alphanumeric or
of different types than we go
for List, Tuple or set .

 If data is in the form of key-


value pair than we go for
dictionary.

324 324 324


8
Copyright © 2021, ABES Engineering College
325
String
A string is a sequence of alphanumeric and
special character.

String is the collection of characters, it may


compose of alphanumeric and special
characters.

Strings are created in many ways using


single quotes or double-quotes.

Alphanumeric characters: a-z, A-Z, 0-9; Special symbol: *, -, +, $, @, whitespace …. etc

325 325 325


9
Copyright © 2021, ABES Engineering College
326
Creation of Empty String

Empty String

 An empty string is a string having no


character.
 We have three ways to create an empty
string as shown in syntax.
 An Empty String is created by single quotes,
double quotes and str().

326 326 326


10
Copyright © 2021, ABES Engineering College
327
Creation of Non Empty String

 A non-empty string is a sequence of alphanumeric character with at least one character.

 A non-empty string is created by using single quotes and double quotes

327 327 327


11
Copyright © 2021, ABES Engineering College
328
Assessing the String

 String Element can be accessed using Square


Bracket.

 These Square brackets [ ] take an index as


input.

 In Python we have two types of Indexing.

 Positive Indexing
 Negative Indexing

328 328 328


12
Copyright © 2021, ABES Engineering College
329
Positive Indexing

 Positive indexing
start from Zero (0)
and from left hand
side i.e. first
character store at
index 0, second at
index 1 and so on.

 Every character of
string has some
index value.

329 329 329


13
Copyright © 2021, ABES Engineering College
330
Negative Indexing

 Negative
Indexing starts
from negative
indexing start
from -1 and
from right-hand
side.

 Last character
store at index -
1 and as we
move towards
the left, it keeps
increasing like -
2, -3, and so
on.
330 330 330
14
Copyright © 2021, ABES Engineering College
331
Example

 Write a program to print character 'P' and 'L' using positive indexing and negative indexing.
Assume a string st = 'I Like Python’, is given.

331 331 331


15
Copyright © 2021, ABES Engineering College
332
String Slicing

 String slicing is the way of selection


of substring.

 String 'Like' is substring in given 'I Like


Python' string.

 [] we can access string characters by


giving indexes if we use colon inside
square bracket like [:] it becomes a
slicing operator in Python.

332 332 332


16
Copyright © 2021, ABES Engineering College
333
Syntax of String Slicing

 Start index: Index from


which slicing starts.

 End Index: Index up to


which slicing end.

 Step value is optional.

333 333 333


17
Copyright © 2021, ABES Engineering College
334
Examples of String Slicing

Example Explanation Syntax

st[ 2 : 6 ] It starts with the 2nd index and ending with (6It
starts with the 2nd index and ending with (6-1=5)th
index.-1=5)th index.
st[ 0 : 6 : 2 ] It starts with index 0th and end with (6-1=5) th. Step
is 2 So, it will give value at index 0,2,4

st[ 12 : 6 : -1] It starts slicing from 12th index up to 6-1=5th index.


12th to 6th in opposite direction because step is
negative.

334 334 334


18
Copyright © 2021, ABES Engineering College
335
Contd..

Example Explanation Syntax

st[ -11 : -7 ] It starts with -11th index and ending with (-


7-1 = -8)th index.

[:] The operator gives the complete original


string.*

[:6] Start index is missing and step is +1, So


it will start from 0 till 6-1=5th index.*

335 335 335


19
Copyright © 2021, ABES Engineering College
336
Contd..

Example Explanation Syntax

st[ 7 : ] It will start from index 7 to last index ( Last


index missing )*

st[ : : -1] Step is -1, So start index will be the last


index and end index will be first index
when start and end is missing.
st[ 2 : 6 : -1 ] This is explaining in Note Section **
Output – Empty string

336 336 336


20
Copyright © 2021, ABES Engineering College
337
Important Points to Remember

Note about *, **

 * When start index is missing it will start from either first character or from last. It
depends on step sign (positive or negative).
 * When end index is missing it will execute till last character or first character. It depends
on step sign (positive or negative).
 * When we take negative steps it will scan from start to end in opposite direction.
 ** In the case of step is positive or negative the slicing will be done as below given
algorithm.

337 337 337


21
Copyright © 2021, ABES Engineering College
338
Comparison

338 338 338


22
Copyright © 2021, ABES Engineering College
339
Updation in String
 Strings in python are Immutable(un-changeable) sequences, which means it does not support new
element assignment using indexes.

 Lets try to understand this concept with the help of an example

In the above example string does not allow assigning a new element, because item assignment does
not support by string.
339 339 339
23
Copyright © 2021, ABES Engineering College
340
Contd..
1. What will be the output of the following code snippets?

A. come to Myso

B. come to Mys

C. lcome to Mys\

D. lcome to Myso

340 340 340


24
Copyright © 2021, ABES Engineering College
341
Contd..
2. What will be the output of the following code Comparison?

A. True
False

B. False
False

341 341 341


25
Copyright © 2021, ABES Engineering College
342
Contd..
3. What will be the output of the following code snippet?

A. ES

B. En

C. ES En

D. ESEn

342 342 342


26
Copyright © 2021, ABES Engineering College
343
Contd..
4. What will be the output of the following code snippet?

A. hellohowa
B. hellohowaaaaa
C. hellohowaaaaaaa
D. Error

343 343 343


27
Copyright © 2021, ABES Engineering College
Session Plan - Day 2 344

3.1 String
 Built in Methods
 Basic Operations
 String Formatters
 Loops with Strings
 Review Questions
 Practice Exercises

344 344 344


28
Copyright © 2021, ABES Engineering College
345
Deletion

 In String, we can’t reassign the string characters but we can delete the complete string
using del command.

 Lets try to understand this concept with the hep of an example

In the above example , after deletion when we try to print the string st it gives NameError : st not
defined.
345 345 345
29
Copyright © 2021, ABES Engineering College
346
String Built in methods:

 String supports a variety of Built-In


methods for achieving different types
of functionalities.

 All built-in methods provide us to use


as plug and play, we do not have to
implement it.

 In python methods are called using


dot(.) operator

346 346 346


30
Copyright © 2021, ABES Engineering College
347
String Built in methods:

Method Name Explanation Code Snippet

capitalize() Return a string with first letter capital


e.g.
i like python  I Like Python

casefold() Return string in lowercase

count() Return the number of occurrence of


substring.
In the first example “i” occurred 3 times.
In the second example “like” occurred 2
times.

347 347 347


31
Copyright © 2021, ABES Engineering College
348
String Built in methods:

Method Name Explanation Code Snippet

endswith() Return True if the string ends with the


given substring otherwise return
False.
startswith() Returns True if the string starts with
the given substring otherwise return
False.

find() Return the lowest index in String


where substring sub is found.
In example – there are two “like”.
1st “like” is at index-2 and 2nd at
index-16. It return 2.

348 348 348


32
Copyright © 2021, ABES Engineering College
349
String Built in methods:

Method Name Explanation Code Snippet

lower() Convert and return a string into lower


case

upper() Convert and return a string into upper


case

swapcase() In swaps cases, the lower case


becomes the upper case and vice
versa

349 349 349


33
Copyright © 2021, ABES Engineering College
350
String Built in methods:

Method Name Explanation Code Snippet

title() Converts the first character of each


word to upper case.

replace() Returns a string after replacing old


substring with new substring.

split() Splits the string from given separator


and returns a list of substring.
Note –
By default, value of separator is a
whitespace

350 350 350


34
Copyright © 2021, ABES Engineering College
351
String Built in methods:
Method Name Explanation Code Snippet

join() Concatenate any number of strings.


The string whose method is called is
inserted in between each given string.
The result is returned as a new string
strip() Return a copy of the string with
leading and trailing whitespace
removed.
isalnum() Return true if the string is
alphanumeric (Combination of a-z, A-
Z, 0-9)
Note – It will return false only if string
contains special character.

351 351 351


35
Copyright © 2021, ABES Engineering College
352
String Built in methods:
Method Name Explanation Code Snippet

isalpha() Return true if the string contains only


alphabets(Combination of a-z, A-Z)

isdecimal() Returns True if all characters in the


string are decimals

islower() Returns True if all characters in the


string are lower case

352 352 352


36
Copyright © 2021, ABES Engineering College
353
String Built in methods:

Method Name Explanation Code Snippet


len() Return length(No of character) of a
given string. This is a generic
function.

353 353 353


37
Copyright © 2021, ABES Engineering College
354
Basic Operations in String:

 Strings in Python support basic operations like concatenation, replication


and membership

 Concatenation means joining/combining two string into one.


 Replication means repeating same string multiple times.
 Membership tells a given string is member of another string or not.

354 354 354


38
Copyright © 2021, ABES Engineering College
355
Operations in String:
Method Name Explanation Code Snippet

+ Concatenation

It will merge/join second string at the


end of first string and return.

* Multiply (Replicas)
It will repeat same string multiple
times and return.
Note – multiply string only with
integer number.

in Membership
It will check a given substring is
present in another string or not.
Note – gives bool value (True/False)

355 355 355


39
Copyright © 2021, ABES Engineering College
356
Operations in String:
Method Name Explanation Code Snippet

Not in It's reverse of Membership

356 356 356


40
Copyright © 2021, ABES Engineering College
357
String Formatters:

 String formatting is the process of infusing things in the string dynamically and presenting
the string.

Why to use String Formatter??

 For different types of requirement to print the string in a formatted manner.

 Here, format implies that in what look and feel we want our strings to get printed.

 Python string provides a number of options for formatting.

357 357 357


41
Copyright © 2021, ABES Engineering College
358
String Formatters:

 String formatting is the process of infusing things in the string dynamically and presenting
the string.

Why to use String Formatter??

 For different types of requirement to print the string in a formatted manner.

 Here, format implies that in what look and feel we want our strings to get printed.

 Python string provides a number of options for formatting.

358 358 358


42
Copyright © 2021, ABES Engineering College
359
String format Style:
Escape Explanation Example
Sequence
\newline Ignores newline

\\ Backslash

Write a backslash in string

\' If we need to use single quotes in our


string like
Good Morning! Mr. 'BOB'

359 359 359


43
Copyright © 2021, ABES Engineering College
360
String format Style

Escape Explanation Example


Sequence
\" If we need to use double quotes in
our string like
Good Morning! Mr. 'BOB'

\n Newline

360 360 360


44
Copyright © 2021, ABES Engineering College
361
String Format()

Method 1: It is a beneficial method for formatting strings; it uses {} as a placeholder.

 We have placed two curly braces and arguments that give the format method filled in
the same output.

361 361 361


45
Copyright © 2021, ABES Engineering College
362
String Format()

 If we want to change the order of , we can give an index of parameters of format


method starting with 0th index.

362 362 362


46
Copyright © 2021, ABES Engineering College
363
String Format()

 If we want to change the order of , we can give an index of parameters of format


method starting with 0th index.

363 363 363


47
Copyright © 2021, ABES Engineering College
364
String Format()

 We can also use keywords arguments in format method, as shown in the


following example, as shown in figure.

364 364 364


48
Copyright © 2021, ABES Engineering College
365
String Format()

 We can also use format specifier in format method like in language ‘C’. Format
specifier are used to do following.

 Represent value of amount = 12.68456 at two decimal place


 Represent value of integer in Binary, Octal or Hexadecimal etc.

Note: In the above example b is used for binary representation.

365 365 365


49i
Copyright © 2021, ABES Engineering College
366
Format Specifiers

Format Specifier Explanation Example

b Use for Binary

o Use for Octal

X or x Use for Hexadecimal

366 366 366


50
Copyright © 2021, ABES Engineering College
367
Format Specifiers

Format Specifiers Explanation Example

d Use for Decimal

f Use for Float


Note – Place .n before f, for
representing floating point
precision. n is decimal places.

367 367 367


51
Copyright © 2021, ABES Engineering College
368
Formatting using f-string

 Fstring is the way of formatting as format method does but in an easier way.

 We include ‘f’ or ‘F’ as a prefix of string.

368 368 368


52
Copyright © 2021, ABES Engineering College
369
Can you answer these questions?
1. What will be the output of the following code snippet?

A. Hello how are you


B. Hello how are
C. hello how are you
D. Hello how re you

369 369 369


53
Copyright © 2021, ABES Engineering College
370
Can you answer these questions?
2. What will be the output of the following code snippet?

A. True

B. False

C. Error

D. None

370 370 370


54
Copyright © 2021, ABES Engineering College
Loops with Strings: 371

 Strings are sequence of character and iterable objects, so we can directly apply for loop
through string.
Example-1 Example -2
Scan/Iterate each character of string through Scan/Iterate each character of string directly
index using for loop. using for loop

371 371 371


55
Copyright © 2021, ABES Engineering College
Loops with Strings: 372

Example 3 – Write a program to print number of alphabets and digits in a given string.

372 372 372


56
Copyright © 2021, ABES Engineering College
Loops with Strings: 373

Example 4
To add 'ing' at the end of a given string (length should be at least 3).

 If the given string already ends with 'ing' then add 'ly' instead.
 If the string length of the given string is less than 3, leave it unchanged.

Sample String : 'abc'


Expected Output : 'abcing’

Sample String : 'string'


Expected Output : 'stringly'
.

373 373 373


57
Copyright © 2021, ABES Engineering College
Session Plan - Day 3 374

3.2 List
 Creation
 Accessing
 Updation
 Review Questions
 Practice Exercises

374 374 374


58
Copyright © 2021, ABES Engineering College
List 375

.  Python List is the most commonly used sequence.

 Important points about list are as follows.


 List elements are enclosed in square brackets [] and are comma separated.

 List is the sequence of class type ‘list’.

 List can contain elements of different data types.

 List is a mutable(changeable) sequence, would be discussed in detail in 3.2.3

 List allows duplicate elements.


 List elements are ordered, it means it give specific order to the elements, if new element is
added, by default it comes at the end of the list.

375 375 375


59
Copyright © 2021, ABES Engineering College
List 376

Real World Scenario:


List Representation
 List is used when there is a
possibility of elements of different
data type.

 For example record of a particular


student, having name as string,
roll.no as integer, marks as float,
father’s name as string.

 To contain this record list is the


appropriate sequence.

376 376 376


60
Copyright © 2021, ABES Engineering College
List Example 377

 In this example a variable named list


example has been created and three
elements have been assigned.

 As we have enclosed elements in


square brackets, this makes list
example is of type list.

377 377 377


61
Copyright © 2021, ABES Engineering College
Ordered Property of List 378

 Ordered sequence of the list means the


order in which elements appear is unique

 The position of every element is fixed.

 If we change the position of any element,


then list would not be the same anymore.

378 378 378


62
Copyright © 2021, ABES Engineering College
Creation of List 379

List can be created by many ways as follows.

Creation of Empty List Creation of Non Empty List

379 379 379


63
Copyright © 2021, ABES Engineering College
Accessing the List 380

Indexing the List


 In the list index are started from 0, it means first element takes 0 index and it increases like
0,1,2…(n-1).
 List also supports negative indexing.

 It means last element can be accessed using -1 index, second last as -2 and so on.

380 380 380


64
Copyright © 2021, ABES Engineering College
Slicing 381

 Slicing is used to get substring from a string.


 We use Slice operator in the list to get a sub list.

Start= Optional argument by default value


is 0.
End = Optional argument by default value is
number of elements in the list. If any
number given, then value is taken as
number-1.
Step=Options argument by default value is
1.
Colon 1: Required
Colon 2: Optional

381 381 381


65
Copyright © 2021, ABES Engineering College
Slicing Example 382

 Single colon[:]- It is used to print the entire list.

 Double colon[:]- It is used to print the entire list.

 l[2::]-It is used to print the list starting from index 2 till


the last element of the list.

 L[2:5:]- We have set start and end both as 2 and 5,


so it’s starting from 2 and ending with (5-1) and
printing values for indexes 2,3 and 4 index.

 L[2:5:2]-end and step has been set as 2,5 and 2. So


output substring starting from index 2, ending with 5-
1=4 and step counter is 2, so its skipping alternate
element.
382 382 382
66
Copyright © 2021, ABES Engineering College
383
Examples of List Slicing

Operator Explanation Example

[:] This gives a complete original list

[1:3] It starts with 1th index and ending


with (3-1=2) index

[2:] Sub list starts with index 2 and


ends at last element as nothing
specified on right side of the
colon

383 383 383


67
Copyright © 2021, ABES Engineering College
384
Examples of List Slicing

Operator Explanation Example

[1:4:] Start=1, stop=4 and by default


step=1.

[1:4:2] Start=1, stop=4 and by step=2.


As the step is 2, it took every 2nd
element.
[::-1] Starting is 0th index and stopping
at last index and step is negative
count so that it would print in
reverse order

384 384 384


68
Copyright © 2021, ABES Engineering College
385
Updation in List:

 List updating involves insertion of new elements, deletion of elements or deletion of complete list.

 List is a mutable sequence it means it allows changes in the elements of list.

385 385 385


69
Copyright © 2021, ABES Engineering College
386
Updation in List:

 List updating involves insertion of new elements, deletion of elements or deletion of complete
list.

 List is a mutable sequence it means it allows changes in the elements of list.

386 386 386


70
Copyright © 2021, ABES Engineering College
387
Can you answer these Questions

1.What is the output of the following code?

A.[‘XY’,’YZ’]

B.[‘xy’,’yz’]

C. None of the above

D. Both of the above


387 387 387
71
Copyright © 2021, ABES Engineering College
388
Can you answer these Questions

2.What is the output of the following code?

A. [‘g’,’h’,’k’,’l’,’m’]

B. [‘g’,’h’,’k’,’l’,’m’,9]

C. [‘g’,’h’,’k’,’l’,’m’,8,9]

D. [‘g’,’h’,’k’,’l’,’m’,9,8]

388 388 388


72
Copyright © 2021, ABES Engineering College
Session Plan - Day 4 389

3.2 List
 Updation in List
 Operations in List
 Built in Methods
 Operations
 Loops
 Nested list
 List Comprehension
 Review Questions
 Practice Exercises
389 389 389
73
Copyright © 2021, ABES Engineering College
390
Add new element in List:

 We can add elements to the existing list using append function.

 Append function always add the element at the end of the list.

Syntax:

Listname.append (element to be added)

In this example element 5 has been


appended in the originally existed list. It’s
being added in the last

390 390 390


74
Copyright © 2021, ABES Engineering College
391
Changing new element in List:

 Value of the element at index 3 has been assigned new value as 5, so element in the output
list is changed from 4 to 5.

391 391 391


75
Copyright © 2021, ABES Engineering College
392
Deletion in List:

List elements can be deleted.

 Using del command If we know the position(index) of the element which is to be deleted.

 We can use the remove method by giving the specific element as given in the example If we know the
position(index) of the element.

392 392 392


76
Copyright © 2021, ABES Engineering College
393
Deletion in List:

 list1 has been deleted and then we are trying to print it and its giving error because
it does not exist now.

393 393 393


77
Copyright © 2021, ABES Engineering College
394
Built in Methods in List

Method Remark Example

len() It calculates the length of the list or the


number of elements in the list.

max(list) It returns the maximum element from the list

min(list) It returns a minimum element from the list

list(seq) It converts into any sequence into a list

394 394 394


78
Copyright © 2021, ABES Engineering College
395
Contd..

Method Remark Example

pop() It deletes the last element from the list


Note – We can also pass index as argument in pop() to
delete a specific index value.

count() It counts the occurrences of a particular element in the list

sort() Sort the elements of the list in ascending order

reverse() Sort the elements of the list in reverse order

395 395 395


79
Copyright © 2021, ABES Engineering College
396
Operations on List

 Python supports variety of operations on the list

Operation Remark Example

Concatenation Operation adds two list


elements

Repitition It repeats the list specified


number of times

396 396 396


80
Copyright © 2021, ABES Engineering College
397
Contd..

 Python supports variety of operations on the list

Operation Remark Example

Membership To check whether an element


belongs to the list or not

Membership not I return true of an element

that does not belong to the list

397 397 397


81
Copyright © 2021, ABES Engineering College
398
Example

 Write Python Program to swap elements in the list.

398 398 398


82
Copyright © 2021, ABES Engineering College
399
Practice Problems

 Take a list input from user having integer elements and calculate sum and average of the
list.

 Take an input list and swap string elements of the list with empty string.

399 399 399


83
Copyright © 2021, ABES Engineering College
400
Loops with List

 While loop with list  For Loop with list

400 400 400


84
Copyright © 2021, ABES Engineering College
401
Example

 Write a python program to print all positive number of a list.

Practice Exercise:

 Write a python program to remove duplicate from the list.

 Write a python program to count positive, negative and string type elements.

401 401 401


85
Copyright © 2021, ABES Engineering College
402
Nested List

 When we have an element of a list in the form of the list itself, it is called Nested List.

 Elements of the nested list can be accessed using the 2-D indexing access method.

In this example, first [1] denotes [3,4] and second [1] represents 4, so it gives output as 4.

402 402 402


86
Copyright © 2021, ABES Engineering College
403
Nested List as a Matrix

 We can represent nested list as matrix also.

 For this we would use nested for loop.

 Outer loop would run for number of elements in the list and inner loop would consider
individual element of the nested list as a list.

403 403 403


87
Copyright © 2021, ABES Engineering College
404
Example

 Create a flat list from a nested list.

.
Practice Exercise:
 Using nested list print transpose, of a given matrix

 Print reverse order of a nested list


.

404 404 404


88
Copyright © 2021, ABES Engineering College
405
List Comprehensions

 Let's suppose we want to write a program to calculate powers of 3 for a given range.

 Python provide us writing iterative programs in much


 Traditional Programming
lesser lines called List comprehension.

 The same problem has been solved using list


comprehension.

405 405 405


89
Copyright © 2021, ABES Engineering College
406
List Comprehension

Syntax:
IF ELSE :
[ statements for an item in list ]
 We should notice one change that because in if-else
case output is separated based on the condition.
 We have the facility of adding conditionals in
 if-else and conditions has been written along with
the list comprehension. statements.

406 406 406


90
Copyright © 2021, ABES Engineering College
Session Plan - Day 5 407

3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises

407 407 407


91
Copyright © 2021, ABES Engineering College
Session Plan - Day 5 408

3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises

408 408 408


92
Copyright © 2021, ABES Engineering College
409
Tuple

 Tuple is an immutable (unchangeable) ordered collection of elements of different data types.

 Generally, when we have data to process, it is not required to modify the data values.

 Take an example of week days, here the days are fixed. So, it is better to store the values in the data
collection, where modification is not required.

409 409 409


93
Copyright © 2021, ABES Engineering College
410
Creation of Tuple

Creation of Empty Tuple Creation of Non Empty Tuple

 Syntax of Creating Non Empty Tuple

 In above example, the () round brackets are used


to create the variable of tuple type.

 We can also call the class to create a tuple object


as shown in example below.

410 410 410


94
Copyright © 2021, ABES Engineering College
411
Example

 Write a program in python to create one element in tuple

 If you want to create a tuple with single value, it is required to add a comma after the single value as
shown in the above example c=(‘college’,).

 If the comma is not placed, then the single value a= (1) or b=(ABES) will be treated as an
independent value instead of the data collection.
.

411 411 411


95
Copyright © 2021, ABES Engineering College
412
Packing and Unpacking of Tuple

 Tuple can also be created without using parenthesis; it is known as packing.

 Write a program to create tuple without parenthesis.

In above example 1, newtup4=3,4,5,” hello” creates a new tuple without parenthesis.

412 412 412


96
Copyright © 2021, ABES Engineering College
413
Unpacking of Tuple

 Write a program to unpack elements in tuple

 Unpacking is called when the multiple variables is assigned to a tuple; then these variables take
corresponding values.

Practice Questions:

 Write a Python program to create the colon of a tuple.


.
 Write a Python program to unpack a tuple in several variables.
413 413 413
97
Copyright © 2021, ABES Engineering College
414
Accessing Elements in Tuple

 Tuple elements can be accessed using indexes, just like String and List .

 Each element in the tuple is accessed by the index in the square brackets [].

 An index starts with zero and ends with (number of elements - 1)

Example:

Write a program to access index 1 element from tuple.

In above example 1: tuple newtup carries multiple types of data in it as “hello” is string, 2 is integer, and
.
23.45 is float. If we can fetch the index 1 element using print(newtup[1]).
414 414 414
98
Copyright © 2021, ABES Engineering College
415
Contd…

 Write a program to access index 0 element from tuple.

 Basically, the -1 index will return the last value of tuple.

 Indexes start from zero, and it goes up to a number of elements or say -1.

 Take another example to fetch the -1 index from tuple.

 last element is accessed by print(tuple_days[-1]).


.

415 415 415


99
Copyright © 2021, ABES Engineering College
416
Indexing in Tuple and Slicing

 Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.

 Write a program to access elements from 0 to 4 index in tuple.

 Write a program to access elements from 1 to 3 index in tuple.

416 416 416


100
Copyright © 2021, ABES Engineering College
417
Modification/Updating a Tuple

 If we want to change any of the index value in tuple, this is not allowed and throw an error.

 Tuple object does not support item assignment.

 Here, we are taking the same above example of days and showing the immutable
characteristic of tuple

417 417 417


101
Copyright © 2021, ABES Engineering College
418
Practice Exercises

 Write a Python program to get the 4th element and 4th element from last of a tuple.

 Write a Python program to check whether an element exists within a tuple.

418 418 418


102
Copyright © 2021, ABES Engineering College
419
Built in Methods in Tuple

Tuple has 2 Built in methods

Method name Remark Example


count() It returns the
occurrences of
the value
given
index() It returns the
index of the
specified value

419 419 419


103
Copyright © 2021, ABES Engineering College
420
Operations on Tuple

Tuple has some Remarks


Operations operations, which are listed below:
Example

Concatenation Add two tuples

Creates copies of the


Multiplication
tuple

To check whether an
Membership element belong to tuple
or not

Would return true if


. Not Membership element does not belong
to tuple.
420 420 420
104
Copyright © 2021, ABES Engineering College
421
Loops and Conditions on Tuples

 Tuple can be traversed using Loop

 Take the tuple named tuple_days and print all its elements

 In this example The elements are printed while iterating through for loop condition for in tuple_days and then
we print the values of i in each iteration.

421 421 421


105
Copyright © 2021, ABES Engineering College
422
Loops and Conditions on Tuples

Example:
 Let have a look to the example where we are placing a condition to return the values
having word length greater than 3.

 In above example , The elements are printed while iterating through for loop condition for in tuple_days
and then we print the values of i in each iteration with the condition if(len(i)>3)

422 422 422


106
Copyright © 2021, ABES Engineering College
423
Comparison between List and Tuple

List Tuple
Mutable Sequence Immutable Sequence
Accession Slower than Tuple because of Faster access of elements due to
mutable property immutable property
It cannot be used as Dictionary keys Can work as a key of the dictionary
Not suitable for application which needs It suits such scenarios where write
write protection protection is needed.

423 423 423


107
Copyright © 2021, ABES Engineering College
Session Plan - Day 6 424

3.4 Dictionaries
• Creation
• Assessing
• Modification/Updation
• Nested Dictionary
• Built in Methods
• Review Questions
• Practice Exercises

424 424 424


108
Copyright © 2021, ABES Engineering College
425
Dictionaries

 Dictionary is a unique data collection of Python which stores the


key-value pair.
 The user can add an element by giving a user-defined index called a key.
 Each key and its corresponding value makes the key-value pair in dictionary.
 This key-value pair is considered as one item in dictionary.

425 425 425


109
Copyright © 2021, ABES Engineering College
426
Introduction

 In dictionaries, the indexes are not by default. (such as 0 in string,


list, tuple).
 {} is the representation of Dictionary
 Creation of Dictionary
 An empty dictionary can be created as

426 426 426


110
Copyright © 2021, ABES Engineering College
427
Example-1
 Creating an empty dictionary

427 427 427


111
Copyright © 2021, ABES Engineering College
428
Example-2
 Creating a non-empty dictionary

428 428 428


112
Copyright © 2021, ABES Engineering College
429
Accessing of Dictionary
 In dictionary, the items are accessed by the keys.

429 429 429


113
Copyright © 2021, ABES Engineering College
430
Can you answer these questions?

1. Output of following code?

A) ‘Java’

B) ‘Python’

C) KeyError

D) None of above

430 430 430


114
Copyright © 2021, ABES Engineering College
431
Can you answer these questions?

2. Output of following code?

A) 5

B) 10

C) 15

D) None of above

431 431 431


115
Copyright © 2021, ABES Engineering College
432
Accessing of Dictionary
List Dictionary

By Default indexing User defined Keys

Indexes are only of Keys can be of any


integer type type

Adds an element to Adds an element to


the next default the user defined key
index location

Fetching of element Fetching of value is


is through index, through keys,
lst[0] dic[<key>]

Traversing is easy Traversing is easy


just by increase the just by increase the
index, i+=1 index, i+=1

432 432 432


116
Copyright © 2021, ABES Engineering College
433
Modification in a Dictionary

433 433 433


117
Copyright © 2021, ABES Engineering College
434
Can you answer these questions?

1. Output of following code?

A) {1:’Store’,2:’Kitchen’}

B) {2:’Store’,1:’Kitchen’}

C)KeyError

D) None of above

434 434 434


118
Copyright © 2021, ABES Engineering College
435
Can you answer these questions?

2. Is it possible to change key in dictionary?

A) True

B) False

435 435 435


119
Copyright © 2021, ABES Engineering College
436
Nested Dictionary
 As we have the option of a nested list, similarly, dictionaries can consist of
data collections.

436 436 436


120
Copyright © 2021, ABES Engineering College
Session Plan - Day 7 437

3.4 Dictionary
• Built in Methods in Dictionary
• Loops in Dictionary
• Review Questions
• Practice Exercises

437 437 437


121
Copyright © 2021, ABES Engineering College
438
Built-in Methods in Dictionary
Method Description

copy() Copying a dictionary to another dictionary

fromkeys() Create a new dictionary with key in a data sequence list/tuple with value

get() If the key is present in the dictionary, its value is returned. If the key is not present in a dictionary, then
the default value will be shown as output instead of a KeyError.
items() this will return the key-value pair as an output.

keys() this will return only the keys as an output.

values() this will return only the dictionary values as an output.

update() this adds the one dictionary with another dictionary.

pop() The pop() method takes an argument as the dictionary key, and deletes the item from the dictionary.

popitem() The popitem() method retrieves and removes the last key/value pair inserted into the
dictionary.
438 438 438
122
Copyright © 2021, ABES Engineering College
439
copy()
 copy() method provide a fresh copy with different memory location.

Output

439 439 439


123
Copyright © 2021, ABES Engineering College
440
fromkey()

Output

440 440 440


124
Copyright © 2021, ABES Engineering College
441
get()

Output

441 441 441


125
Copyright © 2021, ABES Engineering College
442
items(),keys(),values()

Output

442 442 442


126
Copyright © 2021, ABES Engineering College
443
update()

Output

443 443 443


127
Copyright © 2021, ABES Engineering College
444
pop(),popitem()

Output

444 444 444


128
Copyright © 2021, ABES Engineering College
445
Can you answer these questions?

1. Output of following code?

A) {1:1,2:4,3:9,4:16,5:25,6:36}

B) {1:1,2:4,3:9,4:16,5:25}

C) [1,4,9,16,25]

D) Error

445 445 445


129
Copyright © 2021, ABES Engineering College
446
Can you answer these questions?

1. Output of following code?

A) {1:’Store’,2:’Kitchen’}

B) {2:’Store’,1:’Kitchen’}

C)KeyError

D) None of above

446 446 446


130
Copyright © 2021, ABES Engineering College
Session Plan - Day 8 447

3.5 Set
• Creation
• Assessing
• Modification
• Built in methods
• Operators
• Loops
• Frozen Set
• Review Questions

447 447 447


131
Copyright © 2021, ABES Engineering College
448
Set

 A set is another data collection data types in python, which stores


unique elements in an unordered way.
 Every element in a set is unique and immutable(unchangeable),
i.e. no duplicate values should be there, and the values can’t be
changed.

448 448 448


132
Copyright © 2021, ABES Engineering College
449
Creation of empty Set

449 449 449


133
Copyright © 2021, ABES Engineering College
450
Creation of non-empty Set

450 450 450


134
Copyright © 2021, ABES Engineering College
451
Creation of non-empty Set

451 451 451


135
Copyright © 2021, ABES Engineering College
452
Can you answer these questions?

2. Is it possible to create an empty set using like s1={} ?

A) True

B) False

452 452 452


136
Copyright © 2021, ABES Engineering College
453
Accessing set

 Python set’s item cannot be accessed using indexes.

453 453 453


137
Copyright © 2021, ABES Engineering College
454
Built-in Methods in Dictionary
Method Description

copy() Copying a set to another set

clear() Removes all element from set

add() Adding a new item in set

update() If the key is present in the dictionary, its value is returned. If the key is not present in a dictionary, then
the default value will be shown as output instead of a Key Error.
remove() to remove the specified element from the given set.

pop() used to removes a random element from the set and returns the popped (removed) elements.

remove () used to remove the specified element from the given set.

discard () used to remove the specified item from the given input set. the remove() method will give an error if
the specified item does not exist but this method will not.

454 454 454


138
Copyright © 2021, ABES Engineering College
455
copy()
 copy() method provide a fresh copy with different memory location.

455 455 455


139
Copyright © 2021, ABES Engineering College
456
clear()

456 456 456


140
Copyright © 2021, ABES Engineering College
457
add()

457 457 457


141
Copyright © 2021, ABES Engineering College
458
update()

458 458 458


142
Copyright © 2021, ABES Engineering College
459
remove()

459 459 459


143
Copyright © 2021, ABES Engineering College
460

discard()

460 460 460


144
Copyright © 2021, ABES Engineering College
461
Operators
Set Operation Description Operator Method

Union All unique elements in set1 and set2 | union()

Intersection Elements present in set1 and set2 & intersection()

Difference Elements that are present in one set, but not the other - difference()

Symmetric Difference Elements present in one set or the other, but not both ^ symmetric_difference()

Disjoint True if the two sets have no elements in common None isdisjoint()
True if one set is a subset of the other (that is, all
Subset <= issubset()
elements of set2 are also in set1)

True if one set is a subset of the other,


Proper Subset < None
but set2 and set1 cannot be identical

True if one set is a superset of the other (that


Superset >= issuperset()
is, set1 contains all elements of set2)

True if one set is a superset of the other,


Proper Superset > None
but set1 and set2 cannot be identical
461 461 461
145
Copyright © 2021, ABES Engineering College
462
Union

462 462 462


146
Copyright © 2021, ABES Engineering College
463
Intersection

463 463 463


147
Copyright © 2021, ABES Engineering College
464
Intersection

464 464 464


148
Copyright © 2021, ABES Engineering College
465
Set Difference

465 465 465


149
Copyright © 2021, ABES Engineering College
466
Symmetric Difference

466 466 466


150
Copyright © 2021, ABES Engineering College
467
Loops with set

467 467 467


151
Copyright © 2021, ABES Engineering College
Frozen Set 468

A frozen set is a special category of the set which is unchangeable once created

468 468 468


152
Copyright © 2021, ABES Engineering College
Frozen Set 469

469 469 469


153
Copyright © 2021, ABES Engineering College
470
Summary
List Tuple Set Dictionary
List is a collection of values Tuple is ordered and Set stores the unique values Dictionary is a collection of
that is ordered. unchangeable collection of as data collection key-value pairs
values
Represented by [ ] Represented by ( ) Represented by { } Represented by { }
Duplicate elements allowed Duplicate elements allowed Duplicate elements not Duplicate keys not allowed, in
allowed dictionary values allowed
duplicate
Values can be of any type Values can be of any type Values can be of any type Keys are immutable type, and
value can be of any type
Example: Example: Example: Example:
[1, 2, 3, 4] (1, 2, 3, 4) {1, 2, 3, 4} {1:1, 2:2, 3:3, 4:4}
List is mutable Tuple is immutable Set is mutable Dictionary is mutable

List is ordered Tuple is ordered Set is unordered Dictionary is insertion ordered

Creating an empty list Creating an empty Tuple Creating a set Creating an empty dictionary
l=list() t = tuple () s=set () d=dict( )
l = [] t=( ) d={}

470 470 470


154
Copyright © 2021, ABES Engineering College
471
Can you answer these questions?

1. Which of the following Python code will create a set?


(i) set1=set((0,9,0))
(ii) set1=set([0,2,9])
(iii) set1={}

A) iii
B) i and ii
C) ii and iii
D) All of Above

471 471 471


155
Copyright © 2021, ABES Engineering College
472
Can you answer these questions?

2. What is the output of following code?


set1=set((0,9,0))
print(set1)

A) {0,0,9}
B) {0,9}
C) {9}
D) Error

472 472 472


156
Copyright © 2021, ABES Engineering College
473
Can you answer these questions?

3. What is the output of following python code?


set1={1,2,3}
set1.add(4)
set1.add(4)
print(set1)
A) {1,2,3}
B) {1,2,3,4}
C) {1,2,3,4,4}
D) Error

473 473 473


157
Copyright © 2021, ABES Engineering College
474

ABES ENGINEERING COLLEGE, GHAZIABAD

Unit-3
QUESTION BANK
SUBJECT NAME: PYTHON PROGRAMMING
SUBJECT CODE: BCC-302

Q.No Description CO BL
Explain the concept of string indexing & slicing and provide an
1 CO3 K2
example in Python.
Differentiate between mutable and immutable objects in Python
2 CO3 K2
language with example.
Explain the difference between function arguments and function
3 parameters. Discuss the concept of variable scope within functions in CO3 K2
Python.
Write a Python program to add 'ing' at the end of a given string (length
should be at least 3). If the given string already ends with 'ing', add
4 CO3 K3
'ly' instead. If the string length of the given string is less than 3, leave
it unchanged.
When to Use Python Lists and when to Use Tuples, Dictionaries or
5 CO3 K2
Sets.
6 Explain Tuples and Unpacking Sequences in Python Data Structure. CO3 K2
Describe the difference between append () and extend () methods in
7 Python lists. CO3 K2

Explain the algorithm Sieve of Eratosthenes used in Python


8 CO3 K2
Programming
Explain the concept of list slicing and demonstrate its usage with a
9 CO3 K2
sample list.
10 Discuss the concept of function decorators and their role in Python. CO3 K2
Find all of the numbers from 1-1000 that are divisible by 7 using list
11 CO3 K3
comprehension.
Write a Python program to get a list, sorted in increasing order by the
last element in each tuple from a given list of non-empty tuples.
12 CO3 K3
Sample List: [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Write a Python script to sort (ascending and descending) a dictionary
13 CO3 K3
by value
Write a Python program to count the number of characters (character
14 CO3 K3
frequency) in a string. Sample String: google.com'.
Write a Python program to compute the square of the first N
15 Fibonacci numbers, using the map function and generate a list of the CO3 K3
numbers.
Implement a function that finds the largest element in a list without
16 CO3 K3
using the max () function.

474 474 474


475

ABES ENGINEERING COLLEGE, GHAZIABAD

Write a program that merges two dictionaries and handles duplicate


17 CO3 K3
keys intelligently.
Develop a Python function that removes duplicates from a list while
18 CO3 K3
maintaining the original order.
Write a Python program to create a lambda function that adds 15 to a
19 given number passed in as an argument, also create a lambda function CO3 K3
that multiplies argument x with argument y and prints the result.
20 Write a Python function to calculate the factorial of a number (a non- CO3 K3
negative integer). The function accepts the number as an argument.

475 475 475


476

Python programming (BCC302)


UNIT-3
QUESTION BANK SOLUTIONS

Q1: Explain the concept of string indexing & slicing and provide an example in Python.

Ans:

There are two type of Indexing:

1: Positive Indexing:

❑ Positive indexing start from Zero (0) and from left hand side i.e. first character store at index 0,
second at index 1 and so on.

❑ Every character of string has some index value.

2: Negative Indexing:

❑ Negative Indexing starts from negative indexing start from -1 and from right-hand side.

❑ Last character store at index -1 and as we move towards the left, it keeps increasing like -2, -3,
and so on.

Slicing: String slicing is the way of selection of substring.


String 'Like' is substring in given 'I Like Python' string. we can access string characters by giving indexes if
we use colon inside square bracket like [:] it becomes a slicing operator in Python.

476 476 476


477

➢ Start index: Index from which slicing starts.

➢ End Index: Index up to which slicing end.

➢ Step value is optional.

Example:

Q2: Differentiate between Mutable and Immutable objects in python languages with
example?
Ans:

Mutable Objects: Immutable Objects:

477 477 477


478

• Mutable objects are • Immutable objects are


those whose state or those whose state or
value can be modified value cannot be
after creation. modified after creation.
• Lists, dictionaries, and • Strings, tuples, and
sets are examples of integers are examples
mutable objects in of immutable objects in
Python. Python.
• When you modify a • When you perform an
mutable object, you are operation that appears
actually changing the to modify an
object in place. immutable object, you
are actually creating a
new object with the
modified value.

Example of Mutable Object: Examples of Immutable


Objects:
python
# Mutable object: List python
my_list = [1, 2, 3, 4] # Immutable objects:
String, Tuple, Integer
# Modifying the list in my_string = "Hello"
place my_tuple = (1, 2, 3)
my_list[2] = 10 my_integer = 5
print(my_list) # Output:
[1, 2, 10, 4] # Operations that create
new objects
In the example above, the list new_string = my_string +
", World!"
my_list can be modified by
new_tuple = my_tuple +
changing the value at a specific (4, 5)
index. new_integer = my_integer
* 2

# Original objects remain


unchanged
print(my_string) #
Output: 'Hello'
print(my_tuple) #
Output: (1, 2, 3)
print(my_integer) #
Output: 5

# New objects with


modified values
print(new_string) #
Output: 'Hello, World!'
print(new_tuple) #
Output: (1, 2, 3, 4, 5)

478 478 478


479

print(new_integer) #
Output: 10

Q3:
Explain the difference between function arguments and function
parameters. Discuss the concept of variable scope within
functions in Python

Ans: In Python, the terms "function parameters" and "function


arguments" are often used interchangeably, but they have distinct
meanings:

1. Function Parameters:
o Parameters are the names used in the function
definition to represent the input values that a
function expects.
o They act as placeholders for the actual values
(arguments) that will be passed into the function
when it is called.
o Parameters are defined in the function signature and
serve as a way to declare what kind of values a
function should accept.

python
• def add(x, y): # x and y are parameters
result = x + y
return result

• Function Arguments:

• Arguments are the actual values or expressions passed to a


function when it is called.
• They correspond to the parameters of the function and
provide the actual data that the function will operate on.
• Arguments are passed within the parentheses when calling
a function.

python
2. # 2 and 3 are arguments
3. sum_result = add(2, 3)
4.

1. Local Scope:

479 479 479


480

o Variables defined within a function have a local


scope, meaning they are only accessible within that
function.
o Once the function completes execution, the local
variables are destroyed, and their values are not
accessible from outside the function.

python
• def example_function():
local_variable = "I am local"
print(local_variable)

example_function()
# This would cause an error because local_variable is
not defined here:
# print(local_variable)

• Global Scope:

• Variables defined outside of any function have a global


scope, making them accessible throughout the entire
program.
• Global variables can be accessed and modified both inside
and outside functions.

python
• global_variable = "I am global"

def example_function():
print(global_variable)

example_function()
print(global_variable)

• Scope Hierarchy:

• When a variable is referenced within a function, Python


first looks for it in the local scope. If not found, it searches
in the enclosing (if any) function's scope, and so on, until it
reaches the global scope.

python
x = 10 # Global variable

def outer_function():
y = 20 # Enclosed variable

def inner_function():
z = 30 # Local variable
print(x, y, z)

480 480 480


481

inner_function()

outer_function()

In the example above, inner_function can access both the global


variable x and the enclosed variable y, but outer_function cannot
directly access z because it's local to inner_function.

Q4: Write a Python program to add 'ing' at the end of a given string
(length should be at least 3). If the given string already ends with 'ing',
add 'ly' instead. If the string length of the given string is less than 3,
leave it unchanged.
Ans:

def modify_string(input_string):

if len(input_string) >= 3:

if input_string.endswith('ing'):

result_string = input_string + 'ly'

else:

result_string = input_string + 'ing'

else:

result_string = input_string

return result_string

# Example usage:

input_str1 = "play"

input_str2 = "swimming"

input_str3 = "go"

result1 = modify_string(input_str1)

result2 = modify_string(input_str2)

result3 = modify_string(input_str3)

print(f"Original: {input_str1}, Modified: {result1}")

481 481 481


482

print(f"Original: {input_str2}, Modified: {result2}")

print(f"Original: {input_str3}, Modified: {result3}")

Q5:
When to Use Python Lists and when to Use Tuples, Dictionaries
or Sets.
ANS:

In Python, lists, tuples, dictionaries, and sets are all data structures that serve different purposes.
The choice of which one to use depends on the specific requirements of your program. Here are
some guidelines on when to use each:

1. Lists:
o Use when:
▪ You need an ordered collection of items.
▪ You need a collection that allows duplicate elements.
▪ You need to modify the elements (add, remove, or modify) after creation.
o Example:

python

• •
• my_list = [1, 2, 3, 'hello', 2.5]

• Tuples:

• Use when:
o You need an ordered, immutable collection of items.
o You want to create a collection that should not be changed during the program's
execution.
o You want to use the collection as a key in a dictionary (since keys must be
immutable).
• Example:

python

• •
• my_tuple = (1, 2, 'world', 3.14)

• Dictionaries:

• Use when:
o You need an unordered collection of key-value pairs.
o You want to look up values based on some unique identifier (the key).
o You need to associate values with labels or names.
• Example:

482 482 482


483

python

• •
• my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

• Sets:

• Use when:
o You need an unordered collection of unique elements.
o You want to perform set operations like union, intersection, and difference.
• Example:

python

4.
o my_set = {1, 2, 3, 4, 5}
o

Note:

• Use lists when you need an ordered collection with the ability to modify elements.
• Use tuples when you need an ordered and immutable collection.
• Use dictionaries when you need a collection of key-value pairs for quick lookups.
• Use sets when you need an unordered collection of unique elements and want to perform
set operations.

Ultimately, the choice between lists, tuples, dictionaries, and sets depends on the specific
requirements of your program and the characteristics of each data structure.

Q6:
Explain Tuples and Unpacking Sequences in Python Data
Structure
ANS:

Tuples in Python:

A tuple is a data structure in Python that is similar to a list but is immutable, meaning its elements
cannot be changed after creation. Tuples are defined using parentheses () and can contain elements
of different data types. Tuples are often used to represent fixed collections of items.

Creating a Tuple:

python
my_tuple = (1, 'hello', 3.14)

Accessing Elements:

483 483 483


484

python
first_element = my_tuple[0] # Accessing the first element

Immutable Nature:

python
# This will result in an error because tuples are immutable
my_tuple[1] = 'world'

Unpacking Sequences in Python:

Unpacking sequences is a feature in Python that allows you to assign the elements of a sequence
(like a tuple or a list) to multiple variables in a single line. This is often used with tuples to assign
values to individual variables.

Example:

python
# Creating a tuple
coordinates = (3, 4)

# Unpacking the tuple into separate variables


x, y = coordinates

print("x:", x) # Output: x: 3
print("y:", y) # Output: y: 4

In this example, the tuple (3, 4) is unpacked into the variables x and y. This is a concise way to
assign values to multiple variables at once.

Swapping Variables:

python
a = 5
b = 10

# Swapping values using tuple unpacking


a, b = b, a

print("a:", a) # Output: a: 10
print("b:", b) # Output: b: 5

Unpacking sequences is not limited to tuples; it can be used with any iterable, such as lists.

Using the * Operator for Unpacking:

python
# Unpacking with the * operator
first, *rest = (1, 2, 3, 4, 5)

print("first:", first) # Output: first: 1

484 484 484


485

print("rest:", rest) # Output: rest: [2, 3, 4, 5]

Q7:
Describe the difference between append () and extend () methods
in Python lists.
ANS:

In Python, append() and extend() are two methods used to add elements to lists, but they behave
differently:

1. append() Method:
o The append() method is used to add a single element to the end of the list.
o The element can be of any data type, including another list or any other object.
o It modifies the original list in place by adding the specified element as a single item.

python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

If the element being appended is a list, it is added as a single element, not as individual elements.

python
• my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list) # Output: [1, 2, 3, [4, 5]]

• extend() Method:

• The extend() method is used to append elements from an iterable (e.g., a list, tuple, string)
to the end of the list.
• It modifies the original list in place by adding each element from the iterable individually.

python
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]

Q8:
Explain the algorithm Sieve of Eratosthenes used in Python
Programming
ANS:

The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to a given limit.
It efficiently identifies prime numbers and eliminates multiples of each prime as it iterates through

485 485 485


486

the numbers. The algorithm is named after the ancient Greek mathematician Eratosthenes, who
first described it.

Here's a step-by-step explanation of the Sieve of Eratosthenes algorithm:

1. Create a List of Numbers:


o Generate a list of integers from 2 to the desired limit. These are the numbers we
want to check for primality.
2. Start with the First Prime (2):
o The first number in the list is 2, which is a prime number. Mark it as prime, and
eliminate all multiples of 2 from the list.
3. Move to the Next Unmarked Number:
o Move to the next unmarked number (in this case, 3). Mark it as prime, and eliminate
all multiples of 3 from the list.
4. Repeat Until the Square Root of the Limit:
o Continue this process, marking the next unmarked number as prime and eliminating
its multiples, until the square root of the limit is reached. This is because, for any
composite number n, its smallest prime factor is guaranteed to be less than or equal
to √n.
5. Remaining Unmarked Numbers are Primes:
o After completing the elimination process, the remaining unmarked numbers in the
list are prime.

Here's a Python implementation of the Sieve of Eratosthenes:

python
def sieve_of_eratosthenes(limit):
primes = []
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False

for number in range(2, int(limit**0.5) + 1):


if is_prime[number]:
primes.append(number)
for multiple in range(number * number, limit + 1, number):
is_prime[multiple] = False

for number in range(int(limit**0.5) + 1, limit + 1):


if is_prime[number]:
primes.append(number)

return primes

# Example usage:
limit = 30
result = sieve_of_eratosthenes(limit)
print(result)

In this implementation, is_prime is a boolean list where is_prime[i] is True if i is a prime


number and False otherwise. The function returns a list of prime numbers up to the specified limit.

486 486 486


487

The time complexity of the Sieve of Eratosthenes is generally considered to be O(n log log n),
making it an efficient algorithm for finding primes.

Q9:
Explain the concept of list slicing and demonstrate its usage with
a sample list.

ANS:

List slicing in Python is a technique that allows you to create a subsequence (or "slice") of a list
by specifying a range of indices. The general syntax for list slicing is list[start:stop:step],
where start is the index of the first element to include, stop is the index of the first element to
exclude, and step is the number of indices between each element in the slice. All three parameters
are optional.

Here's an explanation of each part of the syntax:

• start: The index of the first element to include in the slice. If omitted, it defaults to 0 for
positive step values or -1 for negative step values (i.e., it starts from the end of the list).
• stop: The index of the first element to exclude from the slice. If omitted, it defaults to the
end of the list for positive step values or the beginning of the list for negative step values.
• step: The number of indices between each element in the slice. If omitted, it defaults to 1.

Now, let's demonstrate list slicing with a sample list:

python
# Sample list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Basic slicing examples


slice1 = my_list[2:6] # Elements from index 2 to 5 (exclusive)
slice2 = my_list[3:] # Elements from index 3 to the end
slice3 = my_list[:5] # Elements from the beginning to index 4
slice4 = my_list[1:8:2] # Elements from index 1 to 7, every 2nd element

# Negative indexing and reverse slicing


slice5 = my_list[-3:] # Last 3 elements
slice6 = my_list[::-1] # Reverse the entire list

# Printing the results


print("Original list:", my_list)
print("Slice 1:", slice1)
print("Slice 2:", slice2)
print("Slice 3:", slice3)
print("Slice 4:", slice4)
print("Slice 5:", slice5)
print("Slice 6:", slice6)

Output:

487 487 487


488

less
Original list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Slice 1: [2, 3, 4, 5]
Slice 2: [3, 4, 5, 6, 7, 8, 9]
Slice 3: [0, 1, 2, 3, 4]
Slice 4: [1, 3, 5, 7]
Slice 5: [7, 8, 9]
Slice 6: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In the example above, various slices of the original list are created using different combinations of
start, stop, and step values. The results demonstrate how list slicing can be a powerful and
concise way to extract specific portions of a list.

Q10:
Discuss the concept of function decorators and their role in
Python
ANS:

In Python, a decorator is a design pattern that allows you to extend or modify the behavior of
functions or methods without changing their actual code. Decorators are applied using the
@decorator syntax before the function definition. They are a powerful and flexible feature in
Python, commonly used for tasks such as logging, timing, authentication, and more.

Key Concepts:

1. Syntax:
o A decorator is a function that takes another function as an argument and usually returns
a new function that enhances or modifies the behavior of the original function.

python
• @decorator
def my_function():
# Original function code

• Function as First-Class Object:

• In Python, functions are first-class objects, which means they can be passed as arguments to other
functions and returned as values from other functions.

• Applying Multiple Decorators:

• You can apply multiple decorators to a single function, and they are executed in the order they
are listed.

python
3. @decorator1
4. @decorator2
5. def my_function():
6. # Original function code

488 488 488


489

7. This is equivalent to decorator1(decorator2(my_function)).

Example:

Let's consider a simple example of a decorator that logs information about the function call:

python
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned: {result}")
return result
return wrapper

@log_decorator
def add(a, b):
return a + b

result = add(3, 5)

In this example, the log_decorator function takes another function (func) as its argument,
defines a new function (wrapper) that logs information before and after calling func, and returns
this new function. The @log_decorator syntax is used to apply the decorator to the add function.

When add(3, 5) is called, it is actually the wrapper function created by the decorator that gets
executed, and it logs information about the function call.

Role in Python:

• Code Reusability: Decorators allow you to encapsulate common behavior and reuse it
across multiple functions.
• Separation of Concerns: Decorators help separate the concerns of different aspects of
code, making it more modular and easier to maintain.
• Aspect-Oriented Programming (AOP): Decorators support the AOP paradigm by
providing a way to add cross-cutting concerns (e.g., logging, authentication) without
modifying the core logic of functions.
• Readability: Decorators improve code readability by keeping the core functionality of a
function separate from additional features.

Decorators are a powerful tool in Python, enabling clean and modular code design by promoting
the separation of concerns and facilitating code reuse. They are widely used in various frameworks
and libraries to enhance the functionality of functions and methods.

Q11:
Find all of the numbers from 1-1000 that are divisible by 7 using list
comprehension.
ANS:

489 489 489


490

divisible_by_7 = [num for num in range(1, 1001) if num % 7 == 0]

# Print the result


print(divisible_by_7)

In this code:

• range(1, 1001) generates numbers from 1 to 1000.


• The list comprehension [num for num in range(1, 1001) if num % 7 == 0] iterates
through each number in the range and includes it in the list only if it is divisible by 7 (num
% 7 == 0 checks for divisibility).

When you run this code, it will print a list containing all the numbers from 1 to 1000 that are
divisible by 7.

Q12:
Write a Python program to get a list, sorted in increasing order
by the last element in each tuple from a given list of non-empty
tuples.
Sample List: [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
ANS:
# Sample list of tuples
sample_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

# Define a custom key function to extract the last element from each tuple
def last_element_of_tuple(t):
return t[-1]

# Use sorted() with the custom key function to sort the list of tuples
sorted_list = sorted(sample_list, key=last_element_of_tuple)

# Print the result


print("Original List:", sample_list)
print("Sorted List:", sorted_list)

This program defines a custom key function last_element_of_tuple that takes a tuple and
returns its last element (t[-1]). Then, the sorted() function is used with this custom key function
to sort the list of tuples based on their last elements.

When you run this program, it will output the expected result:

less
Original List: [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Sorted List: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

Q13:
Write a Python script to sort (ascending and descending) a dictionary
by value

490 490 490


491

ANS:
#Sample dictionary
sample_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

# Sort dictionary by values in ascending order


sorted_dict_ascending = dict(sorted(sample_dict.items(), key=lambda item:
item[1]))

# Sort dictionary by values in descending order


sorted_dict_descending = dict(sorted(sample_dict.items(), key=lambda item:
item[1], reverse=True))

# Print the results


print("Original Dictionary:", sample_dict)
print("Sorted Dictionary (Ascending):", sorted_dict_ascending)
print("Sorted Dictionary (Descending):", sorted_dict_descending)

In this script:

• sorted(sample_dict.items(), key=lambda item: item[1]) is used to sort the


dictionary by values in ascending order. The key parameter is set to a lambda function that
extracts the values.
• sorted(sample_dict.items(), key=lambda item: item[1], reverse=True) is used
to sort the dictionary by values in descending order. The reverse=True argument is added
to the sorted() function.

When you run this script, it will output the original dictionary and two sorted dictionaries
(ascending and descending):

python
Original Dictionary: {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}
Sorted Dictionary (Ascending): {'grape': 1, 'banana': 2, 'apple': 5, 'orange':
8}
Sorted Dictionary (Descending): {'orange': 8, 'apple': 5, 'banana': 2, 'grape':
1}

Q14:
Write a Python program to count the number of characters
(character frequency) in a string. Sample String: google.com'
ANS:
# Sample string
sample_string = 'google.com'

# Initialize an empty dictionary to store character frequencies


char_frequency = {}

491 491 491


492

# Count the frequency of each character


for char in sample_string:
char_frequency[char] = char_frequency.get(char, 0) + 1

# Print the character frequencies


print("Character Frequencies in the String:")
for char, frequency in char_frequency.items():
print(f"{char}: {frequency}")

This program uses a dictionary (char_frequency) to store the frequency of each character in the
given string. The for loop iterates through each character in the string, and the get() method is
used to retrieve the current count of the character (or 0 if it's the first occurrence), and then
increments it.

When you run this program with the provided sample string, it will output the character
frequencies:

makefile
Character Frequencies in the String:
g: 2
o: 4
l: 1
e: 1
.: 1
c: 1
m: 1

Q15:
Write a Python program to compute the square of the first N
Fibonacci numbers, using the map function and generate a list of
the numbers.
ANS:
# Function to generate the first N Fibonacci numbers
def generate_fibonacci(n):
fib_numbers = [0, 1]
while len(fib_numbers) < n:
fib_numbers.append(fib_numbers[-1] + fib_numbers[-2])

492 492 492


493

return fib_numbers[:n]

# Function to compute the square of a number


def square(x):
return x ** 2

# Specify the value of N


N = 10

# Use map to compute the square of each Fibonacci number


squared_fibonacci = list(map(square, generate_fibonacci(N)))

# Print the result


print(f"The first {N} Fibonacci numbers squared:")
print(squared_fibonacci)

In this program:

• The generate_fibonacci function generates the first N Fibonacci numbers.


• The square function computes the square of a given number.
• The map function applies the square function to each element of the list of Fibonacci
numbers.
• The list() constructor is used to convert the result of map into a list.

Adjust the value of N as needed, and when you run the program, it will output the squared Fibonacci
numbers:

python
The first 10 Fibonacci numbers squared:
[0, 1, 1, 9, 25, 121, 361, 1444, 3249, 8100]

Q16: Implement a function that finds the largest e;ement in a list without using the max() function?

ANS:
def find_largest_element(lst):
# Check if the list is empty
if not lst:
return None

# Initialize the maximum to the first element


largest = lst[0]

# Iterate through the list to find the largest element


for element in lst:
if element > largest:
largest = element

return largest

# Example usage:
my_list = [3, 8, 2, 7, 5, 1, 4]
result = find_largest_element(my_list)

493 493 493


494

print("List:", my_list)
print("Largest Element:", result)

Q17: Write a program that merges two dictionaries and handles duplicate keys intelligently.
ANS:
def merge_dictionaries(dict1, dict2, conflict_resolution=lambda x, y: x + y):
merged_dict = dict1.copy()

for key, value in dict2.items():


if key in merged_dict:
merged_dict[key] = conflict_resolution(merged_dict[key], value)
else:
merged_dict[key] = value

return merged_dict

# Example dictionaries
dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 25, 'c': 35, 'd': 40}

# Merge dictionaries with conflict resolution using maximum value


merged_dict = merge_dictionaries(dict1, dict2, conflict_resolution=max)

# Print the result


print("Dictionary 1:", dict1)
print("Dictionary 2:", dict2)
print("Merged Dictionary (using max):", merged_dict)

Q18: Develop a Python function that removes duplicates from a list while maintaining the original
order.
ANS:
def remove_duplicates(original_list):
seen = set()
unique_list = []

for element in original_list:


if element not in seen:
seen.add(element)
unique_list.append(element)

return unique_list

# Example usage:
my_list = [3, 2, 1, 2, 4, 3, 5, 4, 6]
result = remove_duplicates(my_list)

print("Original List:", my_list)

In this example:

494 494 494


495

• The remove_duplicates function takes a list (original_list) as input.


• It uses a set (seen) to keep track of elements that have already been encountered.
• It iterates through the original list, and if an element is not in the set, it adds it to both the
set and a new list (unique_list).
• The function returns the list with duplicates removed.

When you run this code with the provided example list, it will output:

mathematica
Original List: [3, 2, 1, 2, 4, 3, 5, 4, 6]
List with Duplicates Removed: [3, 2, 1, 4, 5, 6]

Q19: Write a Python program to create a lambda function that adds 15 to a given number passed in as
an argument, also create a lambda function that multiplies argument x with argument y and prints the
result
ANS:
# Lambda function to add 15 to a given number
add_15 = lambda x: x + 15

# Lambda function to multiply two numbers


multiply = lambda x, y: x * y

# Example usage
number_to_add_15 = 5
result_add_15 = add_15(number_to_add_15)
print(f"Adding 15 to {number_to_add_15}: {result_add_15}")

number1 = 3
number2 = 7
result_multiply = multiply(number1, number2)
print(f"Multiplying {number1} and {number2}: {result_multiply}")

In this program:

• The add_15 lambda function takes one argument x and adds 15 to it.
• The multiply lambda function takes two arguments x and y and multiplies them.

When you run this code, it will output:

yaml
Adding 15 to 5: 20
Multiplying 3 and 7: 21

Q20: Write a Python function to calculate the factorial of a number (a non-negative integer). The
function accepts the number as an argument.
ANS:
def factorial(n):

495 495 495


496

# Base case: factorial of 0 or 1 is 1


if n == 0 or n == 1:
return 1
else:
# Recursive case: n! = n * (n-1)!
return n * factorial(n - 1)

# Example usage:
number = 5
result = factorial(number)

print(f"The factorial of {number} is: {result}")

In this function:

• The base case checks if n is 0 or 1, in which case the factorial is 1.


• The recursive case calculates the factorial using the formula n! = n * (n-1)!.

When you run this code with the provided example (number = 5), it will output:

csharp
The factorial of 5 is: 120

496 496 496


497

LAST YEAR QUESTIONS AND IMPORTANT QUESTIONS

1. MERGING OF DICTONARY WITH 2ND largest NO


def merge_dictionaries(dict1, dict2, conflict_resolution=lambda x, y: x + y):
merged_dict = dict1.copy()

for key, value in dict2.items():


if key in merged_dict:
merged_dict[key] = conflict_resolution(merged_dict[key], value)
else:
merged_dict[key] = value

return merged_dict

dict1 = {'a': 10, 'b': 20, 'c': 30}


dict2 = {'b': 25, 'c': 35, 'd': 40}

merged_dict = merge_dictionaries(dict1, dict2, conflict_resolution=max)

print("Dictionary 1:", dict1)


print("Dictionary 2:", dict2)
print("Merged Dictionary (using max):", merged_dict)

Dictionary 1: {'a': 10, 'b': 20, 'c': 30}


Dictionary 2: {'b': 25, 'c': 35, 'd': 40}
Merged Dictionary (using max): {'a': 10, 'b': 25, 'c': 35, 'd': 40}

1. Find largest no from list


def find_largest_element(lst):

if not lst:

return None

largest = lst[0]

for element in lst:

if element > largest:

largest = element

return largest

my_list = [3, 8, 2, 7, 5, 1, 4]

497 497 497


498

result = find_largest_element(my_list)

print("List:", my_list)

print("Largest Element:", result)


List: [3, 8, 2, 7, 5, 1, 4]
Largest Element: 8

2. Find no of character In given string:


# Sample string

sample_string = 'google.com'

# Initialize an empty dictionary to store character frequencies

char_frequency = {}

# Count the frequency of each character

for char in sample_string:

char_frequency[char] = char_frequency.get(char, 0) + 1

# Print the character frequencies

print("Character Frequencies in the String:")

for char, frequency in char_frequency.items():

print(f"{char}: {frequency}")

o/p:
Character Frequencies in the String:
g: 2
o: 3
l: 1
e: 1
.: 1
c: 1
m: 1

3. Ascending and descending of dictionary:

498 498 498


499

#Sample dictionary
sample_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

# Sort dictionary by values in ascending order


sorted_dict_ascending = dict(sorted(sample_dict.items(), key=lambda item: item[1]))

# Sort dictionary by values in descending order


sorted_dict_descending = dict(sorted(sample_dict.items(), key=lambda item: item[1],
reverse=True))

# Print the results


print("Original Dictionary:", sample_dict)
print("Sorted Dictionary (Ascending):", sorted_dict_ascending)
print("Sorted Dictionary (Descending):", sorted_dict_descending)

o/p:
Original Dictionary: {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}
Sorted Dictionary (Ascending): {'grape': 1, 'banana': 2, 'apple': 5,
'orange': 8}
Sorted Dictionary (Descending): {'orange': 8, 'apple': 5, 'banana': 2,
'grape': 1}

4. Sorted of tuple:
# Sample list of tuples

sample_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

# Define a custom key function to extract the last element from each tuple

def last_element_of_tuple(t):

return t[-1]

# Use sorted() with the custom key function to sort the list of tuples

sorted_list = sorted(sample_list, key=last_element_of_tuple)

# Print the result

print("Original List:", sample_list)

499 499 499


500

print("Sorted List:", sorted_list)

o/p:
Original List: [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Sorted List: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

5. Convert 12 hr format into 24 hr format

def convert_to_24_hour_format(time_12_hour):
# Split the time into hours, minutes, and AM/PM
time_components = time_12_hour.split()
time = time_components[0].split(":")
hours, minutes = int(time[0]), int(time[1])
period = time_components[1]

# Convert to 24-hour format


if period.upper() == 'PM' and hours != 12:
hours += 12
elif period.upper() == 'AM' and hours == 12:
hours = 0

# Format the result


time_24_hour = "{:02d}:{:02d}".format(hours, minutes)
return time_24_hour

# Example usage:
time_12_hour = "03:45 PM"
time_24_hour = convert_to_24_hour_format(time_12_hour)
print(f"{time_12_hour} in 24-hour format is: {time_24_hour}")

o/p:
03:45 PM in 24-hour format is: 15:45

6. Find vowels in input string:

def count_vowels(input_string):
# Initialize a variable to store the count
vowel_count = 0

# Convert the input string to lowercase to handle both uppercase and lowercase vowels
input_string = input_string.lower()

500 500 500


501

# Iterate through each character in the string


for char in input_string:
# Check if the character is a vowel
if char in "aeiou":
vowel_count += 1

return vowel_count

# Get input from the user


user_input = input("Enter a string: ")

# Call the function to count vowels


result = count_vowels(user_input)

# Display the result


print(f"Number of vowels in the input string: {result}")

o/p:

Enter a string: rahul


Number of vowels in the input string: 2

7. Even number from 1 to 20 but skip 10 number


for num in range(1, 21):

# Check if the number is even

if num % 2 == 0:

# Skip number 10

if num == 10:

continue

# Print the even number

print(num)

o/p:
2
4
6
8
12
14
16

501 501 501


502

18
20

8. Armstrong_numbe program :
def is_armstrong_number(number):

# Convert the number to a string to get individual digits

str_number = str(number)

# Calculate the number of digits

num_digits = len(str_number)

# Calculate the sum of each digit raised to the power of the number of digits

sum_of_digits = sum(int(digit) ** num_digits for digit in str_number)

# Check if the sum is equal to the original number

return sum_of_digits == number

# Get user input for the number to check

user_number = int(input("Enter a number to check for Armstrongness: "))

# Check and print the result

if is_armstrong_number(user_number):

print(f"{user_number} is an Armstrong number.")

else:

print(f"{user_number} is not an Armstrong number.")

O/P:
Enter a number to check for Armstrongness: 153
153 is an Armstrong number.

502 502 502


503

9. Palindrome PROGRAM
def is_palindrome(input_str):

# Convert the input to lowercase (for case-insensitive comparison)

input_str = str(input_str).lower()

# Remove spaces and special characters

input_str = ''.join(char for char in input_str if char.isalnum())

# Check if the reversed string is equal to the original string

return input_str == input_str[::-1]

# Get user input for the string or number to check

user_input = input("Enter a string or number to check for palindrome: ")

# Check and print the result

if is_palindrome(user_input):

print(f"{user_input} is a palindrome.")

else:

print(f"{user_input} is not a palindrome.")

10. PATTERN QUESTIONS:


rows = 5

# Upper part of the pattern


for i in range(1, rows + 1):
for j in range(1, i + 1):

503 503 503


504

print("*", end=" ")


print()

# Lower part of the pattern


for i in range(rows - 1, 0, -1):
for j in range(1, i + 1):
print("*", end=" ")
print()

O/P:

*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

504 504 504


505
1

Index
UNIT-4
PYTHON : BCC-302

S.NO Topic Page no


1. Notes 2

2. Class Programs 24

3. Important Questions 30

505 505 505


1
506
2

Table of Contents
.............................................................................................................................................................0
8.1 Introduction to Files .....................................................................................................................2
8.2 Types of Files................................................................................................................................2
8.3 Opening and Closing a Text File ..................................................................................................... 4
8.3.1 File Opening ..........................................................................................................................4
8.3.2 File Closing ............................................................................................................................6
8.4 Read Mode in File Handling .......................................................................................................... 6
8.4.1 Read ()method .......................................................................................................................7
8.4.2 Readline () and Readlines () method/Function......................................................................... 8
8.5 Write Mode in File Handling.......................................................................................................... 9
8.6 Append Mode in File Handling .................................................................................................... 10
8.7 Multiple Operations with File Handling ....................................................................................... 11
Reading file in ‘r+’ mode ............................................................................................................... 12
Reading file in ‘w+’ mode.............................................................................................................. 12
Writing file in ‘r+’ mode ................................................................................................................ 13
Writing file in ‘w+’ mode .............................................................................................................. 13
8.8 Delete a File ............................................................................................................................... 13
8.9 Pickle in Python .......................................................................................................................... 14
8.9.1 Pickling files ......................................................................................................................... 14
8.9.2 Unpickling files .................................................................................................................... 15
References....................................................................................................................................... 16

506 506 506


2
507
3

8.1 Introduction to Files


Files are named locations on disk to store related information. They are used to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several functions for
creating, reading, updating, and deleting the files.

In Python, a file handling operation takes place in the following order as:

1. Open a file
2. Read / write perform operation or tasks
3. Close the file at end
Note: input value by user stored in RAM which is volatile memory (finished after close program)
But in Application, we have to store data (two ways store data: file handling and data base)
Q: Explain the difference between text mode ('t') and binary mode ('b') when opening a file
in Python.

8.2 Types of Files


Every file is encoded in the form of binary data (0s and 1s). Thus, every file is merely a stream of
bytes sequentially stored.

There are essentially two file types text files and binary files.

Text file: It contains characters that are viewable by any text editor. Alphabets, numbers, and
other special symbols are used to make up a text file.

• It contains the “text” usually in ASCII.


• The last character in each text file is termed the End of Line character (EOL).
• The default end-of-line character in Python is the newline (\n).
• A text file can be a text document that contains the details of student their name,
section, marks etc.

Figure 8.2 (a): A text file


• Common extensions that are text file formats:
507 507 507
3
508
4

Text File

Tabular data( csv,


Webstandards files ( html, tsv)
xml, css, svg, json)
Configuration
filesini, cfg, rc, reg)
Source code files (c, cpp,
h, cs, js, py, java, rb, pl, Documents (txt,tex,
markdown, asciidoc,
rtf, ps)

Figure 8.2 (b): Common text files

Binary file: The term "binary file" is often used as a term meaning “non-text file”.

• These files are not meant to be readable by humans in notepad or editor.


• Some specific software is required to open binary files. A binary file can be a jpeg image.

Figure 8.2 (c): A binary file in hex editor


• Common extensions that are binary file formats:
3
508 508 508
4
509
5

Text File

Database: mdb,
Images: jpg, png, gif, bmp, accde, frm, sqlite
tiff, psd
Archive: zip, rar, 7z,
Audio: mp3, aac, wav, tar, iso
flac, ogg, mka, wma
Documents (pdf, doc, xls,
ppt, docx, odt) Executable: exe, dll, so,
Videos: mp4, mkv, avi,
class
mov, mpg, vob

Figure 8.2 (d): Common binary files

8.3 Opening and Closing a Text File


These days, computers deal with numerous data formats including databases, CSV files, HTML,
XML, etc. Files in general are used to either read or write data. However, working with files
includes performing several functions such as creating, opening, writing, navigating, and
reading. The io module offers numerous methods for managing files in Python.

8.3.1 File Opening


Python has a built-in open() function to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly. The basic syntax of open () is
as follows:

Figure 8.3.1(a): Basic Syntax

4
509 509 509
5
510
6

Here are parameter details −

file_name − The file_name argument is a string value that contains the name or path of the file that you
want to access.

Figure 8.3.1 (b): example of file_name

access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. A complete list of possible values is given below in the table. This is optional
parameter and the default file access mode is read (r).

Table 8.3.1 (a) : list of the different modes of opening a file


Q: What are the primary modes in which you can open a file in Python
for reading and writing? Explain each mode briefly.

access_mode Description
“r” Opens a file for reading. (default)
“w” Opens a file for writing. Creates a new file if it does not
exist or truncates the file if it exists.
“a” Opens a file for appending at the end of the file without
truncating it. Creates a new file if it does not exist.
“x” Opens a file for exclusive creation. If the file already
exists, the operation fails.
“t” Opens in text mode. (default)
“b” Opens in binary mode.
“+” Opens a file for updating (reading and writing)

Figure 8.3.1 (c): example of access_mode

FileNotFoundError has been occurred in python if file not found or wrong path has been written.
Consider an example to open a file name Test.txt contains the marks of student and this file not exist in
current working directory.

5
510 510 510
6
511
7

Figure 8.3.1(d): General Mistake while using Open function

To avoid this mistake we can prefer “pwd” command to know the path of file. For example table 8.3.2
(b) shows the correct example of path in linux and windows.

Table 8.3.2 (b): Correct file path

OS Path
Linux “D:/myfiles/welcome.txt”
Windows “D:\\myfiles\\welcome.txt”
8.3.2 File Closing
It is a common practice to close a file when we have completed the read/write operations on it.
Python uses built-inclose () function. The system frees the RAM assigned to a file when it is
closed.

The basic syntax:

Figure 8.3.2: Closing a file

Here, file_object is an object of file that has been open for read or write operation.

8.4 Read Mode in File Handling


We can simply read the content of the existing file bypassing “r” or “r+” mode inside the open
function.As the second argument is optional in an open method so if don’t pass anything, the
file opens in reading mode by default.

6
511 511 511
7
512
8

Figure 8.4: Reading file without the read () method

Q: What is the purpose of the with statement when working with files in Python? Provide an
example?
Ans: The with statement in Python is used to ensure that a block of code is executed within the
context of a specific context manager. For file handling, the with statement is commonly used to
open and manage files. The primary purpose is to ensure that the file is properly closed after the
block of code is executed, even if an exception occurs.

Without use of with: Ensure the file is closed

file = open(file_path, "r")


content = file.read()
print(content)
file.close()

with use of with: No need for an explicit 'finally' block; the file is
automatically closed
with open(file_path, "r") as file:
content = file.read()
print(content)

7
512 512 512
8
513
9

Note:
1. Read content in file:
You can read the entire contents of a file using the read() method.
Ex:
with open("unit.txt", "r") as file:
content = file.read()
print(content)

2. Reading Line by Line:


• To read a file line by line, you can use a loop or the readline() method.
Ex:
with open("unit.txt", "r") as file:
for line in file:
print(line.strip())

3. Reading a Specific Number of Characters:

The read(n) method reads the next n characters from the file.
Ex:
with open("unit.txt", "r") as file:
partial_content = file.read(10) # Reads the first 10 characters
print(partial_content)

4. Seeking and Reading:

• The seek(offset) method moves the file cursor to a specified offset. Combine it with
read() for more control.
python
with open("example.txt", "r") as file:
file.seek(5) # Move to the 6th character
partial_content = file.read(10) # Read the next 10 characters
print(partial_content)

5. Reading Binary Files:


• When dealing with binary files, use the "rb" mode and read binary data using read().
python
with open("image.jpg", "rb") as file:
binary_data = file.read()
8
513 513 513
9
514
10

# Process binary data as needed

Q: What is Difference between readline() and readlines()?


readline() Method:
The readline() method reads a single line from the file. If you call it again, it will read the
next line. This is useful when you want to process the file line by line.
python
file_path = "example.txt"

try:
with open(file_path, "r") as file:
# Read the first line
line1 = file.readline()
print(line1)

# Read the next line


line2 = file.readline()
print(line2)

except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except IOError:
print("Error reading the file.")

readlines() Method:
The readlines() method reads all the lines from the file and returns them as a list. Each
element in the list corresponds to a line in the file.
python
file_path = "example.txt"

try:
with open(file_path, "r") as file:
# Read all lines into a list
lines = file.readlines()

# Print each line


for line in lines:
print(line.strip()) # strip() removes newline characters

except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except IOError:
print("Error reading the file.")

8.4.1 Read ()method


Built-in read()or read(n)method is used to read a numbers of bytes of data from a data file.

9
514 514 514
10
515
11

Figure 8.4.1(a): Reading file through read () method

Figure 8.4.1(b): Reading file through read () method with the size parameter

The size parameter is optional. Default -1, which means the whole file.

NOTE: In other words, if we don’t pass any of the arguments or pass a negative number in read
(), then the entire file content is read.

1
515 515 515
11
516
12

8.4.2 Readline() andReadlines() method/Function


Thesebuilt-in methods read a whole line from a file with a newline (\n) character at the end of
each line. It may also be used to read a number (n) of bytes in a file but up to a newline
character (\n).

• We can also find the cursor position from the built-in tell () method as shown in Figure
7.9.1(b)

Figure 8.4.2(a): Reading file through readline () method

• The readlines () method reads and returns all the lines in form of list along with newline
as a list of strings as shown in the figure 8.4.2 (b) as an example to read data from the
text file Test.txt.

Figure 8.4.2(b): Reading file through readlines () method

• We can also use data descriptors line name and closed that can be used as functions but
we don’t pass parenthesis in front of them as shown in figure 7.9.2(c)

Figure 8.4.2(c): Use of data descriptors in file handling

• The built-inseek() function is used to locate a certain location in a file.


o For the beginning of the file, pass 0 value to seek method.
o Current location of the file, pass 0 value to seek method.

516 516 516


12
517
13

o end of file, pass 2 value to seek method.

Figure 8.4.2(d): Use of seek () and tell () method in file handling

8.5 Write Mode in File Handling


First, we open the file in either "write" or "append" mode.

• The file object will be positioned at the beginning of the file if we open the file in write
mode.
• In append mode, new data will be appended to the end of the existing data so the file
object will be positioned at the end of the file.

The write()method accepts a string as a parameter and writes it to the text file. This function
returns the number of characters written when it is called once. Additionally, every phrase
must conclude with a newline character (\n) to signify the end of a line.

Figure 8.5(a): Use of the write()

517 517 517


13
518
14

Figure 8.5(b): Contents of wTest.txtwith the write () method

Q:When working with files, what is the difference between the


tell() and seek() methods in Python?
ANS:

In Python, the tell() and seek() methods are used when working with files to manage the current
position or cursor within the file.

1. tell():

o The tell() method returns the current position of the cursor in the file. It indicates the
byte offset from the beginning of the file where the next read or write operation will
occur.
python
• with open("example.txt", "r") as file:
position = file.tell()
print(f"Current position: {position}")
• The tell() method returns an integer representing the current position in the file.

• seek(offset, whence):

• The seek() method is used to change the position of the cursor within the file. It takes two
arguments: offset (the number of bytes to move) and whence (the reference point for the
offset).
python
2. with open("example.txt", "r") as file:
3. # Move the cursor to the beginning of the file
4. file.seek(0, 0)
5. content = file.read()
6. print(content)
7.
o The offset argument specifies the number of bytes to move, and whence can take one of
three values:

 0 (default): Offset from the beginning of the file.

 1: Offset from the current position.

 2: Offset from the end of the file.

o The seek() method returns the new cursor position after the move.
Here's a quick example demonstrating the use of both methods together:
python
with open("example.txt", "r") as file:
position_before_read = file.tell()
content = file.read(10) # Read the first 10 characters
position_after_read = file.tell()

print(f"Content: {content}")
print(f"Position before read: {position_before_read}")
print(f"Position after read: {position_after_read}")
518 518 518
14
519
15

Q. Explain the use of the writelines() method. When would you


prefer it over the write() method for writing data to a file?

In Python, the writelines() method is used to write a list of lines to a file. Each string in the list
represents a line, and the method writes them to the file without adding any line separators.
Here's an example:
python
# Open a file in write mode
file_path = "example.txt"
lines_to_write = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open(file_path, "w") as file:


# Write multiple lines to the file
file.writelines(lines_to_write)
In this example, the writelines() method is used to write the list lines_to_write to the file. Note
that each string in the list should already include the necessary line separators (e.g., "\n" for newline). If
you want to include line breaks between the lines, you need to add them manually in the strings.

It's important to mention that the writelines() method does not add line breaks automatically, so you
have to include them in the strings if needed. If you want to add line breaks after each line, as in the
example, you need to include \n at the end of each string in the list.
Note:

The writelines() method in Python is typically used when you want to write multiple lines of text to a
file at once. Here are some scenarios where you might prefer writelines() over the write() method:
1. Writing Multiple Lines:
o When you have a list of lines (strings), and you want to write all of them to a file
sequentially. The writelines() method allows you to pass a list of strings, and it writes
each string to the file without adding line breaks.
python
• lines_to_write = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("example.txt", "w") as file:


file.writelines(lines_to_write)
• Avoiding Manual Line Breaks:
• If the lines you want to write already include the necessary line breaks (e.g., "\n" for newline),
you can use writelines() to avoid manually adding line breaks to each string.
python
• lines_to_write = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("example.txt", "w") as file:


file.writelines(lines_to_write)

•519
Efficiency for Large Data Sets: 519 519
15
520
16

• When dealing with a large number of lines or a large amount of data, using writelines() with a
list of lines can be more efficient than calling write() multiple times in a loop.
python
lines_to_write = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("example.txt", "w") as file:


file.writelines(lines_to_write)

Note:
The writelines() method writes the items of a list to the file. Where the texts will be inserted depends
on the file mode and stream position. "a" : The texts will be inserted at the current file stream position,
default at the end of the file.
Ex:
f = open("demofile3.txt", "a")
f.writelines(["See you soon!", "Over and out."])
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

output:

Hello! Welcome to demofile2.txt


This file is for testing purposes.
Good Luck!See you soon!Over and out

Built-in writelines() method used to write multiple lines of string in form of list in the file.

Figure 8.5(c): Use of the writelines ()

Figure 8.5(d): Contents of wTest.txtwith the writelines () method

x-Mode:“x” for exclusive creation. If you open a file in mode x, the file is created and opened
for writing only if it doesn’t already exist. Otherwise you get a FileExistsError.
520 520 520
16
521
17

Figure 8.5(e): Use of the x-mode

8.6 Append Mode in File Handling


Opening a file with "a" mode opens a file for you in append mode, in which pointing cursor at
the end of opened file and further more you may perform write operation to update the
content.

10

521 521 521


17
522
18

Figure 8.6 (a): Contents of aTest.txtbefore applying append ()

Figure 8.6 (b): Use of append () method

Figure 8.6 (c): Contents of aTest.txtafter applying append ()

8.7 Multiple Operationswith File Handling

Now that you know how to make, read, and write files, what if you want to accomplish many
things in the same program? Let's examine what happens, if you try to write to a file that has
been opened in "r" mode (read):

11
522 522 522
18
523
19

Figure 8.7 (a): Error while executing multiple operations at the same time

You will get an error and similarly if you open a file in "w" mode (write), and then try to read it
again you will get an error.To perform multiple operations at the same time, you need to add
the "+" symbol to the mode, like this:

Figure 8.7(b): Syntax for "+" symbol to the mode

Reading file in ‘r+’ mode:

Figure 8.7 (c): Reading file in r+ mode

Reading file in ‘w+’ mode:

Figure 8.7 (d): Reading file in w+ mode

12
523 523 523
19
524
20

Writing file in ‘r+’ mode:

Figure 8.7 (e): Writing file in r+ mode

Writing file in ‘w+’ mode:

Note:

• Opening file in ‘w+’ mode and when the file not exist it creates new empty file.
• Opening file in ‘r+’ modeand when the file not existing It throws exception instead of creating
new file.FileNotFoundError: [Errno 2] No such file or directory.

8.8 Delete a File


To delete a file, you must import the OS module, and run its os.remove(). Deleting a file name
dTest.txt

Figure 8.8 (a): Delete a file

To delete anentire folder, you must import the OS module, and run its os.rmdir(). Deleting a
folder named myfolder.

Figure 8.8 (b): Deleting a folder

13

524 524 524


20
525
21

8.9 Pickle in Python


Pickle is used for serializing and de-serializing Python object structures, also called marshalling
or flattening.

• Serialization refers to the process of converting an object in memory to a byte stream


that can be stored on disk or sent over a network.
• Later on, this character stream can then be retrieved and de-serialized back to a Python
object.
• Pickling is useful for applications
o where you need some degree of persistency in your data.
o Your program's state data can be saved to disk, so you can continue working on
it later on.
o It can also be used to send data over a Transmission Control Protocol (TCP) or
socket connection, or to store python objects in a database.
• You can pickle objects with the following data types: Booleans, Integers, Floats, Complex
numbers, (normal and Unicode) Strings, Tuples, Lists, Sets, and Dictionaries that contain
picklable objects.

8.9.1 Pickling files


To use pickling files

• start by importing it in Python.


• open a file using open() in “wb” mode.
• Once the file is opened for writing, you can use pickle.dump(), which takes two
arguments: the object you want to pickle and the file to which the object has to be
saved.
• In the last close the file with close() function.

For example a user want to pickle age, salary and a dictionary contains their mobile number
and email.

14

525 525 525


21
526
22

Figure 8.9.1 (a): Importing pickle in python

8.9.2 Unpickling files


To use unpickling files

• start by importing it in Python.


• open a file using open() in “rb” mode.
• Once the file is opened for reading, you can use pickle.load(), which takes file from
which the object has to be load
• In the last close the file with close() function.

For example a user want to unpickle age, salary and a dictionary contains their mobile number
and email of previous example

15

526 526 526


22
527
23

Figure 8.9.2 (b): Importing pickle in python

References
• https://www.guru99.com/reading-and-writing-files-in-python.html
• https://www.programiz.com/python-programming/file-operation
• https://www.geeksforgeeks.org/file-handling-python/
• https://www.datacamp.com/community/tutorials/reading-writing-files-python?
• https://realpython.com/working-with-files-in-python/
• https://realpython.com/read-write-files-python/
• https://stackabuse.com/file-handling-in-python
• https://ncert.nic.in/textbook/pdf/lecs102.pdf
• https://www.csestack.org/difference-r-w-python-example/

16

527 527 527


23
528
24

UNIT-4 Class Program


1. f=open("unit.txt","w")

f.write("welcome to file handling")

f.close()

2. f=open("unit.txt","w")

f.write("welcome to file handling/")

n= int(input("how many times"))

for i in range(n):

s=input("enter your roll no=")

f.write(s)

f.close()

output:
how many times3
enter your roll no=120
enter your roll no=126
enter your roll no=156

3. with open("unit.txt", "r") as file:

content = file.read()

print(content)

output:
welcome to file handling/120126156
Files are named locations on disk to store related information. They are used
to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several
functions for
creating, reading, updating, and deleting the files.
In Python, a file handling operation takes place in the following order as:
1. Open a file
2. Read / write perform operation or tasks
3. Close the file at end

4. with open("unit.txt", "r") as file:

528 528 528


24
529
25

for line in file:

print(line.strip())

output:
welcome to file handling/120126156
Files are named locations on disk to store related information. They are used
to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several
functions for
creating, reading, updating, and deleting the files.
In Python, a file handling operation takes place in the following order as:
1. Open a file
2. Read / write perform operation or tasks
3. Close the file at end

5. with open("unit.txt", "r") as file:

partial_content = file.read(10) # Reads the first 10 characters

print(partial_content)

output:
welcome to

6. with open("unit.txt", "r") as file:

file.seek(5) # Move to the 6th character

partial_content = file.read(10) # Read the next 10 characters

print(partial_content)

output:
me to file

7. file_path = "unit.txt"

try:

with open(file_path, "r") as file:

# Read the first line

line1 = file.readline()

print(line1)

529 529 529


25
530
26

# Read the next line

line2 = file.readline()

print(line2)

except FileNotFoundError:

print(f"The file {file_path} does not exist.")

except IOError:

print("Error reading the file.")

output:
welcome to file handling/120126156

Files are named locations on disk to store related information. They are used
to store data

8. file_path = "unit.txt"

try:

with open(file_path, "r") as file:

# Read all lines into a list

lines = file.readlines()

# Print each line

for line in lines:

print(line.strip()) # strip() removes newline characters

except FileNotFoundError:

print(f"The file {file_path} does not exist.")

except IOError:

print("Error reading the file.")

output:
welcome to file handling/120126156

530 530 530


26
531
27

Files are named locations on disk to store related information. They are used
to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several
functions for
creating, reading, updating, and deleting the files.
In Python, a file handling operation takes place in the following order as:
1. Open a file
2. Read / write perform operation or tasks
3. Close the file at end

9. file_path = "unit.txt"

# Use "w" for write mode. If the file doesn't exist, it will be created.

with open(file_path, "w") as file:

# Write content to the file

file.write("Hello, World!\n")

file.write("This is a sample file.\n")

file.write("Python is awesome!\n")

10. # Open a file in write mode

file_path = "unit.txt"

lines_to_write = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open(file_path, "w") as file:

# Write multiple lines to the file

file.writelines(lines_to_write)

11. with open("unit.txt", "r") as file:

position = file.tell()

print(f"Current position: {position}")

print(file.read())

print(file.tell())

output:
Current position: 0

531 531 531


27
532
28

welcome to file handling/120126156


Files are named locations on disk to store related information. They are used
to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several
functions for
creating, reading, updating, and deleting the files.
In Python, a file handling operation takes place in the following order as:
1. Open a file
2. Read / write perform operation or tasks
3. Close the file at endLine 1
Line 2
Line 3

449

12. with open("unit.txt", "r") as file:

position_before_read = file.tell()

content = file.read(3) # Read the first 10 characters

position_after_read = file.tell()

print(f"Content: {content}")

output:
Content:
we

13. with open("unit.txt", "r") as file:

# Move the cursor to the beginning of the file

file.seek(0, 0)

content = file.read()

print(content)

output:
welcome to file handling/120126156
Files are named locations on disk to store related information. They are used
to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several
functions for
creating, reading, updating, and deleting the files.
In Python, a file handling operation takes place in the following order as:
1. Open a file
2. Read / write perform operation or tasks
3. Close the file at endLine 1
Line 2

532 532 532


28
533
29

Line 3

14. f = open("unit.txt", "a")

f.writelines(["See you soon!", "Over and out."])

f.close()

#open and read the file after the appending:

f = open("unit.txt", "r")

print(f.read())

output:
welcome to file handling/120126156
Files are named locations on disk to store related information. They are used
to store data
permanently in a non-volatile memory (e.g., hard disk). Python has several
functions for
creating, reading, updating, and deleting the files.
In Python, a file handling operation takes place in the following order as:
1. Open a file
2. Read / write perform operation or tasks
3. Close the file at endLine 1
Line 2
Line 3
See you soon!Over and out.

15. file1 = open("unit.txt", "r")

print("Output of Readlines after appending")

print(file1.read())

print()

file1.close()

output:
Output of Readlines after appending
This is Delhi
This is Paris
This is LondonToday

533 533 533


29
534
30

ABES ENGINEERING COLLEGE, GHAZIABAD

Unit-4
QUESTION BANK
SUBJECT NAME: PYTHON PROGRAMMING
SUBJECT CODE: BCC-302

Q.No Description CO BL
What are the primary modes in which you can open a file in Python
1 CO4 K2
for reading and writing? Explain each mode briefly.
Explain the difference between text mode ('t') and binary mode ('b')
2 CO4 K2
when opening a file in Python.
What is the purpose of the with statement when working with files in
3 CO4 K2
Python? Provide an example.
What is the purpose of the with statement when working with files in
4 CO4 K2
Python? Provide an example.
What are the common methods for reading a file in Python, and when
5 CO4 K2
would you use each of them (e.g., read(), readline(), readlines())?
How can you iterate through a file line by line in Python without
6 CO4 K2
reading the entire file into memory?
Explain the concept of a file pointer in Python. How can you
manipulate it using the seek() method? When working with files,
7 CO4 K2
what is the difference between the tell() and seek() methods in
Python?
Explain the use of the writelines() method. When would you prefer
8 CO4 K2
it over the write() method for writing data to a file?
Write Python code to read the contents of a text file named "sample.txt"
9 CO4 K3
and print its contents to the console.
Write a Python program to copy the contents of one text file to another text
10 CO4 K3
file.
Create a function that reads a text file and counts the number of words
11 CO4 K3
in it. Test the function with a sample file.
Write a Python program to append a line of text to an existing file
12 CO4 K3
named "output.txt."
Write a function in Python to count and display the total number of
13 CO4 K3
words in a text file
Write a function in Python to read lines from a text file "notes.txt".
14 Your function should find and display the occurrence of the word CO4 K3
"the"
Write a function display_words() in python to read lines from a text
15 file "story.txt", and display those words, which are less than 4 CO4 K3
characters.
16 How to open and close file? Also give the Syntax for same. CO4 K2
17 Differentiate between file modes r+ and w+ with respect to Python. CO4 K2
18 List down the steps involved in processing a large file in Python? CO4 K2

534 534 534


30
535
31

ABES ENGINEERING COLLEGE, GHAZIABAD

When trying to open a file in Python, I get the error CO4 K2


19 “FileNotFoundError: [Errno 2] No such file or directory”. What
could be the cause of this issue?
CO4 K2
20 Which functions allow us to check if we have reached the end of a
file in Python?

535 535 535


31
536
1

Index
UNIT-5
PYTHON : BCC-302

S.NO Topic Page no


1. Notes 2

2. Class Programs 37

3. Important Questions 50

536 536 536


1
537
2

UNIT-5:
UNIT

Load and dump


In Python, load and dump are methods provided by the json module for working with JSON
data. These methods are used to serialize (dump) Python objects into a JSON-formatted string
or deserialize (load) a JSON-formatted string into Python objects.

Here's a brief explanation of how load and dump work along with examples:

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,


allow_nan=True, cls=None, indent=None, separators=None, default=None,
sort_keys=False, **kw)

• Description:

o Serialize a Python object obj to a JSON-formatted string and write it to a file-


like object fp.
• Parameters:

o obj: The Python object to be serialized.

o fp: A file-like object (e.g., a file object opened in write mode) where the JSON
data will be written.
o Other optional parameters allow customization of the serialization process, such
as indentation, sorting keys, etc.

• Example:
python
• import json

• # Python dictionary to be serialized
• data = {"name": "John", "age": 30, "city": "New York"}

• # Open a file in write mode and serialize the dictionary to JSON
• with open("example.json", "w") as file:
• json.dump(data, file, indent=2)
• In this example, the Python dictionary data is serialized to a JSON-formatted string and
written to the file "example.json" with an indentation of 2 spaces.

json.load(fp, *, cls=None, object_hook=None, parse_float=None,


parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

• Description:

o Deserialize a JSON-formatted string from a file-like object fp and return the


corresponding Python object.

• Parameters:

o fp:A file-like object (e.g., a file object opened in read mode) containing the
JSON-formatted string.
537 537 537
2
538
3

o Other optional parameters allow customization of the deserialization process,


such as custom decoding functions.

• Example:
python
import json

# Open a file in read mode and deserialize the JSON data


with open("example.json", "r") as file:
loaded_data = json.load(file)

# Print the loaded data


print(loaded_data)

picking, seralization ans


deserialization of python object

In Python, "picking" typically refers to the process of serializing (pickling) and deserializing
(unpickling) objects, which is a way of converting Python objects into a byte stream
(serialization) and reconstructing them from a byte stream (deserialization). This process is
commonly used for storing or transmitting objects between different Python programs or across
different platforms.

Serialization (Pickling):
Serialization is the process of converting a Python object into a byte stream, usually in a format
that can be easily stored or transmitted. The pickle module is commonly used for this purpose.
python
import pickle

# Python object to be serialized (pickled)


data = {"name": "John", "age": 30, "city": "New York"}

# Serialize (pickle) the object


serialized_data = pickle.dumps(data)

# Save the serialized data to a file


with open("serialized_data.pkl", "wb") as file:
file.write(serialized_data)
In this example:

• The pickle.dumps() function serializes the Python object (data) into a byte stream
(serialized_data).

• The serialized data is then saved to a file using the write() method.

Deserialization (Unpickling):
Deserialization is the process of reconstructing a Python object from a byte stream. The pickle
module is also used for unpickling.
python
import pickle

#538
Read serialized data from a file 538 538
3
539
4

with open("serialized_data.pkl", "rb") as file:


serialized_data = file.read()

# Deserialize (unpickle) the data


loaded_data = pickle.loads(serialized_data)

# Print the loaded data


print(loaded_data)

1. Simple programs using the built-in functions of


packages
Matplotlib
Matplotlib is a comprehensive and widely used 2D plotting library for Python. It
provides a flexible and high-quality way of creating static, animated, and interactive
visualizations in Python. Matplotlib is particularly useful for creating a variety of charts,
plots, and graphs, making it a valuable tool for data visualization and analysis.
Here are some key aspects of Matplotlib:
Ex:
import matplotlib.pyplot as plt

# Create a simple line plot


x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()

Customization: Matplotlib provides extensive customization options to control the appearance


of plots. You can customize colors, line styles, markers, labels, titles, and more.
python
# Customizing a plot
plt.plot(x, y, color='red', linestyle='--', marker='o', label='Data Points')
plt.legend()

Subplots: You can create multiple subplots within the same figure using the subplot()
function. This is useful for displaying multiple plots in a single visualization.
python
# Creating subplots
plt.subplot(2,
539 1, 1) # 2 rows, 1 column,
539 plot 1 539
4
plt.plot(x, y)
540
5

plt.subplot(2, 1, 2) # 2 rows, 1 column, plot 2


plt.scatter(x, y)

Saving and Exporting: You can save your plots in different formats, such as PNG, PDF, or
SVG, using the savefig() function.
python
# Saving a plot
plt.savefig('my_plot.png')

NumPy:
NumPy, short for Numerical Python, is a powerful library in Python for numerical and
mathematical operations. It provides support for large, multi-dimensional arrays and matrices,
along with a collection of high-level mathematical functions to operate on these arrays. NumPy
is a fundamental package for scientific computing in Python and serves as the foundation for
many other libraries in the Python data science ecosystem.
Here are some key features and aspects of NumPy:

1. Arrays: The core data structure in NumPy is the numpy.ndarray, commonly known as
an array. Arrays are similar to lists in Python but offer more functionality and are
optimized for numerical operations. NumPy arrays can be one-dimensional, two-
dimensional, or multi-dimensional.
python
• import numpy as np

# Creating a NumPy array


arr1d = np.array([1, 2, 3, 4, 5])
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
• Operations on Arrays: NumPy provides a wide range of mathematical operations that can
be performed on arrays element-wise, such as addition, subtraction, multiplication, division,
exponentiation, and more.
python
• # Example of array operations
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

result = arr1 + arr2


print(result) # Output: [5 7 9]
• Broadcasting: NumPy supports broadcasting, a powerful feature that allows operations on
arrays of different shapes and sizes. Broadcasting simplifies code and eliminates the need for
explicit looping constructs.
python
• # Broadcasting example
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 2

result = arr * scalar


print(result)
# Output:
# [[2 4 6]
# [8 10 12]]

540 540 540


5
541
6

• Universal Functions (ufuncs): NumPy provides a set of universal functions that operate
element-wise on arrays. These functions are optimized for performance and can be applied to
entire arrays without the need for explicit looping.

python
• # Example of ufuncs
arr = np.array([1, 2, 3, 4, 5])

square_root = np.sqrt(arr)
print(square_root) # Output: [1. 1.414 1.732 2. 2.236]
• Linear Algebra Operations: NumPy includes a variety of linear algebra operations, such as
matrix multiplication (np.dot()), eigenvalue decomposition, singular value decomposition,
and more.
python
• # Example of matrix multiplication
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

result = np.dot(matrix1, matrix2)


print(result)
# Output:
# [[19 22]
# [43 50]]
• Random Number Generation: NumPy provides functions for generating random numbers
and random samples, which is useful for various applications, including simulations and
statistical analysis.
python
6. # Example of random number generation
7. random_numbers = np.random.rand(3, 3) # Generates a 3x3 array of
random numbers
8.
NumPy is a fundamental library in the Python scientific computing ecosystem and is widely
used in fields such as machine learning, data analysis, physics, engineering, and more. Its
efficient array operations and mathematical functions make it a key tool for numerical
computing tasks.
NOTE:
Q: explain the advantages of using NumPy for matrix operations. ?
ANS:
NumPy (Numerical Python) is a powerful library in Python for performing numerical and
matrix operations. Here are some advantages of using NumPy for matrix operations:

1. Efficient Array Operations: NumPy provides an array data type that allows for
efficient storage and manipulation of large, multi-dimensional arrays. The underlying
implementation of NumPy arrays is written in C and Fortran, which makes it faster than
using native Python lists for numerical operations.
2. Vectorized Operations: NumPy supports vectorized operations, which means you can
perform operations on entire arrays or matrices at once, without the need for explicit
looping. This leads to concise and more readable code, as well as improved
performance.

541 541 541


6
542
7

3. Broadcasting: NumPy allows for broadcasting, which is a powerful mechanism for


performing operations on arrays of different shapes and sizes. Broadcasting implicitly
expands smaller arrays to match the shape of larger arrays, making it easier to perform
element-wise operations on arrays of different sizes.
4. Memory Efficiency: NumPy arrays are more memory-efficient compared to Python
lists. NumPy uses a contiguous block of memory for its arrays, which reduces overhead
and allows for efficient storage and manipulation of large datasets.

5. Optimized Linear Algebra Operations: NumPy provides a comprehensive set of


functions for linear algebra operations, such as matrix multiplication (np.dot or @
operator), eigenvalue decomposition, singular value decomposition, and more. These
functions are implemented using highly optimized, low-level code, often leveraging
specialized libraries like BLAS (Basic Linear Algebra Subprograms) and LAPACK
(Linear Algebra PACKage).
Q: Describe the purpose of broadcasting in NumPy and provide an example where it is useful.
ANS:
Broadcasting is a powerful feature in NumPy that allows for performing operations on arrays of
different shapes and sizes, without the need for explicitly reshaping or duplicating the data.
Broadcasting makes it possible to write concise and readable code when working with arrays of
varying dimensions, and it often leads to improved performance by avoiding unnecessary
memory duplication.

The broadcasting rules in NumPy allow arrays with different shapes to be combined element-
wise, provided that their dimensions are compatible. The dimensions are considered compatible
when they are either equal or one of them is 1. NumPy then automatically broadcasts the
smaller array to match the shape of the larger one.
Here's a simple example to illustrate the concept of broadcasting:
python
import numpy as np

# Create a 3x3 matrix


matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Define a one-dimensional array


row_vector = np.array([10, 20, 30])

# Add the row_vector to each row of the matrix using broadcasting


result = matrix + row_vector

print(result)
In this example, the row_vector has a shape of (3,), and the matrix has a shape of (3, 3).
According to NumPy's broadcasting rules, the dimensions are compatible because one of them
is 1. As a result, NumPy automatically broadcasts the row_vector to match the shape of the
matrix, effectively adding the corresponding elements element-wise:
lua
[[11 22 33]
[14 25 36]
[17 28 39]]
542 542 542
7
543
8

Without broadcasting, you would need to explicitly reshape or tile the row_vector to match the
shape of the matrix. Broadcasting simplifies the syntax and improves code readability.
Broadcasting is particularly useful in scenarios such as:
1. Element-wise Operations: Perform element-wise operations on arrays of different
shapes without explicitly looping through elements.
2. Efficient Memory Usage: Avoid unnecessary memory duplication by broadcasting
smaller arrays, leading to more memory-efficient code.
3. Simplifying Code: Write more concise and readable code when working with arrays of
varying dimensions, reducing the need for explicit reshaping.

Broadcasting is a key feature in NumPy that enhances its flexibility and usability when working
with arrays, making it a powerful tool for scientific computing and data manipulation.

Pandas:
Pandas is a powerful open-source data manipulation and analysis library for Python. It provides
data structures for efficiently handling large datasets and offers a wide range of functions for
data cleaning, exploration, and analysis. Pandas is widely used in data science, machine
learning, and other domains where working with structured data is essential.
Here are some key features and aspects of Pandas:

1. Data Structures: Pandas introduces two main data structures: Series and DataFrame.
o Series: A one-dimensional array-like object that can hold any data type. It is
similar to a column in a spreadsheet or a single variable in statistics.
python
• import pandas as pd

# Creating a Pandas Series


s = pd.Series([1, 3, 5, np.nan, 6, 8])
• DataFrame: A two-dimensional table with rows and columns, similar to a spreadsheet or a
SQL table. It is a primary data structure for most Pandas operations.
python
• •
• # Creating a Pandas DataFrame
• df = pd.DataFrame({
• 'Name': ['Alice', 'Bob', 'Charlie'],
• 'Age': [25, 30, 35],
• 'City': ['New York', 'San Francisco', 'Los Angeles']
• })
• Data Cleaning and Preparation: Pandas provides a plethora of functions for cleaning and
preparing data, including handling missing values, removing duplicates, filtering, and
transforming data.
python
• # Example of handling missing values
df.dropna() # Removes rows with missing values
543 543 543
8
544
9

• Indexing and Selection: Pandas allows for flexible indexing and selection of data based on
labels or conditions. This includes the ability to use column names, row indices, and boolean
conditions for filtering data.
python
• # Example of indexing and selection
df['Name'] # Selects the 'Name' column
df[df['Age'] > 30] # Selects rows where 'Age' is greater than 30
• Grouping and Aggregation: Pandas supports grouping data based on one or more keys,
enabling the application of aggregate functions to each group. This is particularly useful for
performing summary statistics on grouped data.
python
• # Example of grouping and aggregation
df.groupby('City')['Age'].mean() # Computes the mean age for each city
• Merging and Joining: Pandas provides functions for combining datasets through merging
and joining operations, similar to SQL. This is useful when working with multiple datasets that
share common keys.
python
• # Example of merging DataFrames
df1 = pd.DataFrame({'key': ['A', 'B'], 'value': [1, 2]})
df2 = pd.DataFrame({'key': ['B', 'C'], 'value': [3, 4]})

pd.merge(df1, df2, on='key') # Merges based on the 'key' column


• Time Series Analysis: Pandas has robust support for working with time series data,
including functionalities for date and time indexing, resampling, and moving window statistics.
python
6. # Example of time series analysis
7. date_rng = pd.date_range(start='2022-01-01', end='2022-01-10',
freq='D')
8. time_series = pd.Series(np.random.randn(len(date_rng)),
index=date_rng)
9.
Pandas is an essential tool for data analysis and manipulation in Python. It simplifies many
common data-related tasks, making it easier for users to handle, analyze, and visualize
structured data efficiently. It is often used in conjunction with other libraries such as NumPy,
Matplotlib, and scikit-learn for comprehensive data analysis and machine learning workflows.

Q: Write a Python program that reads data from an Excel spreadsheet using Pandas, performs
data analysis, and generates a new Excel file with the results.?
ANS:
import pandas as pd

# Read data from Excel file


input_file = "input_data.xlsx"
output_file = "output_results.xlsx"

# Change sheet_name and usecols as needed based on your Excel file structure
df = pd.read_excel(input_file, sheet_name="Sheet1", usecols=["Column1", "Column2"])

# Perform data analysis (calculate mean and standard deviation)


mean_values = df.mean()
std_dev_values = df.std()
544 544 544
9
545
10

# Create a new DataFrame with the analysis results


analysis_results = pd.DataFrame({
"Mean": mean_values,
"Standard Deviation": std_dev_values
})

# Display the analysis results


print("Analysis Results:")
print(analysis_results)

# Save the analysis results to a new Excel file


analysis_results.to_excel(output_file, index_label="Column")

print(f"\nAnalysis results saved to '{output_file}'.")

Q:Load a CSV file into a Pandas DataFrame and display basic


statistics (mean, median, std) for a specific column. Explain the
concept of merging and joining in Pandas with suitable examples.
ANS:
Sure, let's start by loading a CSV file into a Pandas DataFrame and displaying basic statistics
for a specific column. For this example, I'll assume you have a CSV file named "data.csv" with
columns "Name," "Age," and "Salary." We will calculate basic statistics for the "Salary"
column.
python
import pandas as pd

# Load CSV file into a Pandas DataFrame


file_path = "data.csv"
df = pd.read_csv(file_path)

# Display basic statistics for the "Salary" column


salary_statistics = df["Salary"].describe()

print("Salary Column Statistics:")


print(salary_statistics)
Now, let's move on to explaining the concepts of merging and joining in Pandas.

Merging and Joining in Pandas:


Merging: Merging in Pandas is the process of combining two DataFrames based on a common
key or column. The pd.merge() function is used for merging. Here's a simple example:
python
# Create two DataFrames
df1 = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']})
df2 = pd.DataFrame({'ID': [2, 3, 4], 'Salary': [50000, 60000, 70000]})

# Merge DataFrames based on the 'ID' column


merged_df = pd.merge(df1, df2, on='ID')

print("Merged DataFrame:")
545
print(merged_df) 545 545
10
546
11

This would produce a DataFrame where the two original DataFrames are merged based on the
common 'ID' column.
Joining: Joining is a convenient method in Pandas for combining two DataFrames based on
their index. The pd.DataFrame.join() method is used for joining. Here's an example:
python
# Create two DataFrames with a common index
df1 = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie']}, index=[1, 2, 3])
df2 = pd.DataFrame({'Salary': [50000, 60000, 70000]}, index=[2, 3, 4])

# Join DataFrames based on the index


joined_df = df1.join(df2, how='inner')

print("Joined DataFrame:")
print(joined_df)
This would produce a DataFrame where the two original DataFrames are joined based on their
indices.
In both examples, you can customize the merging and joining behavior using parameters like
how, on, left_on, right_on, and others. The choice between merging and joining depends on
the specific requirements of your data integration

2. GUI Programming
A GUI or a graphical user interface is an interactive environment to take responses from users
on various situations such as forms, documents, tests, etc. Python provides multiple options
for developing graphical user interfaces (GUIs).
Most important are listed below.
• Tkinter
• PyQT5
• PySide 2
• Kivy
• wxPython etc.

In this chapter, we will discuss Tkinter. Figure 8.1 shows the three components of GUI
programming:

546 546 546


11
547
12

Figure 8.1 Components of GUI

8.2 Introduction to Tkinter

Tkinter is one of the most popular Python GUI libraries for developing desktop applications.
Tkinter provides diverse widgets such as labels, buttons, text boxes, checkboxes, etc., that
are used in a graphical user interface application.

Tkinter gives us the following component to create a GUI application.

• A main window or container - this is what will be drawn on the screen for the user to
use.
• A widget such as a label, entry, button, frame, etc.
• A Geometry manager – To place a widget in the window, Tkinter has particular
function called geometry managers. Like pack, gride, and place. We will discuss each
in detail.

547 547 547


12
548
13

8.2.1 Importing Tkinter Module

Tkinter module is part of the standard library. To use tkinter, import the tkinter module
using the below-given code(Figure-8.2.1).

Figure-8.2.1 import tkinter module

8.2.2 Creating window

Tkinter's Tk class instance creates a window. In the below code, we created an object of Tk()
and named it window. Tk() method creates a blank window with close, maximize and
minimize buttons as shown in figure 8.2.2, and the mainloop() method is used to display the
window until you manually close it.

Output -

Figure 8.2.2 Creating Blank Window

8.3 Basic Attributes of tkinter Window

8.3.1 Set Title and Background of Window

We used the title() method for setting the title and used the configure() method for
background color.

548 548 548


13
549
14

Syntax – To set Title window.title(string)


To set Background window.configure(background=color)

Note - We can use either standard color ( black, red, white, etc.) or hexadecimal digits
representing RGB.

Example – Create a Blank Window and set background color red, title as "My first GUI
Application” as shown in figure 8.3.1.

Figure 8.3.1 Set Title and Background of window

8.3.2 Resize the window

geometry() method is used to resize the window. We have to provide the dimension (width
X height (in px)) of the window as a string, as shown in Figure 8.3.2.

Figure 8.3.2 Resize the window

549 549 549


14
550
15

8.3.3 Resizing behavior

By default, we can resize a window when it displays through mouse selection. To prevent
the window from resizing, we can use the resizable () method. resizable() method takes two
parameters (width, height). If you want to disable width and height, then pass True/False,
respectively.

Example – Change the resizing behavior of the tkinter window .

Output -

Figure 8.3.3 Resizable window

8.3.4 Changing the default icon at Title Bar

To change the default icon at the top of the window, we used iconbitmap() method of the
window object. It only takes. ioc file. The example is shown in Figure 8.3.4

550 550 550


15
551
16

Output-

Figure 8.3.4 Changing the default icon at Title Bar

8.4 Widgets

Tkinter provides various controls, such as labels, text boxes, radio buttons, submit buttons,
etc., used in a GUI application. These controls are commonly called widgets.

8.4.1 Label Widgets

A Label is used to display text or an image. The label is a widget that the user just views but
does not interact with.

Syntax - l = Label (master, option, ...)

master – This represents the window object; means in which window you want to add.
option – Entry widgets have the following option
• text - To display one or more lines of text in a label widget
• fg – To set Text Color
• bg – To set the background color of the text
• font – To set font style, size, bold, italic.
• image – Image as a label
• Reference for more options - https://tkdocs.com/shipman/label.html

Example – Create two labels with the text "This is my first Label" and "This is Second Label"
and place them in the window object. The code is given in figure 8.4.1(a). label () is used to

551 551 551


16
552
17

create a Label. For example pack() method is used to place the widget in the window. Details
about pack() will be discussed in section 8.5 (Layout Management ). At this point, only
remember that every widget must be added to the window object using the layout
management method ( pack(), grid(), place).

Output-

Figure 8.4.1(a) Label Widgets

Example –2 To display label having text in "yellow", background in "dark green", font style
in "Helvetica", size 16.

Output-

Figure 8.4.1(b) Example 2

Using Images in Labels -

To add an image to the label, we have to create a name for the image using the PhotoImage()
method. PhotoImage() - Create an image with NAME and display pictures in PGM, PPM, GIF,
PNG format. If you want to use another format's image, then use the pillow package.
An example of the image inside the label is shown in figure 8.4.2( c).

552 552 552


17
553
18

Output -

Figure 8.4.1(c) Image in the label

8.4.2 Entry Widgets


Entry widgets are the basic widgets of Tkinter used to get input, i.e., text strings, from an
application user. This widget allows the user to enter a single line of text.

Syntax - e = Entry (master, option, ... )

master – This represents the window


option – Entry widgets have the following option
• bg - To set the Background color of textbox
• font - To set font style used for the text.
• fg - The color used to render the text.
• show - Normally, the characters that the user types appear in the entry. To make a
password entry that echoes each character like an asterisk, set show = "*".
• textvariable - To be able to retrieve the current text from your entry widget.
• Reference for more options - https://tkdocs.com/shipman/entry.html

Example – 1 Create a window having one label and a Textbox (Entry widget)

553 553 553


18
554
19

Output -

Figure 8.4.2 (a)Entry Widgets

Figure 8.4.2(a) show the code and output of a window having one label and a Textbox.

Example –2 Create a window with one label and a Textbox where enter text color will be
red.

Output -

Figure 8.4.2(b) Example of Entry widget with text color red

Figure 8.4.2(b) show the code and output of a window having one label and a Textbox
where when user enter any text then text will be displayed in red color.

554 554 554


19
555
20

8.4.3 Buttons Widgets

The Button widget is used to add buttons in a Python application.

Syntax - b = Button (master, option = value, ... )

master – This represents the window


option – Buttons widgets have the following option
• text – To set the text of Button
• bg - To set the Background color
• fg – To set Text-color of Button
• height - Height of the button in text lines
• image - Image to be displayed on the button
• justify - To show multiple text lines: LEFT to left-justify each line; CENTER to center
them; or RIGHT to right-justify.
• Reference for more options - https://tkdocs.com/shipman/button.html

Example – Create a window having two buttons as shown in Figure 8.4.3 Output

Output -

Figure 8.4.3 Example of Buttons Widgets

8.4.4 Checkbutton Widgets

The Checkbutton widget is used to display several options to a user as toggle buttons.

Syntax – c = Checkbutton(master, option, ...)

master – This represents the window

555 555 555


20
556
21

option – Checkbutton widgets have the following option


• bg - To set Background color
• fg – To set the Text color of Button
• selectcolor – To set checkbutton color.
• text - The label is displayed next to the checkbutton.
• offvalue - Normally, a checkbutton's associated control variable will be set to 0 when
it is cleared (off). You can supply an alternate value for the off-state by setting off value
to that value.
• onvalue - Normally, a checkbutton's associated control variable will be set to 1 when
set (on). You can supply an alternate value for on the state by setting on value to that
value.
• Reference for more options - https://tkdocs.com/shipman/checkbutton.html

Example – Create a window and place three checkbutton as shown in figure 8.4.4

Output -

Figure 8.4.4 Example of Checkbutton Widgets

8.4.5 Radiobutton Widgets

This widget implements a multiple-choice button. Only one radio button in a group can be
selected at a time.

Syntax - r = Radiobutton (master, option, ... )

master – This represents the window


option – radiobutton widgets have the following option
• bg - To set the Background color

556 556 556


21
557
22

• fg – To set Text-color of Button


• text - The label is displayed next to the rediobutton.
• value - When the user turns on a radiobutton, its control variable is set to its current
value option.
• Reference for more options - https://tkdocs.com/shipman/radiobutton.html

Example – Create a window having two radio button, one label with male and second with
Female as shown in figure 8.4.5

Output -

Figure 8.4.5 Example of Radiobutton Widgets

8.4.6 Frame Widgets

A frame is just a container for other widgets. It is used for grouping and organizing other
widgets in a somehow friendly way.

Syntax - f = Frame ( master, option, ... )

master – This represents the window


option – frame widgets have the following option
• bd or border-width – It is used for border width
• bg or background – Set background-color
• height – To set the height of the frame
• width – Set width if the frame
• Reference for more options - https://tkdocs.com/shipman/frame.html

Example - Create Two frames and pack them left side and right side. Add two buttons on
each frame as shown in figure 8.4.6.

557 557 557


22
558
23

Output -

Figure 8.4.6 Example of Frame Widgets

8.4.7 MessageBox Widgets

MessageBox() module is used to display message boxes in your applications.

Syntax - messagebox.FunctionName(title, message [, options])

FunctionName − Name of the appropriate message box function. Figure 8.4.7(a) shows
different types of function used for the message box.

558 558 558


23
559
24

Figure 8.4.7(a) Different type of message box and its function name

title − Text to be displayed in the title bar of a message box.


message − This is the text to be displayed as a message.

Example - Create a Button and call a function name show_msg() which displays a message
using messageBox.

Figure 8.4.7(b) Example of MessageBox


We call function show_msg() using command option in Button widgets as shown in Figure
8.4.7(b).

559 559 559


24
560
25

8.5 Layout Management / Geometry Management

The purpose of Geometry Management is to organize widgets in the parent area. Tkinter
possesses three layout managers:
• pack()
• grid()
• place()
Note - Never mixed all three layout managers in the same window.

8.5.1 Pack () - It packs the widget in rows or columns.

Syntax - widget.pack( pack_options )

Following are pack_option -


• side − Determines which side of the parent widget packs against TOP (default),
BOTTOM, LEFT, or RIGHT.
• fill – It is used to make the widgets as wide as the parent widget; you have to use the
fill=X

Example 1 – Create four buttons and pack them left, right, top, and bottom side.

Output -

Figure 8.5.1(a) Example of pack() layout manager with a side option

As shown in Figure 8.5.1(a), to pack button widgets we used pack() method and set value of
side with “LEFT”, “RIGHT”, “TOP”, “BOTTOM”.

560 560 560


25
561
26

Example 2 – Create Two buttons, pack the first button using fill=X and second as default.

Output -

Figure 8.5.1(b) Example of the pack() layout manager and fill=X option

Fill=X, in pack() method set button widgets as wide as the parent widget as shown in Figure
8.5.1(b).

8.5.2 grid()

This geometry manager organizes widgets in a table-like structure (Figure 8.5.2(a)) in the
parent widget.

Figure 8.5.2(a) table-like structure

561 561 561


26
562
27

Syntax - widget.grid( grid_options )

grid_options -
• column - The column number where you want the widget gridded, counting from
zero. The default value is zero.
• columnspan - Defines the number of columns a cell should span.
• row - The row number into which you want to insert the widget, counting from 0.
• rowspan - rowspan specifies the number of rows a cell should span.
• For more option - https://tkdocs.com/shipman/grid.html

Example – Create a grid of 3X3 having nine buttons.

Output -

Figure 8.5.2(b) Example of grid layout manager

To create a grid of 3X3, we set row and column option in grid method as shown in Figure
8.5.2(b).

8.5.3 place

This geometry manager organizes widgets by placing them in a specific position in the
parent widget.

562 562 562


27
563
28

Syntax - widget.place( place_options )

place_options -
• height, width − Height and width in pixels.
• anchor − The exact spot of widget other options refers to: maybe N, E, S, W, NE, NW,
SE, or SW.
• x, y − Horizontal and vertical coordinate in pixels. In the window at topmost corner
coordinate is (0,0).

Example – Given the below code, place two buttons at a different coordinate.

Output -

Figure 8.5.3 Example of place layout manager

To place widgets at different coordinates we set value of x (for x coordinate) and y (for y
coordinate) in place() method as shown in Figure 8.5.3.

8.6 Tkinter Variables

To manipulate the values of widgets, Tkinter have following variables class


• Variable1 = StringVar() - It holds a string. Default value “”
• Variable2 = IntVar() - It holds an integer. Default value 0
• Variable3 = DoubleVar() - It holds float. Default value 0.0
• Variable4 = BooleanVar() - It holds boolean i.e. 0/1.

Methods – it has two methods to set or get value to/from the widget.

set () - Used to set variable value


get() - Used to get value from variable

563 563 563


28
564
29

8.7 Tkinter command binding

Widgets are essential to make an application interactive. Widgets respond to the events by:
• Mouse clicks
• Key presses

Widgets require assigning a callback function to a specific event. When the event occurs, the
callback will be invoked automatically to handle the event. In Tkinter, some widgets allow you
to associate a callback function with an event using the command binding.

To use command binding, we first define a function as a callback and then assign the
function's name to the command option of the widgets.

To understand command binding, let's take an example.

Example – Create a login page and display a message through messages box if user_name=
admin and password = admin; otherwise, display Wrong username and password as shown
in Figure 8.7(b).

In the figure8.7(a), we created a function check () which display message using message box
on given condition. To call check () function when button will press, we use < command =
name_of_function > option.

Figure 8.7(a) Example to call a function when button press

564 564 564


29
565
30

Figure 8.7(b) Output of figure 8.7(a) code

8.8 Passing Arguments to command in tkinter Button

We can pass the parameter to the callback function using the lambda operator when the
Button is clicked. The figure8.8 below shows the code.

Output -

Figure 8.8: Passing Arguments to command in tkinter Button

565 565 565


30
566
31

8.9 Demo of Basic Calculator App

The development of the Basic Calculator app will be divided into two parts.

1. GUI
2. Callback Function to act on pressing Button.

8.9.1. GUI Code - The code of Simple Calculator is shown in Figure 8.9(a). In this we create 15
Buttons for digits (0-9), operator (+, -, *, /, =) and one entry box for displaying calculation.

Output -

Figure 8.9(a) GUI of Basic Calculator app

566 566 566


31
567
32

8.9.2 Complete Basic code with Call-back Function to act on pressing Button on calculator -
This calculator will evaluate any expression written as a sequence of operand and operator.
In this we create two function digit() and equal(). digit() function is used to concatenate all
pressed button's text into a string name "var." The complete code is shown in figure 8.9(b).

Output -

Figure 8.9(b) Complete Code of Basic Calculator

567 567 567


32
568
33

8.10 Tkinter and Database(MySQL)

8.10.1 Installation of mysql-connector-python package

Python needs a MySQL driver to access the MySQL database. So first, we install the mysql-
connector-python package using the below command

pip install mysql-connector-python

8.10.2 Database Connection

There are the following steps to connect a python application to our database.
• Import mysql.connector module
• Create the connection object
• Create the cursor object
• Execute the SQL query

Import mysql.connector module - To import the module, we used the below code.

import mysql.connector as mysql

Create the connection object – To create a connection with MySQL database, we used
connect() method of mysql.connector module.

Syntax - db = mysql.connect(host =" ",user = "", password="",db ="")

host – address of MySQL server


user - user name to access the database if given; otherwise, leave it blank
Password – Password to access the database if provided otherwise, leave it blank
db – Database name

Create the cursor object - The cursor object is used to execute SQL queries to the
database.

Syntax - my_cursor = db.cursor()

Execute the query - To execute SQL queries, execute() method of the cursor object is used.

Syntax - my_cursor.execute(“your sql query as string”)

fetchall() – We use the fetchall() method, fetched all rows from the last executed
statement.
Syntax – myresult = my_cursor.fetchall()

568 568 568


33
569
34

Example – Create a login form and connect to a database to check username and
password with MySql Database.

Figure 8.10(a) Login Page with Database Connectivity

In example Figure 8.10(a), we create a database "test," and in the "test" database, we created
a table "users". In table users, there are two fields (username, password). Figure 8.10(b)
shows the phpMyAdmin page.

569 569 569


34
570
35

Figure 8.10(b) phpMyAdmin page

Event-Driven Programming in Tkinter:


1. Event Loop:
o Tkinter operates using an event loop. The program continuously waits for
events to occur, such as button clicks, keypresses, or mouse movements.
o When an event occurs, Tkinter triggers the associated event handler, which is
a function or method specified by the programmer.

2. Widgets and Bindings:


o Tkinter applications are built using widgets (GUI elements like buttons,
labels, and entry fields).
o Events are associated with specific widgets, and bindings are used to connect
events to corresponding event handlers.

3. Event Handling:
o Event handlers (functions or methods) are defined to respond to specific
events. For example, a button click might trigger a function that performs a
certain action.
o Handlers are typically associated with widgets during the application's setup.

4. Asynchronous Execution:
o Tkinter applications operate asynchronously. The program doesn't follow a
linear flow; instead, it responds to events as they occur.
o Users can interact with the GUI while the program continues to wait for
events and execute the associated handlers.

Differences from Traditional Procedural Programming:


1. Control Flow:
570 570 570
35
571
36

o In traditional procedural programming, the flow of control is typically linear.


The program executes statements sequentially, one after another.
o In event-driven programming, control flow is driven by events. The program
waits for events to occur and responds to them, allowing for non-linear
execution.

2. User Interaction:
o In procedural programming, user interactions are often handled by calling
functions or methods based on user input at specific points in the code.
o In event-driven programming, user interactions are central. The program
reacts to events triggered by user actions, such as button clicks or keypresses.

3. Blocking vs. Non-Blocking:


o Procedural programming may involve blocking operations where the program
waits for a task to complete before moving on to the next one.
o Event-driven programming is typically non-blocking. The program can
continue executing other tasks while waiting for events, allowing for a more
responsive user interface.

4. GUI Development:
o In procedural programming, GUI development might involve creating static
interfaces with limited user interaction.
o Event-driven programming, especially in GUI frameworks like Tkinter,
focuses on dynamic interfaces where the user's actions trigger events and
drive the application's behavior.

5. State Management:
o Procedural programs often rely on maintaining explicit states and managing
transitions between states.
o Event-driven programming can have implicit states driven by user interactions. The
program responds to events without explicit state management in many cas

571 571 571


36
572
37

Class Programs:
1.

import matplotlib.pyplot as plt

# Create a simple line plot

x = [1, 2, 3, 4, 5]

y = [2, 4, 6, 8, 10]

plt.plot(x, y)

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.title('Simple Line Plot')

plt.show()

2: plt.plot(x, y, color='red', linestyle='--', marker='o', label='Data Points')

plt.legend()

3:

plt.subplot(2, 1, 1) # 2 rows, 1 column, plot 1

plt.plot(x, y)

plt.subplot(2, 1, 2) # 2 rows, 1 column, plot 2

plt.scatter(x, y)

4:

import numpy as np

# Creating a NumPy array

572 572 572


37
573
38

arr1d = np.array([1, 2, 3, 4, 5])

arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

5:

# Example of array operations

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result = arr1 + arr2

print(result) # Output: [5 7 9]

6:

# Broadcasting example

arr = np.array([[1, 2, 3], [4, 5, 6]])

scalar = 2

result = arr * scalar

print(result)

# Output:

# [[2 4 6]

# [8 10 12]]

7:

# Example of ufuncs

arr = np.array([1, 2, 3, 4, 5])

square_root = np.sqrt(arr)

print(square_root) # Output: [1. 1.414 1.732 2. 2.236]

8:

573 573 573


38
574
39

# Example of matrix multiplication

matrix1 = np.array([[1, 2], [3, 4]])

matrix2 = np.array([[5, 6], [7, 8]])

result = np.dot(matrix1, matrix2)

print(result)

# Output:

# [[19 22]

# [43 50]]

9:

import pandas as pd

# Creating a Pandas Series

s = pd.Series([1, 3, 5, np.nan, 6, 8])

10:

# Creating a Pandas DataFrame

df = pd.DataFrame({

'Name': ['Alice', 'Bob', 'Charlie'],

'Age': [25, 30, 35],

'City': ['New York', 'San Francisco', 'Los Angeles']

})

11:

# Example of handling missing values

df.dropna() # Removes rows with missing values

13:

574 574 574


39
575
40

# Example of indexing and selection

df['Name'] # Selects the 'Name' column

df[df['Age'] > 30] # Selects rows where 'Age' is greater than 30

14:

# Example of grouping and aggregation

df.groupby('City')['Age'].mean() # Computes the mean age for each city

15:

# Example of merging DataFrames

df1 = pd.DataFrame({'key': ['A', 'B'], 'value': [1, 2]})

df2 = pd.DataFrame({'key': ['B', 'C'], 'value': [3, 4]})

pd.merge(df1, df2, on='key') # Merges based on the 'key' column

16:

#Write a Python program to create a line plot using matplotlib

#that displays the population growth of a city over 10 years

import matplotlib.pyplot as plt

# Years and corresponding population data

years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]

population = [500000, 520000, 540000, 560000, 580000, 600000, 620000, 640000, 660000, 680000]

# Create a line plot

plt.plot(years, population, marker='o', linestyle='-', color='b', label='Population Growth')

# Adding labels and title

plt.xlabel('Year')

575 575 575


40
576
41

plt.ylabel('Population')

plt.title('City Population Growth Over 10 Years')

# Display a legend

plt.legend()

# Display the plot

plt.show()

17:

#Create a NumPy array with random integers and write a function to find

#the mean, median, and standard deviation of the array.

import numpy as np

def array_stats(arr):

# Calculate mean, median, and standard deviation

mean_value = np.mean(arr)

median_value = np.median(arr)

std_deviation = np.std(arr)

return mean_value, median_value, std_deviation

# Create a NumPy array with random integers

random_array = np.random.randint(1, 100, 10) # Generating 10 random integers between 1 and 100

# Display the random array

print("Random Array:", random_array)

# Calculate and display mean, median, and standard deviation using the function

mean, median, std_dev = array_stats(random_array)

576 576 576


41
577
42

print("Mean:", mean)

print("Median:", median)

print("Standard Deviation:", std_dev)

18:

#Implement matrix multiplication using NumPy arrays and

#explain the advantages of using NumPy for matrix operations.

import numpy as np

# Create two matrices using NumPy arrays

matrix1 = np.array([[1, 2, 3],

[4, 5, 6],

[7, 8, 9]])

matrix2 = np.array([[9, 8, 7],

[6, 5, 4],

[3, 2, 1]])

# Perform matrix multiplication

result_matrix = np.dot(matrix1, matrix2)

# Display the result

print("Matrix 1:")

print(matrix1)

print("\nMatrix 2:")

print(matrix2)

print("\nResultant Matrix (Matrix Multiplication):")

577 577 577


42
578
43

print(result_matrix)

19:

import matplotlib.pyplot as plt

# Create a simple line plot

x = [1, 2, 3, 4, 5]

y = [2, 4, 6, 8, 10]

plt.plot(x, y)

plt.xlabel('X-axis')

plt.ylabel('Y-axis')

plt.title('Simple Line Plot')

plt.show()

20:

#BROADCASTING

import numpy as np

# Create a 3x3 matrix

matrix = np.array([[1, 2, 3],

[4, 5, 6],

[7, 8, 9]])

# Define a one-dimensional array

row_vector = np.array([10, 20, 30])

# Add the row_vector to each row of the matrix using broadcasting

result = matrix + row_vector

578 578 578


43
579
44

print(result)

21:

import pandas as pd

# Read data from Excel file

input_file = "input_data.xlsx"

output_file = "output_results.xlsx"

# Change sheet_name and usecols as needed based on your Excel file structure

df = pd.read_excel(input_file, sheet_name="Sheet1", usecols=["Column1", "Column2"])

# Perform data analysis (calculate mean and standard deviation)

mean_values = df.mean()

std_dev_values = df.std()

# Create a new DataFrame with the analysis results

analysis_results = pd.DataFrame({

"Mean": mean_values,

"Standard Deviation": std_dev_values

})

# Display the analysis results

print("Analysis Results:")

print(analysis_results)

# Save the analysis results to a new Excel file

analysis_results.to_excel(output_file, index_label="Column")

579 579 579


44
580
45

print(f"\nAnalysis results saved to '{output_file}'.")

23:

##import tkinter as tk

import tkinter as tk

def on_button_click():

label.config(text="Hello, Tkinter!")

# Create the main window

root = tk.Tk()

root.title("Tkinter Example")

# Create a label

label = tk.Label(root, text="Welcome to Tkinter!")

label.pack(pady=10)

# Create a button

button = tk.Button(root, text="Click Me", command=on_button_click)

button.pack(pady=10)

# Run the Tkinter event loop

root.mainloop()

24:

##colur chnage

import tkinter as tk

from random import choice

def change_color():

580 580 580


45
581
46

new_color = choice(colors)

root.configure(bg=new_color)

# Create the main window

root = tk.Tk()

root.title("Color Changer")

# Define a list of colors

colors = ["red", "green", "blue", "yellow", "orange", "purple", "pink"]

# Create a button

button = tk.Button(root, text="Change Color", command=change_color)

button.pack(pady=20)

# Run the Tkinter event loop

root.mainloop()

25:

## image upload

import tkinter as tk

from tkinter import filedialog

from PIL import Image, ImageTk

def open_file_dialog():

file_path = filedialog.askopenfilename(title="Select an Image", filetypes=[("Image files",


"*.png;*.jpg;*.jpeg;*.gif")])

if file_path:

display_image(file_path)

def display_image(file_path):

image = Image.open(file_path)

581 581 581


46
582
47

photo = ImageTk.PhotoImage(image)

label.config(image=photo)

label.image = photo

# Create the main window

root = tk.Tk()

root.title("Image Uploader")

# Create a button to open the file dialog

upload_button = tk.Button(root, text="Upload Image", command=open_file_dialog)

upload_button.pack(pady=20)

# Create a label to display the image

label = tk.Label(root)

label.pack()

# Run the Tkinter event loop

root.mainloop()

27:

import tkinter as tk

def display_message():

user_input = entry.get()

message_label.config(text=f"Hello, {user_input}!")

# Create the main window

root = tk.Tk()

root.title("Entry Widget Example")

# Create an Entry widget

entry = tk.Entry(root, width=30)

entry.pack(pady=10)

# Create a button

button = tk.Button(root, text="Display Message", command=display_message)

button.pack(pady=10)

582 582 582


47
583
48

# Create a label to display the message

message_label = tk.Label(root, text="")

message_label.pack(pady=10)

# Run the Tkinter event loop

root.mainloop()

28:

import tkinter as tk

win = tk.Tk()

# add an orange frame

frame1 = tk.Frame(master=win, width=100, height=100, bg="orange")

frame1.pack()

# add blue frame

frame2 = tk.Frame(master=win, width=50, height=50, bg="blue")

frame2.pack()

# add green frame

frame3 = tk.Frame(master=win, width=25, height=25, bg="green")

frame3.pack()

win.mainloop()

import tkinter as tk

583 583 583


48
584
49

win = tk.Tk()

for i in range(5):

for j in range(3):

frame = tk.Frame(

master = win,

relief = tk.RAISED,

borderwidth = 1

frame.grid(row=i, column=j)

label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}")

label.pack()

win.mainloop()

from tkinter import *

top = Tk()

top.geometry("400x250")

Username = Label(top, text = "Username").place(x = 30,y = 50)

email = Label(top, text = "Email").place(x = 30, y = 90)

password = Label(top, text = "Password").place(x = 30, y = 130)

e1 = Entry(top).place(x = 80, y = 50)

e2 = Entry(top).place(x = 80, y = 90)

e3 = Entry(top).place(x = 95, y = 130)

top.mainloop()

584 584 584


49
585
50

ABES ENGINEERING COLLEGE, GHAZIABAD

Unit-5
QUESTION BANK
SUBJECT NAME: PYTHON PROGRAMMING
SUBJECT CODE: BCC-302

Q.No Description CO BL
Write a Python program to create a line plot using matplotlib that
1 CO5 K2
displays the population growth of a city over 10 years.
Create a NumPy array with random integers and write a function to
2 CO5 K3
find the mean, median, and standard deviation of the array.
Implement matrix multiplication using NumPy arrays and explain the
3 CO5 K3
advantages of using NumPy for matrix operations.
Load a CSV file into a Pandas DataFrame and display basic statistics
4 (mean, median, std) for a specific column. Explain the concept of CO5 K3
merging and joining in Pandas with suitable examples.
Describe the purpose and usage of the Tkinter library in Python for
5 CO5 K2
creating graphical user interfaces (GUIs).
6 List and explain some common Tkinter widgets and their use cases. CO5 K2
Create a simple Tkinter application that takes user input in a text box
7 and displays it in a label widget when a button is clicked. CO5 K3

Discuss the event-driven programming model in Tkinter and how it


8 CO5 K2
differs from procedural programming.
Create a Tkinter program that uses at least three different types of
9 widgets, such as buttons, labels, and entry fields, to build a basic CO5 K3
calculator.
Develop a Tkinter application that allows users to browse and select
10 CO5 K3
an image file from their computer and display it on the GUI.
Compare and contrast the popular Python Integrated Development
Environments (IDEs) like PyCharm, VSCode, and Jupyter
11 Notebook. Discuss their strengths and weaknesses. CO5 K2
Describe the steps to set up a Python project in your preferred IDE,
including creating virtual environments and managing dependencies.
Create a bar chart using Matplotlib that visualizes the sales data for a
12 set of products over a month. Add labels, titles, and customize the CO5 K3
chart appearance.
Describe the purpose of broadcasting in NumPy and provide an
13 CO5 K2
example where it is useful.
Discuss the role of the root window in a Tkinter application and
14 CO5 K2
explain how it is created and configured.
Create a Tkinter program that uses the Listbox widget to implement
15 a simple to-do list application with options to add, remove, and mark CO5 K3
tasks as complete.

585 585 585


50
586
51

ABES ENGINEERING COLLEGE, GHAZIABAD

Discuss the advantages and disadvantages of various geometry


16 CO5 K2
managers in Tkinter, such as pack(), grid(), and place().
Write a Python program that reads data from an Excel spreadsheet
17 using Pandas, performs data analysis, and generates a new Excel file CO5 K2
with the results.
Explain the difference between plot() and scatter() functions in
18 CO5 K2
Matplotlib, and when to use each.
Describe the event-driven programming paradigm in the context of
19 Tkinter and explain how it differs from traditional procedural CO5 K2
programming.
Develop a Tkinter application for a basic calculator with a user-
20 friendly interface for addition, subtraction, multiplication, and CO5 K2
division.

586 586 586


51
587

ABES Engineering College, Ghaziabad


B. Tech Odd Semester Sessional Test-1 Solution

Printed Pages:2
Session: 2023-24
Semester: III
Course Code: BCC302 Roll No.:
Course Name: Python Programming Time: 1.15 Hrs.
Maximum Marks: 30
Instructions:
1. Attempt All sections.
2. If require any missing data, then choose suitably.

Q. No. Question Marks CO KL PI


Section-A Total Marks: 20
1 Attempt ANY ONE part from the following Same K Levels Questions
What is python, and why is it considered a high-level programming
language?
solution:
Python is a high-level, general-purpose programming language that
was created by Guido van Rossum and first released in 1991. It has
become one of the most popular and widely used programming
languages in the world. Python is known for its simplicity,
a) readability, and versatility, making it an excellent choice for a wide 5 CO1 K2 1.3.1
range of applications, including web development, data analysis,
scientific computing, artificial intelligence, automation, and more.
It's high-level because it abstracts low-level details, focuses on
readability, is platform-independent, has a vast standard library,
uses dynamic typing, manages memory automatically, and is
interpreted rather than compiled. These features make it an
excellent choice for a wide range of applications.
Explain the difference between a compiler and an interpreter in the
context of programming languages.
solution:

b) 5 CO1 K2 1.3.1

2 Attempt ANY ONE part from the following Same K Levels Questions

587 587 587


588

Define the term "left-associative" and "right-associative" operators


in the context of programming languages. Give examples of each.
solution:
In programming languages, the terms "left-associative" and "right-
associative" are used to describe how operators with the same
precedence are grouped and evaluated when they appear in a
sequence within an expression. These terms are particularly relevant
in languages that support multiple operators in a single expression.

5 + 3 – 2 In this
a) 5 CO1 K2 1.3.1
expression, the
addition is evaluated
first (left to right),
followed by
subtraction.

2 ^ 3 ^ 2 In this expression, the exponentiation is evaluated


from right to left. First, 3 ^ 2 is calculated, and then 2 ^ (9) is
evaluated

How do you declare and assign values to variables? What are data
types in Python? Give examples of different data types.
solution:
In Python, you do not need to declare variables with explicit
data types as you do in some other programming languages like
C or Java. Python is a dynamically-typed language, which
means that the data type of a variable is determined at runtime
based on the value it is assigned. This is in contrast to statically-
typed languages where you need to declare the data type of a
variable explicitly before using it.
my_variable = 42 # No need to specify data
type
In Python, data types are used to classify and represent different
b) 2.5+2.5 CO1 K2 2.1.2
types of data, such as numbers, text, and more. Python has
several built-in data types, and you can also create custom data
types using classes. Here are some common built-in data types
in Python:
x=5 Integers (int):
y = -10 Floating-Point Numbers (float)
pi = 3.14159 Strings (str):
price = 19.99
name = "Alice" Booleans (bool):
message = 'Hello, World!'
is_true = True NoneType (None):
is_false = False Complex Type:
empty_variable = None

588 588 588


589

3 Attempt ANY ONE part from the following Same K Levels Questions

Can we make multiline comments in Python? Write a program


to find the sum of all odd numbers up to a number.
solution:
Python does not have a specific syntax for multi-line comments.
However, you can create multi-line comments using triple-quotes
(''' or """). These are often used for longer comments, docstrings
(function or module documentation), and explanations that span
multiple lines.
'''
This is a multi-line comment or docstring.
It can span multiple lines and is often used for
providing detailed explanations or documentation.
'''
a) # Input: Get the number from the user 4+6 CO1 K2 2.1.2

Describe the is and is not operators and type() function. Also,


discuss why Python is called as dynamic and strongly typed
language.
solution:
is and is not are identity operators in Python, used to check if
two variables or objects refer to the same memory location (i.e.,
they are the same object) or if they are different objects.
These operators compare the identity of objects, not their
values.
b) x is y returns True if x and y are the same object, and x is not y 5+5 CO1 K2 2.1.2
returns True if they are not the same object.
a = [1, 2, 3]
b = a # Both a and b now refer to the same list object
c = [1, 2, 3] # A new list with the same values

print(a is b) # True, a and b reference the same list


print(a is c) # False, a and c are different objects with the same
values

589 589 589


590

print(a is not c) # True, a and c are not the same object

Python is called a dynamic and strongly typed language due to


the way it handles data types and type checking during runtime.
In a dynamically typed language like Python, the data type of a
variable is not explicitly declared. Instead, the type is
determined at runtime based on the value assigned to the
variable.
Variables in Python can change their data type as needed, and
you can reassign a variable to a different type without explicit
type declarations.
x=5 # x is an integer
x = "hello" # x is now a string
x = [1, 2] # x is now a list
Python is also considered a strongly typed language. This
means that Python enforces strict type checking, and it does not
automatically perform implicit type conversions or coercions.
x=5 # x is an integer
y = "2" # y is a string

# The following would raise a TypeError because Python


doesn't implicitly convert y to an integer.
result = x + y # TypeError: unsupported operand type(s) for +:
'int' and 'str'
Section-B Total Marks: 10
4 Attempt ANY ONE part from the following Same K Levels Questions

Write a python program that calculates and prints the BMI of a


person based on their weight (in kilograms) and height (in meters)
entered by the user. [Company Specific]
solution:
The BMI is calculated as weight divided by the square of height
(BMI = weight / (height^2)).

a) 5 CO2 K3 3.2.2

590 590 590


591

Write a python program that checks if a set of three given sides can
form a valid triangle. Print a message indicating whether it's
possible or not. [Company Specific]
solution:

b) 5 CO2 K3 3.2.2

5 Attempt ANY ONE part from the following Same K Levels Questions
Write a Program to prompt for a score between 0.0 and 1.0. If
the score is out of range, print an error. If the score is between
0.0 and 1.0, print a grade using the following:
>= 0.9 --A, >=0.8 -- B, >=0.7 --C, >=0.6 --D and <0.6 –F
solution:

a) 5 CO2 K3 2.1.3

Write a Python program that calculates and prints the ticket


price for a theme park based on a person's age and height.
solution:

b) 5 CO2 K3 2.1.3

591 591 591


592

592 592 592


593

ABES Engineering College, Ghaziabad


B. Tech Odd Semester Sessional Test-2 Solution
Printed Pages:
Session: 2023-24
Semester: 3
Course Code: BCC302 Roll No.:
Course Name: Python Programming Time: 1.15 Hrs.
Maximum Marks: 30
Instructions:
1. Attempt All sections.
2. If require any missing data, then choose suitably.

Q. No. Question Ma CO KL PI
rks
Section-A Total Marks : 20
Same K Levels
1 Attempt ANY ONE part from the following
Questions
Explain the Set-in python. Elaborate the various built-in functions used
in set.
ANSWER
1. Set stores the unique values as data collection
2. Set is mutable (changeable)
3. Set is unordered
4. Set elements are enclosed in brackets { }
5. Set not allows duplicate elements.
6. Set can contain elements of different data types.
There are more than 15 Python set of built-in methods that can be used
on sets.
1.Add() Method
Python set add () method is used to add an element to the given input
a) set. If the element already exists, then the add () method does not add 2+3 CO3 K2 2.1.2
the element.
set. Add(element)
2.Update() Method
Python set update () method is used to update the current set by adding
items to it from another set. If an item is present in both sets then only
one appearance of this item will be present in the updated set.
set. Update(element)
3. Clear () method
Python set clear () method is used to remove all the elements in the given
input set.
set. clear ()

593 593 593


594

4.Copy () method
Python set copy () method is used to copy the given input set.
set. copy ()
5.Pop () method
Python Set pop () Method in python set is an inbuilt method which is
used to removes a random element from the set and returns the popped
(removed) elements.
set. Pop ()
6.Remove () method
Python Set remove () Method in python set is used to remove the
specified element from the given set. This method will raise an error if
element does not exist in the set.
set. Remove(item)
7. Discard () method
Python set discard () method is used to remove the specified item from
the given input set. It is different from the remove () method because the
remove () method will give an error if the specified item does not exist
but this method will not.
set. Discard(value)
8. Len () method
The set Len is one of the set methods used to find the length of a set
(total number of items).

Explain the concept of string. Write a program to print number of


alphabets and digits in a given string.
ANSWER
1.String is a sequence of alphanumeric and special character
2. Strings are created in many ways using single quotes or double-
quotes.
3.String is immutable (changeable)
4. Strings element can be accessed using square [] brackets.
5. Single character is simply a string with a length of 1.

b) 2+3 CO3 K2 2.1.2

594 594 594


595

Same K Levels
2 Attempt ANY ONE part from the following
Questions
When to Use Python Lists. Write Python program to swap elements in
the list.
ANSWER
1.List elements are enclosed in square brackets [] and are comma
separated.
2.List is the sequence of class type ‘list’.
3.List can contain elements of different data types.
4.List is a mutable(changeable)
5. List allows duplicate elements.
6.List elements are ordered, it means it give specific order to the
elements, if new element is added, by default it comes at the end of the
list.

a) 2+3 CO3 K2 1.3.1

595 595 595


596

Differentiate between mutable and immutable objects in Python


language with example.
ANSWER
mutable
1.An object that allows you to change its values without
changing its identity is a mutable object.
2.mutable objects are easy to change.
3.It is More efficient
4.Memory allocations of the object can change during its lifetime
5.Provides a method to add or remove element
6.Example mutable data Types List, Set and Dictionary
Immutable
1.An object that doesn’t allow changes in its value is
b) an immutable object 5 CO3 K2 1.3.1

2.Immutable objects are quicker to access


3.It is Less efficient
4.Memory allocations of the object remains Constant during its
lifetime
5. Does Not Provides a method to add or remove element
6.Example immutable data Types String, Tuples, Float and
Frozen set

Same K Levels
3 Attempt ANY ONE part from the following
Questions

596 596 596


597

(i) Write a program that merges two dictionaries and handles


duplicate keys intelligently.
ANSWER
d1 = {'k1': 1, 'k2': 2}
d2 = {'k1': 5, 'k3': 3, 'k4': 4}
d = d1 | d2
print(d)
d = d2 | d1
print(d)
Output
{'k1': 5, 'k2': 2, 'k3': 3, 'k4': 4}

{'k1': 1, 'k3': 3, 'k4': 4, 'k2': 2}

(ii) Write Python program to join two input tuples, if their first
5+
a) element is common. CO3 K3 3.2.2
5
ANSWER

Elaborate the importance of slicing in python. Provide the outputof


below code snippet:
S = 'ABCDEFGHI'
print(S[2:7])
print(S[-7:-2])
print(S[2:-5])
Soln:
In Python, slicing is a powerful feature that allows you to extract a
5+
b) portion of a sequence (like a string, list, or tuple). Slicing is done using CO3 K3 3.2.2
5
the syntax start:stop, where start is the index of the first element you
want to include, and stop is the index of the first element you want to
exclude. If start or stop is not specified, it defaults to the beginning or
end of the sequence, respectively. Additionally, you can use negative
indices to count from the end of the sequence.
Now, let's analyze the given code snippet:
S = 'ABCDEFGHI'
print(S[2:7]) # Extract elements from index 2 to 6 (7-1)

597 597 597


598

print(S[-7:-2]) # Extract elements from index -7 to -3 (-2+1)


print(S[2:-5]) # Extract elements from index 2 to -6 (-5+1)
print(S[2:7]): This will extract the elements from index 2 to 6
(inclusive), so the output will be 'CDEFG'.

print(S[-7:-2]): This will extract the elements from index -7 to -3


(inclusive), counting from the end of the string. The output will be
'CDEFG'.

print(S[2:-5]): This will extract the elements from index 2 to -6


(inclusive), so the output will be 'CDE'.

Now, let's run the code and check the output:


S = 'ABCDEFGHI'
print(S[2:7]) # Output: 'CDEFG'
print(S[-7:-2]) # Output: 'CDEFG'
print(S[2:-5]) # Output: 'CD'

A string is said to be a palindrome if the reverse of the string is the


same as the string. Consider the below examples:

1. Input: malayalam Output: Yes 2. Input: Python Output: No


Write a python program to check whether a string is palindrome or
not.
Soln:
# Test case 1
input_string1 = "malayalam"
# Convert the string to lowercase
input_string1 = input_string1.lower()
# Remove spaces from the string
input_string1 = ''.join(input_string1.split())
# Check if the string is a palindrome
if input_string1 == input_string1[::-1]:
print(f"Input: {input_string1} Output: Yes")
else:
print(f"Input: {input_string1} Output: No")

# Test case 2
input_string2 = "Python"
# Convert the string to lowercase
input_string2 = input_string2.lower()
# Remove spaces from the string
input_string2 = ''.join(input_string2.split())
# Check if the string is a palindrome
if input_string2 == input_string2[::-1]:
print(f"Input: {input_string2} Output: Yes")
else:
print(f"Input: {input_string2} Output: No")

598 598 598


599

Section-B Total Marks : 10

4 Attempt ANY ONE part from the following Same K Levels


Questions

Write a program to check if given input number is Armstrong


number or not.
Soln:
# Convert the number to a string to determine the number of digits
num_str = str(input_number)

# Calculate the power (number of digits)


power = len(num_str)
a) 5 CO2 K3 2.1.3
# Calculate the sum of each digit raised to the power
armstrong_sum = sum(int(digit) ** power for digit in num_str)

# Check if the sum is equal to the original number


if armstrong_sum == input_number:
print(f"{input_number} is an Armstrong number.")
else:
print(f"{input_number} is not an Armstrong number.")

Implement a program that prints the following pattern

2.1.
b) 5 CO2 K3
Soln: 3
rows = 5

for i in range(1, rows + 1):


for j in range(i):
print(i, end="")
print()
5 Attempt ANY ONE part from the following Same K Levels
Questions

599 599 599


600

Write short Note on


(i) Break
(ii) Continue
(iii) Pass
Soln:
(i) Break: The break statement is used in Python to exit from a loop
prematurely. When the break statement is encountered within a loop
(for example, for or while), the loop is terminated, and the program
continues with the next statement after the loop. It is often used with
conditional statements to exit a loop based on certain conditions.
Example:
Python code
for i in range(1, 10): if i == 5: break print(i)
In this example, the loop will print numbers from 1 to 4, and when i
becomes 5, the break statement is encountered, and the loop is
terminated.
(ii) Continue: The continue statement is used to skip the rest of the
code inside a loop for the current iteration and jump to the next
iteration. When the continue statement is encountered, the remaining
code within the loop for the current iteration is skipped, and the loop
proceeds with the next iteration.
Example:
Python code
for i in range(1, 6): if i == 3: continue print(i)
In this example, the loop will print numbers from 1 to 5, but when i is
3, the continue statement is encountered, and the print statement for 2+2
a) CO2 K2 2.1.2
that iteration is skipped. +1
(iii) Pass: The pass statement in Python is a no-operation statement. It
is often used as a placeholder where syntactically some code is
required, but no action is desired. It is essentially a null operation and
does nothing.
Example:
Python code
for i in range(5): if i == 2: pass else: print(i)
In this example, when i is 2, the pass statement is encountered, and no
action is taken. For other values of i, the loop will print the value of i.

600 600 600


601

Discuss the basic structure of a for loop and While Loop in Python. Why
is there no "do while" loop in Python?
Soln:
For Loop: The basic structure of a for loop in Python is as follows:

Python code
for variable in iterable: # code to be executed in each iteration
• The for keyword is used to start the loop.
• variable is the loop variable that takes on the values of the
elements in the iterable.
• iterable is a sequence (such as a list, tuple, or string) that the
loop iterates over.
• The indented block of code under the for statement is executed
in each iteration.

Example:

Python code
for i in range(5): print(i)

While Loop: The basic structure of a while loop in Python is as


follows:

Python code
while condition: # code to be executed as long as the condition is True
• The while keyword is used to start the loop.
• condition is a boolean expression. The loop continues as long
as the condition is True. 2+
b) CO2 K2 2.1.2
• The indented block of code under the while statement is
3
executed as long as the condition is True.

Example:

Python code
count = 0 while count < 5: print(count) count += 1

No "do while" loop in Python: Python does not have a built-in "do
while" loop like some other programming languages. The "do while"
loop typically executes a block of code at least once before checking
the loop condition. In Python, the same behavior can be achieved using
a while loop with an initial condition that is always True, and then
using a break statement to exit the loop when a certain condition is
met.

Example:

Python code
while True: # code to be executed at least once if condition: break

The absence of a "do while" loop in Python is mainly a design choice


to promote code readability and simplicity. The alternative with while
True and break is considered more Pythonic and is seen as clear and
explicit in its intent.
601 601 601
602

CO Course Outcomes mapped with respective question


KL Bloom's knowledge Level (K1, K2, K3, K4, K5, K6)
K1-Remember, K2-Understand, K3-Apply, K4-Analyze, K5:Evaluate, K6-Create

602 602 602


603

ABES Engineering College, Ghaziabad


B. Tech Odd Semester Sessional Test-3
Solution

Printed Pages:
Session: 2023-24
Semester:3rd
Course Code: BCC 302 Roll No.:
Course Name: Python Programming Time:1Hr 30 Min.
Maximum Marks: 40

1(a) Explain the working of the seek() and tell () methods in file handling with examples.
Solution:
In Python's file handling, the seek() and tell() methods are used to control the current position (or cursor
position) within a file and to determine the current position, respectively.
The seek() method is used to change the current file position to the specified offset.
Syntax: file_object.seek(offset, whence)
offset: The number of bytes to move the cursor. A positive value moves the cursor forward, while a negative
value moves the cursor backward.
whence (optional): It specifies the reference point for seeking. It can take one of the following values:
0 (default): The start of the file
1: The current file position
2: The end of the file
tell() method:
The tell() method returns the current position of the cursor (or file pointer) within the file.
Syntax: file_object.tell()
The seek() and tell() methods are often used together to navigate within a file, read or write data from/to
specific positions, or to keep track of the current position while performing file operations.

1(b) Define pickling in Python. Explain serialization & deserialization of Python objects.
Solution:
Pickling in Python refers to the process of serializing Python objects into a binary format that can be written
to a file or transmitted over a network, and later deserialized to reconstruct the original objects. Pickling is a

603 603 603


604

way to convert complex data structures, such as lists, dictionaries, and custom objects, into a byte stream,
which can then be saved to disk or transferred between different Python processes.
Serialization and deserialization are two related concepts that are central to pickling:
Serialization:
Serialization is the process of converting a Python object into a byte stream or other formats (such as JSON
or XML) that can be easily stored, transmitted, or persisted.
In the context of pickling, serialization involves converting Python objects into a binary format, which can be
achieved using Python's built-in pickle module. During serialization, complex data structures are flattened
into a byte stream, preserving their internal structure and relationships. Serialized data can be saved to disk as
a file, transmitted over a network, or stored in a database.
Deserialization:
Deserialization is the process of reconstructing Python objects from a byte stream or other serialized formats
back into their original form.
In the context of pickling, deserialization involves reading a byte stream from a file or network and
reconstructing the original Python objects.
The pickle module provides functions to deserialize pickled data and reconstruct the original objects.
During deserialization, the byte stream is parsed and interpreted to rebuild the original data structures.
2(a) Differentiate between:
i) text file and binary file
ii) readline() and readlines()
iii) write() and writelines()
Solution:
Text File: A text file is a file that contains plain text characters. It can be opened and edited using a simple
text editor such as Notepad. Text files typically contain human-readable text, such as letters, numbers, and
symbols encoded in a specific character encoding (e.g., ASCII, UTF-8). Examples of text files include .txt,
.csv, and .html files.
Binary File: A binary file is a file that contains data in a binary format, meaning it includes non-textual data
represented in binary (0s and 1s). Binary files can contain any type of data, including images, audio, video,
and executable programs. Unlike text files, binary files cannot be easily interpreted using a text editor.
Examples of binary files include image files (e.g., .jpg, .png), audio files (e.g., .mp3, .wav), and executable
files (e.g., .exe).

604 604 604


605

2(b) How to append a line of text to an existing file named "output.txt." and count and display the total
number of words on the console.
Solution:

You can append a line of text to an existing file named "output.txt" using the 'a' mode when opening the file
with the open() function. After appending the line, you can count the total number of words in the file by
reading its contents, splitting the text into words, and then counting the number of words.

3(a)
File I/O (Input/Output) in Python refers to the process of reading from and writing to files on the disk.
Python provides built-in functions and methods to perform file I/O operations easily.
Here's a brief overview of the file I/O operations in Python:
Open a File (open() function):
To open a file, you use the open() function, which takes two parameters: the file name (or path) and the
mode in which you want to open the file ('r' for reading, 'w' for writing, 'a' for appending, 'r+' for reading and
writing, etc.).
Syntax: file_object = open(file_name, mode)
Read from a File:
After opening a file for reading, you can read its contents using various methods such as read(), readline(),
or readlines().
read(): Reads the entire contents of the file as a single string.
readline(): Reads one line from the file.
readlines(): Reads all lines from the file and returns a list of strings (each string represents a line).
Example:
file_object = open("file.txt", "r")

605 605 605


606

content = file_object.read()
print(content)
file_object.close()
Write to a File:
After opening a file for writing, you can write data to it using the write() method.
Syntax: file_object.write(data)
Example:
file_object = open("file.txt", "w")
file_object.write("Hello, World!")
file_object.close()
Close a File:
After you're done reading from or writing to a file, it's important to close the file using the close() method to
free up system resources.
Syntax: file_object.close()

3(b)

606 606 606


607

4(a) How are NumPy arrays better than Python’s lists? Explain.
Solution:

NumPy arrays offer several advantages over Python's built-in lists, particularly in scenarios involving
numerical computation and data manipulation. Here are some key reasons why NumPy arrays are often
preferred:
Performance: NumPy arrays are implemented in C, which makes them much faster compared to Python lists
for numerical operations. This is because operations on NumPy arrays can be vectorized, meaning that they
operate on entire arrays rather than on individual elements, which leads to reduced overhead and improved
performance, especially for large datasets.
Memory Efficiency: NumPy arrays consume less memory compared to Python lists. This is because NumPy
arrays store data in a contiguous block of memory, whereas Python lists store references to objects, resulting
in additional memory overhead. For numerical datasets, this memory efficiency can be crucial, particularly
when dealing with large datasets.
Convenience: NumPy provides a wide range of built-in functions and methods for performing various
mathematical operations and array manipulations. These functions are optimized for performance and are
often more convenient to use compared to writing equivalent code using Python lists. Additionally, NumPy
supports broadcasting, which allows operations to be performed on arrays of different shapes, further
enhancing convenience and expressiveness.
Functionality: NumPy arrays support multidimensional arrays and offer a rich set of functionalities for array
manipulation, including slicing, indexing, reshaping, concatenation, and more. This makes NumPy arrays
suitable for a wide range of applications, including numerical computing, data analysis, and machine learning.
Integration with Libraries: NumPy is a fundamental building block for many scientific computing and data
analysis libraries in Python, such as SciPy, Pandas, Matplotlib, and scikit-learn. As a result, using NumPy
arrays facilitates seamless integration with these libraries, enabling a unified ecosystem for scientific
computing and data analysis tasks.
Overall, NumPy arrays are better suited for numerical computation and data manipulation tasks compared to
Python lists due to their superior performance, memory efficiency, convenience, functionality, and seamless
integration with other libraries in the Python ecosystem.

4(b) Discuss various geometry managers in Tkinter, such as pack (), grid(), and place().
Solution:
In Tkinter, geometry managers are used to organize and arrange widgets within a GUI window or frame. The
three primary geometry managers in Tkinter are pack(), grid(), and place(). Each manager has its own way of
organizing widgets, and the choice of which one to use depends on the specific requirements of the layout.

pack() Geometry Manager:


The pack() geometry manager organizes widgets in a block, either horizontally or vertically.
Widgets are packed inside their parent container (e.g., window or frame) one after another.
Options such as side, fill, and expand control how widgets are packed and distributed within the container.

grid() Geometry Manager:

607 607 607


608

The grid() geometry manager arranges widgets in rows and columns, forming a grid-like structure.
Widgets are placed within the grid by specifying their row and column indices.
Options such as row, column, rowspan, columnspan, sticky, and pad allow for fine-grained control over
widget placement and sizing.

place() Geometry Manager:

The place() geometry manager allows for absolute positioning of widgets within their parent container.
Widgets are placed at specific coordinates (x, y) within the container.
Options such as x, y, anchor, and relx, rely (relative positioning) provide control over widget placement.

5(a) Given a CSV file named "sales_data.csv" containing sales data for a company. Each row represents a
sale, with columns 'Date', 'Product', 'Quantity', and 'Revenue'. Write Python code to perform the following
tasks:
• Load the data from the CSV file into a Pandas DataFrame.
• Display the first 10 rows of the DataFrame.

Solution:

• We import the pandas library as pd.


• We use the pd.read_csv() function to read the data from the CSV file named "sales_data.csv" and
load it into a pandas DataFrame named df.
• We use the head() method to display the first 10 rows of the DataFrame. If you want to display
more or fewer rows, you can pass the desired number as an argument to the head() method (e.g.,
df.head(20) to display the first 20 rows).
5(b)
Write a python program to create a line plot using matplotlib that displays the population growth of a city
over 10 years.
Solution:

608 608 608


609

6(a)
What are ndarrays in NumPy? What are ways of creating 1D, 2D and 3D arrays in NumPy? Implement
matrix multiplication using NumPy arrays. [Company Specific]
Solution:
NumPy, short for Numerical Python, is a library in Python used for working with arrays. The core feature of
NumPy is the ndarray (n-dimensional array) object, which is a multidimensional array. It provides a fast and
efficient way of storing and manipulating numerical data in Python.

6(b)
Describe the event-driven programming paradigm in the context of Tkinter and explain how it differs from
traditional procedural programming. [Company Specific]
Solution:
Event-driven programming is a paradigm commonly used in graphical user interface (GUI) programming,
and Tkinter, which is a Python library for creating GUI applications, follows this paradigm. In event-driven
programming, the flow of the program is determined by events such as user actions (e.g., clicking a button,
typing on a keyboard, moving a mouse), system notifications, or messages from other parts of the program.
Here's how event-driven programming works in the context of Tkinter:

Event Loop:

609 609 609


610

Tkinter provides a main event loop (also known as the "event loop" or "mainloop") that continuously listens
for events and dispatches them to event handlers.
The event loop is started using the mainloop() method, and it runs until the application is terminated or
instructed to stop.
Event Handlers:

Event handlers (also known as "callbacks" or "event listeners") are functions or methods that are called in
response to specific events.
In Tkinter, you associate event handlers with GUI elements such as buttons, text boxes, or menu items using
methods like bind() or command.
When the associated event occurs (e.g., a button is clicked), Tkinter invokes the corresponding event handler.

Asynchronous Execution:
In event-driven programming, the execution of code is asynchronous. This means that the program doesn't
follow a linear flow from start to finish; instead, it responds to events as they occur.
For example, if a user clicks a button while the program is executing another task, the event handler for the
button click is triggered immediately, interrupting the current execution flow.
Here's how event-driven programming in Tkinter differs from traditional procedural programming:

Control Flow:
In traditional procedural programming, the control flow is typically linear, following a sequence of
instructions from start to finish.
In event-driven programming, the control flow is determined by events. The program waits for events to
occur and responds to them dynamically, which can lead to a more interactive and responsive user interface.

User Interaction:
In traditional procedural programming, user interaction is often limited to command-line input and output.
In event-driven programming with Tkinter, user interaction is facilitated through graphical user interfaces,
allowing users to interact with the application through buttons, menus, text boxes, etc.

Concurrency:
Event-driven programming inherently supports concurrency, as multiple events can occur simultaneously
and be handled asynchronously.
Traditional procedural programming may require explicit concurrency mechanisms (e.g., threads) to handle
multiple tasks concurrently.

610 610 610


611

BCC302 / BCC402/ BCC302H / BCC402H :


PYTHON PROGRAMMING
Course Outcome ( CO) Bloom’s Knowledge Level (KL)

At the end of course , the student will be able to understand


Interpret the fundamental Python syntax and semantics and be fluent in the use of Python control flow
CO 1 K1, K2
statements.
CO 2 Express proficiency in the handling of strings and functions K1, K2
Determine the methods to create and manipulate Python programs by utilizing the data structures like
CO 3 K3
lists, dictionaries, tuples and sets.
CO 4 Identify the commonly used operations involving file systems and regular expressions. K1, K2
Articulate the Object-Oriented Programming concepts such as encapsulation, inheritance and
CO 5 K2, K3
polymorphism as used in Python
DETAILED SYLLABUS
Unit Topic Lecture
I Introduction to Python: Python variables, Python basic Operators, Understanding python
blocks. Python Data Types, Declaring and using Numeric data types: int, float etc. 03

Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
II python, For loop using ranges, string, list and dictionaries. Use of while loops in python,
05
Loop manipulation using pass, continue, break and else. Programming using Python
conditional and loop blocks.
Python Complex data types: Using string data type and string operations, Defining list
and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building
III blocks of python programs, string manipulation methods, List manipulation. Dictionary 04
manipulation, Programming using string, list and dictionary in-built functions. Python
Functions, Organizing python codes using functions.
Python File Operations: Reading files, Writing files in python, Understanding read
IV functions, read(), readline(), readlines(). Understanding write functions, write() and 04
writelines() Manipulating file pointer using seek Programming, using file operations.
Python packages: Simple programs using the built-in functions of packages matplotlib,
V numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter and 04
PythonProgramming, Tk Widgets, Tkinter examples. Python programming with IDE.
Text books:
1. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition , Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition , Cengage Learning publication
3. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley, 2015
4. Jeeva Jose &P.SojanLal, “Introduction to Computing and Problem Solving with PYTHON”, Khanna Publishers, New Delhi,
2016
5. Downey, A. et al., “How to think like a Computer Scientist: Learning with Python”, John Wiley, 2015
6. Mark Lutz, “Learning Python”, 5th edition, Orelly Publication, 2013, ISBN 978- 1449355739
7. John Zelle, “Python Programming: An Introduction to Computer Science”, Second edition, Course Technology Cengage
Learning Publications, 2013, ISBN 978- 1590282410
8. Michel Dawson, “Python Programming for Absolute Beginers” , Third Edition, Course Technology Cengage Learning
Publications, 2013, ISBN 978-1435455009
9. David Beazley, Brian Jones., “Python Cookbook”, Third Edition, Orelly Publication, 2013, ISBN 978-1449340377

611 611 611

You might also like