Final Notes Python
Final Notes Python
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
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 5 Day 6
7 7 7
4
Copyright © 2021, ABES Engineering College
Session Plan - Day 1 8
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
Application Development
Web Development
Artificial Intelligence
Data Science
10 10 10
7
Copyright © 2021, ABES Engineering College
11
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
15 15 15
12
Copyright © 2021, ABES Engineering College
16
Review Questions
17 17 17
14
Copyright © 2021, ABES Engineering College
18
Advantages of Python
18 18 18
15
Copyright © 2021, ABES Engineering College
19
Contd..
}
}
19 19 19
16
Copyright © 2021, ABES Engineering College
20
Contd..
In Python
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
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
24 24 24
21
Copyright © 2021, ABES Engineering College
25
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”)
26 26 26
23
Copyright © 2021, ABES Engineering College
27
Review Questions
27 27 27
24
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
28
28 28 28
29 29 29
26
Copyright © 2021, ABES Engineering College
30
1.2 Python Installation Guide
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.
32 32 32
29
Copyright © 2021, ABES Engineering College
33
Contd..
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
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
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.
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
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
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
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
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..
57 57 57
54
Copyright © 2021, ABES Engineering College
58
Review Questions
58 58 58
55
Copyright © 2021, ABES Engineering College
59
Review Questions
59 59 59
56
Copyright © 2021, ABES Engineering College
Session Plan - Day 4 60
60 60 60
57
Copyright © 2021, ABES Engineering College
61
Python keywords
Python keywords are special reserved words that have specific meanings
and purposes.
function name
variable name
identifiers
61 61 61
58
Copyright © 2021, ABES Engineering College
62
Contd..
62 62 62
59
Copyright © 2021, ABES Engineering College
63
input-output statements,
arithmetic statements,
control statements,
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.
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 "
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.
Float Literals - These are basically real numbers that consist of both integer
as well as fractional parts.
66 66 66
63
Copyright © 2021, ABES Engineering College
67
Numeric Literals
Example -
10j , 1 + 0j , 10 + 2J, 12 – 5j
67 67 67
64
Copyright © 2021, ABES Engineering College
68
In Python, True represents the Non-zero value and False represents the
value as Zero.
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( [ ]).
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 )
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 (,) .
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.
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.
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.
72 72 72
69
Copyright © 2021, ABES Engineering College
73
Can you answer these questions?
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 –
76 76 76
73
Copyright © 2021, ABES Engineering College
Session Plan - Day 5 77
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 )
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
Explicit Type Conversion – In this, user converts the data type of variable
of value to needed data type.
Example –
80 80 80
77
Copyright © 2021, ABES Engineering College
81
Can you answer these questions?
a) 12 (20+0j) 123.45
b) 12 20 123.45
c) Error
81 81 81
78
Copyright © 2021, ABES Engineering College
82
82 82 82
79
Copyright © 2021, ABES Engineering College
83
Example –
Example –
84 84 84
81
Copyright © 2021, ABES Engineering College
85
Example –
85 85 85
82
Copyright © 2021, ABES Engineering College
86
sep - (optional), Specify how to separate the values, if there is more than
one. Default is ' '.
87 87 87
84
Copyright © 2021, ABES Engineering College
88
88 88 88
85
Copyright © 2021, ABES Engineering College
Session Plan - Day 6 89
89 89 89
86
Copyright © 2021, ABES Engineering College
90
Operators
Operators are symbol, used to perform mathematical and logical
operation.
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
94 94 94
91
Copyright © 2021, ABES Engineering College
95
Example –
Note - The == and != operators can actually work with values of any data
type.
95 95
92
95
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
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
Example –
Explanation –
Example –
Explanation –
Example –
Explanation –
Example –
Explanation –
Example –
Explanation –
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.
Logical Operators
Example –
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
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
Cont..
Precedence and Associativity Table –
Python 2 vs Python 3
Python 2 vs Python 3
Python 2 vs 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.
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
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 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.
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.
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.
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.
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
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.
1. https://docs.python.org/3/tutorial/controlflow.html
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
UNIT:2
Control Flow System
Day 1
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.
To understand the purpose and syntax of Iterative/looping statements and jump statements.
To apply the knowledge of conditions, loops and jump in solving real time problems.
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
Conditional statements.
Iterative/looping statements.
Revision of Flowchart
Connector / flow
Simple if
if-else
if..elif..else
Nested...if…else
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.
Syntax of Simple if
Examples
Print whether a number is even or not.
Case-1 : When n is even. Case-2 : When n is not even
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,
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
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
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.
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”.
Example
A) if a>=2 :
B) if (a >= 2)
C) if (a => 22)
D) if a >= 22
A) if-elif statement
B) for statement
C) if -else statement
D) if statement
A) No output
B) okok
C) ok
D) None of above
A) Launch a Missile
C) 0.3
D)None
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
Control statement are statements that control the flow of execution of statements so that
they can be executed repeatedly and randomly.
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
While loop
For loop
Write a Python Program to print 4 Natural Numbers using i.e. 1,2,3,4 using While
loop.
Options
A. None
B. Python
C. Ppppp
D. PPPPP
A. 0 1 2
B. 2 3
C. 0 1 2 0
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
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.
Introduction to Iterative/looping
statements:
Assignment No.1
Faculty Name: Tarun Kumar Gautam Sem & Section: 2rd A,B
C
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
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
2.
2_
24
(e) How do you perform a search in Python? 5
2P
5.
SECTION B
.5
P2
|1
(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
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
1
13
0
29
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
|1
(b) Explain the terms Merge List and Merge Sort in Python Programming. 5
: 36
: 25
13
2
02
-2
ar
M
2-
|2
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
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
56
x[0] *= 3
x[1][1] = 'bye'
1
02
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,
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
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
56
SECTION C
7:
a. How can you create Python file that can be imported as a library as well 10 5
1
import library
and
M
2-
library.
makePairs([1,3,5,7],[2,4,6,8])
returns [(1,2),(3,4),(5,6),(7,8)]
makePairs([],[])
returns []
P
Q no. Question 0Q Marks CO
a. Explain why Python is considered an interpreted language. 10 1
1
13
29
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
triangle(3) prints:
*
**
***
triangle(5) prints:
*
**
***
****
*****
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
5.
_Q
.5
17
7. Attempt any one part of the following:
TU
|1
in lst are alternately odd and even, starting with an even number.
:0
UNIT:1
C:\Users\Tarun\AppData\Local\Programs\Python\Python310
anconda: http://localhost:8889/notebooks/Untitled1.ipynb?kernel_name=python3
1:
a=10
2:
print (8 * "\n")
out:
Welcome to Guru99
3:
SI = (p*r*t)/100
amountpay = p+SI
4:
5:
import math
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
7:
a=2
b=3
c=a+b
print (c)
8:
x=10
print (x)
print (x)
9:
10:
11:
n1 = 10
n2 = 20
n3 = 30
out:
original numbers: 10 20 30
after swapping: 20 30 10
12:
n1,n2,n3=n2,n3,n1
n1,n2,n3=n2,n3,n1
13:
x,y=7,2
x,y=y,x+1
print (x,y)
output: 2 8
14:
x=20
y=40
x=x-5
y=y-6
15:
x=20
y=40
x=y
y=x
20 40
40 40
16:
x=20
y=40
c=5
x=y
y=c
c=x
20 40 5
40 5 40
17:
x=20
y=40
c=5
k=x
x=y
y=c
c=x
x=k
out:
enter no x, y,c: 20 40 5
after swapping 20 5 40
18:
cube = num*num*num
19:
area = L*B
20:
km = mile/0.6
21:
avg = (x+y+z)/3
22:
string :
23:
numerical literals
a= 10
b =23.6
c = 10+5j
print (a)
print (b)
print (c)
24:
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:
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)
Unit 2:
1: string :
2: numerical literals
a= 10
b =23.6
c = 10+5j
print (a)
print (b)
print (c)
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)
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)
1: odd/ even
if (n%2==0):
print ("even")
else:
print ("odd")
2: less or greater
if (n>0):
n =n+1
else:
3:
if (n>95):
print ("exellent",n)
else:
4:
if (marks>95):
print ("exellent")
print ("good")
print ("average")
else:
5:
if marks>95:
print ("exellent")
print ("good")
print ("average")
else:
6:
if age>0:
if age<18:
else:
else:
7:
x =3
print ("ok")
else:
8:
y =0.3
if y!=0.3:
else:
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):
condition2=1
while condition2<=3:
condition2+=1
condition1+=1
13:
i=0
while i<3:
print(i)
i+=1
else:
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:
print (i)
17:
for i in num:
print (i)
18:
num =5
print (i,"*5=",i*5)
19:
var=10
print (i,j)
20:
print (i,j)
20:
string ="TECHNOLOGY"
for j in range(len(string)):
print (string[4])
21:
num1 = 5
num2 = 4
while ( num2>=1):
print ('&')
print ('+')
num2= num2-1
print ('*')
22:
print (i)
23:
i=1
while i<5:
if i==3:
break
print (i)
i=i+1
24:
i=1
while i<5:
if i==3:
i=i+1
continue
print (i)
i=i+1
25:
condition=1
while (condition<5):
print (condition)
condition=condition+1
else:
26:
condition=1
while (condition<5):
print (condition)
condition=condition+1
if (condition==3):
break
else:
27:
print (i)
else:
28:
if (i==5):
break
print (i)
else:
29:
color_name=['Red','Green','Blue','Pink']
for c in color_name:
if name==c:
break
else:
30:
if n%i==0:
break
else:
31:
if (i==3):
continue
print (i)
32:
print(i)
if (i==7):
print ("break")
break
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
G
TK
BY
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
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.
To understand the purpose and syntax of Iterative/looping statements and jump statements.
To apply the knowledge of conditions, loops and jump in solving real time problems.
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
Conditional statements.
Iterative/looping statements.
Revision of Flowchart
Connector / flow
Simple if
if-else
if..elif..else
Nested...if…else
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.
Syntax of Simple if
Examples
Print whether a number is even or not.
Case-1 : When n is even. Case-2 : When n is not even
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,
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
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
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.
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”.
Example
A) if a>=2 :
B) if (a >= 2)
C) if (a => 22)
D) if a >= 22
A) if-elif statement
B) for statement
C) if -else statement
D) if statement
A) No output
B) okok
C) ok
D) None of above
A) Launch a Missile
C) 0.3
D)None
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
Control statement are statements that control the flow of execution of statements so that
they can be executed repeatedly and randomly.
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
While loop
For loop
Write a Python Program to print 4 Natural Numbers using i.e. 1,2,3,4 using While
loop.
Options
A. None
B. Python
C. Ppppp
D. PPPPP
A. 0 1 2
B. 2 3
C. 0 1 2 0
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
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.
Introduction to Iterative/looping
statements:
range (1,5,1)
Note: Range()Function returns the range object, you must typecast range function into
collections.
For loop
Syntax of For loop:
For loop is used when we want to
run a part of our program multiple
times.
Example1: Example2:
For loop with range function: Table of number 5 is printed using for loop
Nested for loop is called when we use for loop Syntax of Nested For loop:
a. b.
A. N
How many time special character print?
B. n A. 11
B. 8
C. H
C. 10
D. h
D. 6
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.
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.
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
Break
Syntax
Example
Explanation :-
Continue
It is used to :-
Skip ongoing iteration
Syntax
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.
Example
While loop will execute normally up to a given condition. No early exit is there so else block
will be executed.
Example
While loop will get terminated when value of condition variable = 3, So else
block will not be executed.
Example
.
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
.
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.
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:
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
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
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
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.
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.
https://docs.python.org/3/tutorial/controlflow.html
https://fresh2refresh.com/python-tutorial/python-jump-statements/
https://tutorialsclass.com/python-jump-statements/
Thank You
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
20 CO2 K3
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.
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:
while condition:
if some_condition:
# No action needed in this case
pass
else:
# Perform some action
do_something()
6.
def calculate_product(numbers):
product = 1
for num in numbers:
product *= num
return product
if i%2==0:
print(i)
if i=10:
continue
else:
print(i, end=" ")
10.
Q11 Ans
while True:
user_input = input("Enter a number (or enter 42 to terminate): ")
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
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)
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
# 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 j in range(i+1):
# nCr = n!/((n-r)!*r!)
print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")
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()
UNIT-3
3.Python Collections and Sequences
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.
To describe the importance of list , string, tuple , dictionary and set in python
Empty String
Positive Indexing
Negative 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.
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.
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
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.
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
A. True
False
B. False
False
A. ES
B. En
C. ES En
D. ESEn
A. hellohowa
B. hellohowaaaaa
C. hellohowaaaaaaa
D. Error
3.1 String
Built in Methods
Basic Operations
String Formatters
Loops with Strings
Review Questions
Practice Exercises
In String, we can’t reassign the string characters but we can delete the complete string
using del command.
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:
+ Concatenation
* 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)
String formatting is the process of infusing things in the string dynamically and presenting
the string.
Here, format implies that in what look and feel we want our strings to get printed.
String formatting is the process of infusing things in the string dynamically and presenting
the string.
Here, format implies that in what look and feel we want our strings to get printed.
\\ Backslash
\n Newline
We have placed two curly braces and arguments that give the format method filled in
the same output.
We can also use format specifier in format method like in language ‘C’. Format
specifier are used to do following.
Fstring is the way of formatting as format method does but in an easier way.
A. True
B. False
C. Error
D. None
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
Example 3 – Write a program to print number of alphabets and digits in a given string.
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.
3.2 List
Creation
Accessing
Updation
Review Questions
Practice Exercises
It means last element can be accessed using -1 index, second last as -2 and so on.
List updating involves insertion of new elements, deletion of elements or deletion of complete list.
List updating involves insertion of new elements, deletion of elements or deletion of complete
list.
A.[‘XY’,’YZ’]
B.[‘xy’,’yz’]
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]
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:
Append function always add the element at the end of the list.
Syntax:
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.
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.
list1 has been deleted and then we are trying to print it and its giving error because
it does not exist now.
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.
Practice Exercise:
Write a python program to count positive, negative and string type elements.
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.
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.
.
Practice Exercise:
Using nested list print transpose, of a given matrix
Let's suppose we want to write a program to calculate powers of 3 for a given range.
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.
3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises
3.3 Tuple
• Creation
• Assessing
• Modification/Updation
• Built in Methods
• Operations
• Review Questions
• Practice Exercises
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.
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.
.
Unpacking is called when the multiple variables is assigned to a tuple; then these variables take
corresponding values.
Practice Questions:
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 [].
Example:
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…
Indexes start from zero, and it goes up to a number of elements or say -1.
Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.
If we want to change any of the index value in tuple, this is not allowed and throw an error.
Here, we are taking the same above example of days and showing the immutable
characteristic of tuple
Write a Python program to get the 4th element and 4th element from last of a tuple.
To check whether an
Membership element belong to tuple
or not
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.
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)
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.
3.4 Dictionaries
• Creation
• Assessing
• Modification/Updation
• Nested Dictionary
• Built in Methods
• Review Questions
• Practice Exercises
A) ‘Java’
B) ‘Python’
C) KeyError
D) None of above
A) 5
B) 10
C) 15
D) None of above
A) {1:’Store’,2:’Kitchen’}
B) {2:’Store’,1:’Kitchen’}
C)KeyError
D) None of above
A) True
B) False
3.4 Dictionary
• Built in Methods in Dictionary
• Loops in Dictionary
• Review Questions
• Practice Exercises
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.
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
Output
Output
Output
Output
Output
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
A) {1:’Store’,2:’Kitchen’}
B) {2:’Store’,1:’Kitchen’}
C)KeyError
D) None of above
3.5 Set
• Creation
• Assessing
• Modification
• Built in methods
• Operators
• Loops
• Frozen Set
• Review Questions
A) True
B) False
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.
discard()
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)
A frozen set is a special category of the set which is unchangeable once created
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={}
A) iii
B) i and ii
C) ii and iii
D) All of Above
A) {0,0,9}
B) {0,9}
C) {9}
D) Error
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
Q1: Explain the concept of string indexing & slicing and provide an example in Python.
Ans:
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.
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.
Example:
Q2: Differentiate between Mutable and Immutable objects in python languages with
example?
Ans:
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
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:
python
2. # 2 and 3 are arguments
3. sum_result = add(2, 3)
4.
1. Local Scope:
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:
python
• global_variable = "I am global"
def example_function():
print(global_variable)
example_function()
print(global_variable)
• Scope Hierarchy:
python
x = 10 # Global variable
def outer_function():
y = 20 # Enclosed variable
def inner_function():
z = 30 # Local variable
print(x, y, z)
inner_function()
outer_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'):
else:
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)
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:
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:
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 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)
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
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.
python
# Unpacking with the * operator
first, *rest = (1, 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
the numbers. The algorithm is named after the ancient Greek mathematician Eratosthenes, who
first described it.
python
def sieve_of_eratosthenes(limit):
primes = []
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
return primes
# Example usage:
limit = 30
result = sieve_of_eratosthenes(limit)
print(result)
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.
• 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.
python
# Sample list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
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
• 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.
• 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
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:
In this code:
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)
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
ANS:
#Sample dictionary
sample_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}
In this script:
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'
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])
return fib_numbers[:n]
In this program:
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
return largest
# Example usage:
my_list = [3, 8, 2, 7, 5, 1, 4]
result = find_largest_element(my_list)
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()
return merged_dict
# Example dictionaries
dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 25, 'c': 35, 'd': 40}
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 = []
return unique_list
# Example usage:
my_list = [3, 2, 1, 2, 4, 3, 5, 4, 6]
result = remove_duplicates(my_list)
In this example:
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
# 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.
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):
# Example usage:
number = 5
result = factorial(number)
In this function:
When you run this code with the provided example (number = 5), it will output:
csharp
The factorial of 5 is: 120
return merged_dict
if not lst:
return None
largest = lst[0]
largest = element
return largest
my_list = [3, 8, 2, 7, 5, 1, 4]
result = find_largest_element(my_list)
print("List:", my_list)
sample_string = 'google.com'
char_frequency = {}
char_frequency[char] = char_frequency.get(char, 0) + 1
print(f"{char}: {frequency}")
o/p:
Character Frequencies in the String:
g: 2
o: 3
l: 1
e: 1
.: 1
c: 1
m: 1
#Sample dictionary
sample_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}
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
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)]
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]
# 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
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()
return vowel_count
o/p:
if num % 2 == 0:
# Skip number 10
if num == 10:
continue
print(num)
o/p:
2
4
6
8
12
14
16
18
20
8. Armstrong_numbe program :
def is_armstrong_number(number):
str_number = str(number)
num_digits = len(str_number)
# Calculate the sum of each digit raised to the power of the number of digits
if is_armstrong_number(user_number):
else:
O/P:
Enter a number to check for Armstrongness: 153
153 is an Armstrong number.
9. Palindrome PROGRAM
def is_palindrome(input_str):
input_str = str(input_str).lower()
if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
O/P:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Index
UNIT-4
PYTHON : BCC-302
2. Class Programs 24
3. Important Questions 30
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
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.
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.
Text File
Binary file: The term "binary file" is often used as a term meaning “non-text file”.
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
4
509 509 509
5
510
6
file_name − The file_name argument is a string value that contains the name or path of the file that you
want to access.
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).
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)
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
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.
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.
Here, file_object is an object of file that has been open for read or write operation.
6
511 511 511
7
512
8
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.
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)
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)
• 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)
try:
with open(file_path, "r") as file:
# Read the first line
line1 = file.readline()
print(line1)
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()
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except IOError:
print("Error reading the file.")
9
514 514 514
10
515
11
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
• We can also find the cursor position from the built-in tell () method as shown in Figure
7.9.1(b)
• 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.
• 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)
• 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.
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:
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
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"]
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"]
•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"]
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()
output:
Built-in writelines() method used to write multiple lines of string in form of list in the file.
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
10
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:
12
523 523 523
19
524
20
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.
To delete anentire folder, you must import the OS module, and run its os.rmdir(). Deleting a
folder named myfolder.
13
For example a user want to pickle age, salary and a dictionary contains their mobile number
and email.
14
For example a user want to unpickle age, salary and a dictionary contains their mobile number
and email of previous example
15
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
f.close()
2. f=open("unit.txt","w")
for i in range(n):
f.write(s)
f.close()
output:
how many times3
enter your roll no=120
enter your roll no=126
enter your roll no=156
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
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
print(partial_content)
output:
welcome to
print(partial_content)
output:
me to file
7. file_path = "unit.txt"
try:
line1 = file.readline()
print(line1)
line2 = file.readline()
print(line2)
except FileNotFoundError:
except IOError:
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:
lines = file.readlines()
except FileNotFoundError:
except IOError:
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
9. file_path = "unit.txt"
# Use "w" for write mode. If the file doesn't exist, it will be created.
file.write("Hello, World!\n")
file.write("Python is awesome!\n")
file_path = "unit.txt"
file.writelines(lines_to_write)
position = file.tell()
print(file.read())
print(file.tell())
output:
Current position: 0
449
position_before_read = file.tell()
position_after_read = file.tell()
print(f"Content: {content}")
output:
Content:
we
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
Line 3
f.close()
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.
print(file1.read())
print()
file1.close()
output:
Output of Readlines after appending
This is Delhi
This is Paris
This is LondonToday
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
Index
UNIT-5
PYTHON : BCC-302
2. Class Programs 37
3. Important Questions 50
UNIT-5:
UNIT
Here's a brief explanation of how load and dump work along with examples:
• Description:
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.
• Description:
• 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
• Example:
python
import json
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
• 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
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
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
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
• 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]])
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.
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
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
• 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]})
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
# 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"])
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])
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:
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.
• 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.
Tkinter module is part of the standard library. To use tkinter, import the tkinter module
using the below-given code(Figure-8.2.1).
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 -
We used the title() method for setting the title and used the configure() method for
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.
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.
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.
Output -
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
Output-
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.
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.
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
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-
Example –2 To display label having text in "yellow", background in "dark green", font style
in "Helvetica", size 16.
Output-
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).
Output -
Example – 1 Create a window having one label and a Textbox (Entry widget)
Output -
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) 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.
Example – Create a window having two buttons as shown in Figure 8.4.3 Output
Output -
The Checkbutton widget is used to display several options to a user as toggle buttons.
Example – Create a window and place three checkbutton as shown in figure 8.4.4
Output -
This widget implements a multiple-choice button. Only one radio button in a group can be
selected at a time.
Example – Create a window having two radio button, one label with male and second with
Female as shown in figure 8.4.5
Output -
A frame is just a container for other widgets. It is used for grouping and organizing other
widgets in a somehow friendly way.
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.
Output -
FunctionName − Name of the appropriate message box function. Figure 8.4.7(a) shows
different types of function used for the message box.
Figure 8.4.7(a) Different type of message box and its function name
Example - Create a Button and call a function name show_msg() which displays a message
using messageBox.
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.
Example 1 – Create four buttons and pack them left, right, top, and bottom side.
Output -
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”.
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.
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
Output -
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.
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 -
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.
Methods – it has two methods to set or get value to/from the widget.
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.
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.
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 -
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 -
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 -
Python needs a MySQL driver to access the MySQL database. So first, we install the mysql-
connector-python package using the below command
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.
Create the connection object – To create a connection with MySQL database, we used
connect() method of mysql.connector module.
Create the cursor object - The cursor object is used to execute SQL queries to the
database.
Execute the query - To execute SQL queries, execute() method of the cursor object is used.
fetchall() – We use the fetchall() method, fetched all rows from the last executed
statement.
Syntax – myresult = my_cursor.fetchall()
Example – Create a login form and connect to a database to check username and
password with MySql Database.
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.
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.
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.
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
Class Programs:
1.
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.show()
plt.legend()
3:
plt.plot(x, y)
plt.scatter(x, y)
4:
import numpy as np
5:
print(result) # Output: [5 7 9]
6:
# Broadcasting example
scalar = 2
print(result)
# Output:
# [[2 4 6]
# [8 10 12]]
7:
# Example of ufuncs
square_root = np.sqrt(arr)
8:
print(result)
# Output:
# [[19 22]
# [43 50]]
9:
import pandas as pd
10:
df = pd.DataFrame({
})
11:
13:
14:
15:
16:
years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]
population = [500000, 520000, 540000, 560000, 580000, 600000, 620000, 640000, 660000, 680000]
plt.xlabel('Year')
plt.ylabel('Population')
# Display a legend
plt.legend()
plt.show()
17:
#Create a NumPy array with random integers and write a function to find
import numpy as np
def array_stats(arr):
mean_value = np.mean(arr)
median_value = np.median(arr)
std_deviation = np.std(arr)
random_array = np.random.randint(1, 100, 10) # Generating 10 random integers between 1 and 100
# Calculate and display mean, median, and standard deviation using the function
print("Mean:", mean)
print("Median:", median)
18:
import numpy as np
[4, 5, 6],
[7, 8, 9]])
[6, 5, 4],
[3, 2, 1]])
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print(result_matrix)
19:
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.show()
20:
#BROADCASTING
import numpy as np
[4, 5, 6],
[7, 8, 9]])
print(result)
21:
import pandas as pd
input_file = "input_data.xlsx"
output_file = "output_results.xlsx"
# Change sheet_name and usecols as needed based on your Excel file structure
mean_values = df.mean()
std_dev_values = df.std()
analysis_results = pd.DataFrame({
"Mean": mean_values,
})
print("Analysis Results:")
print(analysis_results)
analysis_results.to_excel(output_file, index_label="Column")
23:
##import tkinter as tk
import tkinter as tk
def on_button_click():
label.config(text="Hello, Tkinter!")
root = tk.Tk()
root.title("Tkinter Example")
# Create a label
label.pack(pady=10)
# Create a button
button.pack(pady=10)
root.mainloop()
24:
##colur chnage
import tkinter as tk
def change_color():
new_color = choice(colors)
root.configure(bg=new_color)
root = tk.Tk()
root.title("Color Changer")
# Create a button
button.pack(pady=20)
root.mainloop()
25:
## image upload
import tkinter as tk
def open_file_dialog():
if file_path:
display_image(file_path)
def display_image(file_path):
image = Image.open(file_path)
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo
root = tk.Tk()
root.title("Image Uploader")
upload_button.pack(pady=20)
label = tk.Label(root)
label.pack()
root.mainloop()
27:
import tkinter as tk
def display_message():
user_input = entry.get()
message_label.config(text=f"Hello, {user_input}!")
root = tk.Tk()
entry.pack(pady=10)
# Create a button
button.pack(pady=10)
message_label.pack(pady=10)
root.mainloop()
28:
import tkinter as tk
win = tk.Tk()
frame1.pack()
frame2.pack()
frame3.pack()
win.mainloop()
import tkinter as tk
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.pack()
win.mainloop()
top = Tk()
top.geometry("400x250")
top.mainloop()
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
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.
b) 5 CO1 K2 1.3.1
2 Attempt ANY ONE part from the following Same K Levels Questions
5 + 3 – 2 In this
a) 5 CO1 K2 1.3.1
expression, the
addition is evaluated
first (left to right),
followed by
subtraction.
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
3 Attempt ANY ONE part from the following Same K Levels Questions
a) 5 CO2 K3 3.2.2
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
b) 5 CO2 K3 2.1.3
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 ()
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).
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.
Same K Levels
3 Attempt ANY ONE part from the following
Questions
(ii) Write Python program to join two input tuples, if their first
5+
a) element is common. CO3 K3 3.2.2
5
ANSWER
# 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")
2.1.
b) 5 CO2 K3
Soln: 3
rows = 5
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)
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
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
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).
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")
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)
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.
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.
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:
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:
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.
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