Python Unit 1
Python Unit 1
PYTHON PROGRAMMING
Course Outcome ( CO) Bloom’s Knowledge Level (KL)
At the end of course , the student will be able to understand
Interpret the fundamental Python syntax and semantics and be fluent in the use of Python control flow
CO 1 K1, K2
statements.
CO 2 Express proficiency in the handling of strings and functions K1, K2
Determine the methods to create and manipulate Python programs by utilizing the data structures like
CO 3 K3
lists, dictionaries, tuples and sets.
CO 4 Identify the commonly used operations involving file systems and regular expressions. K1, K2
Articulate the Object-Oriented Programming concepts such as encapsulation, inheritance and
CO 5 K2, K3
polymorphism as used in Python
DETAILED SYLLABUS
Unit Topic Lecture
I Introduction to Python: Python variables, Python basic Operators, Understanding python
blocks. Python Data Types, Declaring and using Numeric data types: int, float etc. 03
Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
II python, For loop using ranges, string, list and dictionaries. Use of while loops in python,
05
Loop manipulation using pass, continue, break and else. Programming using Python
conditional and loop blocks.
Python Complex data types: Using string data type and string operations, Defining list
and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building
III blocks of python programs, string manipulation methods, List manipulation. Dictionary 04
manipulation, Programming using string, list and dictionary in-built functions. Python
Functions, Organizing python codes using functions.
Python File Operations: Reading files, Writing files in python, Understanding read
IV functions, read(), readline(), readlines(). Understanding write functions, write() and 04
writelines() Manipulating file pointer using seek Programming, using file operations.
Python packages: Simple programs using the built-in functions of packages matplotlib,
V numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter and 04
PythonProgramming, Tk Widgets, Tkinter examples. Python programming with IDE.
Text books:
1. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition , Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition , Cengage Learning publication
3. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley, 2015
4. Jeeva Jose &[Link], “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
Introduction to Python Programming
Syllabus of Chapter 1:Introduction to Python Programming
1. Introduction to Python
• Overview of Python
• History and Features
2. Python Variables
• Rules for variable names
• Assigning values to variables
• Global and local variables
3. Python Basic Operators
• Arithmetic operators
• Comparison operators
• Assignment operators
• Bitwise operators
• Logical operators
4. Understanding Python Blocks
• Indentation
• Code blocks
5. Python Data Types
• Numeric types
• Sequence types
• Mapping type
• Set types
• Boolean type
• Binary types
• None type
1
Notes for Chapter 1: Introduction to Python Pro-
gramming
Introduction to Python
Python is an interpreted, object-oriented, high-level programming language cre-
ated by Guido van Rossum. Python’s design philosophy emphasizes code read-
ability and simplicity. It has a simple and easy-to-use syntax, making it a
popular choice for beginners. It supports Object-Oriented programming, which
encapsulates code within objects. Python is dynamically typed and garbage-
collected. It has a large standard library that supports many common program-
ming tasks.
Python Variables
Variables are containers that store values. For example:
name = "John"
age = 25
• Can only contain alpha-numeric characters and underscores (A-z, 0-9, and
).
• Are case-sensitive.
x = "global"
def my_function():
x = "local"
print(x)
my_function()
print(x)
2
Python Basic Operators
Arithmetic Operators
Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulus: %
Exponentiation: **
Floor division: //
Comparison Operators
Equal: ==
Not equal: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
Assignment Operators
Assign: =
3
Add and assign: +=
Subtract and assign: -=
Multiply and assign: *=
Divide and assign: /=
Modulus and assign: %=
Exponentiation and assign: **=
Floor division and assign: //=
Bitwise Operators
AND: &
OR: |
XOR: ^
NOT: ~
Zero fill left shift: <<
Signed right shift: >>
Logical Operators
AND: and
OR: or
NOT: not
4
Operator Description Example
and Logical AND True and False = False
or Logical OR True or False = True
not Logical NOT not True = False
for i in range(5):
print(i)
print("Outside the loop")
Sequence Types:
• str: String type
Mapping Type:
• dict: Dictionary type
Set Types:
Boolean Type:
5
• bytes: Byte type
Important Questions
1. What are the key features of Python?
2. Explain the difference between local and global variables with an example.
3. List and explain different arithmetic operators in Python with examples.
4. What is the significance of indentation in Python? Provide an example.
Answers
1. Key features of Python:
• Interpreted
• Object-oriented
• High-level language
6
• Dynamically typed
• Garbage-collected
• Large standard library
• Simple and readable syntax
x = "global"
def my_function():
x = "local"
print(x)
3. Arithmetic Operators:
# Addition
x = 5 + 3
print(x) # Output: 8
# Subtraction
x = 5 - 3
print(x) # Output: 2
# Multiplication
x = 5 * 3
print(x) # Output: 15
# Division
x = 6 / 3
print(x) # Output: 2.0
# Modulus
x = 5 % 3
print(x) # Output: 2
# Exponentiation
x = 2 ** 3
print(x) # Output: 8
# Floor Division
x = 7 // 2
7
print(x) # Output: 3
4. Significance of Indentation:
for i in range(5):
print(i)
print("Outside the loop")
5. Data Types:
# Numeric Types
x = 10 # int
y = 10.5 # float
z = 1 + 2j # complex
# Sequence Types
a = "Hello" # str
b = [1, 2, 3] # list
c = (1, 2, 3) # tuple
d = range(5) # range
# Mapping Type
e = {"a": 1, "b": 2} # dict
# Set Types
f = {1, 2, 3} # set
g = frozenset({1, 2, 3}) # frozenset
# Boolean Type
h = True # bool
# Binary Types
i = b"hello" # bytes
j = bytearray(5) # bytearray
k = memoryview(bytes(5)) # memoryview
# None Type
l = None # NoneType
Important Code Examples
Example 1: Basic Python Program
print("Hello, World!")
print(greet("Alice"))
Example 4: Looping
for i in range(5):
print(i)
10
Python Programming Notes
Detailed Notes
Conditional Blocks
Conditional blocks in Python control the flow of execution based on specified
conditions. The primary structures for conditionals are if, else, and elif
statements.
1. if, else, and elif:
if condition:
# code block
An if statement evaluates a condition and executes the associated code block
if the condition is true.
else statement:
if condition:
# code block
else:
# code block
An else statement follows an if statement and executes the code block if the
if condition is false.
elif statement:
1
if condition1:
# code block
elif condition2:
# code block
else:
# code block
An elif (else if) statement allows you to check multiple conditions in sequence.
If the first if condition is false, the program evaluates the elif condition.
Example:
num = 10
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Loops
Loops are used to repeatedly execute a block of code as long as a condition is
met.
1. For Loop: A for loop is used for iterating over a sequence (such as a
list, tuple, dictionary, set, or string).
for variable in sequence:
# code block
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
For Loop with Ranges: The range() function generates a sequence of
numbers, which is useful for iterating over with for loops.
for i in range(5):
print(i)
While Loop: A while loop repeatedly executes a block of code as long as
the specified condition is true.
while condition:
# code block
Example:
count = 0
while count < 5:
print(count)
count += 1
2
Loop Manipulation
Loop manipulation statements are used to control the flow of loops. These
include break, continue, pass, and else.
1. break: Terminates the loop prematurely.
for i in range(10):
if i == 5:
break
print(i)
Important Questions
1. Explain the use of if, else, and elif statements with examples.
2. How does a for loop differ from a while loop?
3. What is the purpose of the break, continue, and pass statements in loop
control?
4. Write a Python program to find the factorial of a number using both for
and while loops.
5. Explain the use of else with loops and provide an example.
3
Answers to Important Questions
1. Use of if, else, and elif statements:
if condition:
# code block
else:
# code block
elif condition1:
# code block
elif condition2:
# code block
else:
# code block
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
for i in range(10):
if i == 5:
break
print(i)
for i in range(10):
if i % 2 == 0:
continue
print(i)
for i in range(10):
if i < 5:
pass
else:
print(i)
num = 5
factorial = 1
4
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, "is", factorial)
num = 5
factorial = 1
i = 1
while i <= num:
factorial *= i
i += 1
print("Factorial of", num, "is", factorial)
for i in range(5):
print(i)
else:
print("Loop finished")
Coding Questions
1. Write a Python program to check if a given number is prime:
num = 29
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
2. Write a Python program to print all the even numbers from 1 to 100 using
a for loop:
string = "Hello"
reversed_string = ""
index = len(string) - 1
5
while index >= 0:
reversed_string += string[index]
index -= 1
print(reversed_string)
4. Write a Python program to calculate the sum of all numbers in a list using
a for loop:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total)
5. Write a Python program that prompts the user for a number and deter-
mines if it is positive, negative, or zero using conditional statements:
Additional Examples
1 # Define a list of fruits and a dictionary of their colors
2 # Ek list banate hain fruits ki aur ek dictionary banate hain unki
colors ki
3 fruits = [" apple ", " banana ", " cherry", " date ", " elderberry "]
4 fruit_colors = {" apple ": " red ", " banana ": " yellow ", " cherry": " red "
, " date ": " brown ", " elderberry ": " purple "}
5
6 # Function to classify a fruit by its color
7 # Ek function banate hain jo fruit ko uske color se classify karta
hai
8 def classify_fruit ( fruit):
9 if fruit in fruit_colors : # Agar fruit dictionary mein hai to
10 color = fruit_colors [ fruit]
11 if color == " red ":
12 print( f"{ fruit} is red .")
13 elif color == " yellow ":
14 print( f"{ fruit} is yellow .")
15 elif color == " brown ":
16 print( f"{ fruit} is brown .")
17 elif color == " purple ":
18 print( f"{ fruit} is purple .")
19 else :
20 print( f"{ fruit} has an unknown color.")
6
21 else :
22 print( f"{ fruit} is not in the dictionary .")
23
24 # Use a for loop to iterate over the list of fruits
25 # Ek for loop ka use karke list ke har fruit par iterate karte hain
26 for fruit in fruits:
27 classify_frui t ( fruit)
28 if fruit == " cherry":
29 continue # Agar fruit cherry hai to , niche ka code skip
kar do aur agla iteration chalu karo
30 elif fruit == " date ":
31 break # Agar fruit date hai to , loop se bahar nikal jao
32 else :
33 pass # Kuch nahi karna , bas yahan se guzar jao
34
35 # Use a for loop with a range to print numbers
36 # Ek for loop ka use karke range ke numbers print karte hain
37 for i in range (1 , 11):
38 print( i)
39
40 # String manipulation
41 # String ko reverse karna
42 my_string = " hello "
43 reversed_string = ""
44 for char in my_string :
45 reversed_string = char + reversed_string
46 print( f" Reversed string : { reversed_string }")
47
48 # Use of pass in a function
49 # Ek function mein pass ka use
50 def pla ce hol der _f uncti o n ():
51 pass # Ye function kuch nahi karta , sirf pass se guzar jata
hai
52
53 # Call the placeholder function
54 # Placeholder function ko call karna
55 pl ace hol de r_ fu nct ion ()
56
57 # Use a while loop to find the first fruit that starts with ’b’
58 # Ek while loop ka use karke pehla fruit dhundna jo ’b’ se shuru
hota hai
59 i = 0
60 wh ile i < len ( fruits):
61 if fruits[ i]. startswith (’b’):
62 print( f" Found a fruit starting with ’b ’: { fruits[ i]}")
63 break
64 i += 1
65 el se :
66 print(" No fruit starting with ’b’ was found .")
7
July 23, 2024
Syllabus of Chapter 3
• Using string data type and string operations
• Dictionary manipulation
1
1 String Data Type and String Operations
• String Definition: Strings are arrays of bytes representing Unicode char-
acters.
• Creating Strings: Strings in Python can be created using single, double,
or triple quotes.
• String Operations:
# S t r i n g R e p e t it i o n
s t r 4 = ” Hi ! - ” ∗ 3 # R e p e t i t i o n
print ( s t r 4 ) # Output : Hi ! Hi ! Hi !
# String S l i c i n g
s t r 5 = ” He l lo - World”
print ( s t r 5 [ 0 : 5 ] ) # Output : Hello
print ( s t r 5 [ 6 : ] ) # Output : World
2
2 List and List Slicing
• List Definition: Lists are ordered collections of items. They can contain
items of different types and are mutable.
• Creating Lists: Lists are created using square brackets [ ], with ele-
ments separated by commas.
3
Listing 6: Negative Indexing
# N e gat i v e i n d e x i n g se e le me nt s ko s l i c e karna
l i s t 1 = [1 , 2 , 3 , 4 , 5]
print ( l i s t 1 [ −4 : −1 ]) # Output : [ 2 , 3 , 4 ]
4
3 Tuple Data Type
• Tuple Definition: Tuples are ordered collections of items that are im-
mutable, meaning their contents cannot be changed after creation. Tuples
can hold elements of different types, including other tuples.
• Creating Tuples: Tuples are created using parentheses ( ), with ele-
ments separated by commas. Tuples can also be created without paren-
theses, but parentheses are recommended for clarity.
5
3.3 Tuple Slicing
• Basic Slicing: Extracting a part of the tuple using slicing syntax tuple[start:stop].
• Slicing with Step: Extracting elements using a step value tuple[start:stop:step].
# Membership t e s t
print ( 2 in t upl e 1 ) # Output : True # 2 t u p l e 1 mein hai
print ( 7 in t upl e 1 ) # Output : False # 7 t u p l e 1 mein nahi hai
6
4 String, List, and Dictionary Manipulations
4.1 String Manipulation Methods
• Common Methods:
– upper(): Converts all characters in the string to uppercase.
– lower(): Converts all characters in the string to lowercase.
– replace(old, new): Replaces occurrences of a substring old with
a new substring new.
– find(substring): Returns the index of the first occurrence of the
substring. Returns -1 if the substring is not found.
# Convert s t r in g to uppercase
print ( s t r 6 . upper ( ) ) # Output : HELLO WORLD
# Convert s t r in g to lo werc as e
print ( s t r 6 . lower ( ) ) # Output : h e l l o world
7
– sort() and sorted(): Sorts the list in place or returns a new sorted
list.
– reverse(): Reverses the elements of the list in place.
– index(item): Returns the index of the first occurrence of the speci-
fied item.
# I n s e r t item at a s p e c i f i c index
m y l i s t . i n s e r t ( 2 , 10 )
print ( m y l i s t ) # Output : [ 1 , 2 , 10 , 3 , 4 , 5 , 6 , 7 , 8 ]
# Sort the l i s t
m y l i s t . s o r t ()
print ( m y l i s t ) # Output : [ 1 , 2 , 3 , 5 , 6 , 7 , 8 ]
# Reverse the l i s t
m y l i s t . r e v e r s e ()
print ( m y l i s t ) # Output : [ 8 , 7 , 6 , 5 , 3 , 2 , 1 ]
8
4.3 Dictionary Manipulations
• Common Methods:
– keys(): Returns a view object that displays a list of all the keys in
the dictionary.
– values(): Returns a view object that displays a list of all the values
in the dictionary.
– items(): Returns a view object that displays a list of tuple pairs
(key, value).
– get(key, default): Returns the value for the specified key if the
key is in the dictionary. If not, it returns the default value.
– update(other dict): Updates the dictionary with elements from
another dictionary or an iterable of key-value pairs.
– pop(key, default): Removes the item with the specified key and
returns its value. If key is not found, returns the default value.
– popitem(): Removes and returns the last key-value pair in the dic-
tionary.
– clear(): Removes all items from the dictionary.
# Get a l l keys
print ( my dict . keys ( ) ) # Output : d i c t k e y s ( [ ’ name ’ , ’ age ’ , ’ c i t y ’ ] )
# Get a l l v a l u e s
print ( my dict . va l ue s ( ) ) # Output : d i c t v a l u e s ( [ ’ Ali c e ’ , 25 , ’New York ’ ] )
# Get v al ue f or a s p e c i f i c key
print ( my dict . get ( ’ age ’ )) # Output : 25
print ( my dict . get ( ’ gender ’ , ’ Not - S p e c i f i e d ’ )) # Output : Not Sp e c i f i e d
9
print ( my dict ) # Output : { ’ name ’ : ’ A li c e ’ , ’ age ’ : 26 , ’ email ’ : ’ alice@ e xample . c
# Clear the d i c t io na ry
my dict . c l e a r ()
print ( my dict ) # Output : {}
10
4.4 List Manipulation Methods
• Common Methods: ‘append()‘, ‘extend()‘, ‘insert()‘, ‘remove()‘
l i s t 3 . i n s e r t ( 2 , 10 ) # in s e r t () method
print ( l i s t 3 ) # Output : [ 1 , 2 , 10 , 3 , 4 , 5 , 6 ]
11
4.5 Dictionary Manipulation Methods
• Common Methods: ‘keys()‘, ‘values()‘, ‘items()‘, ‘update()‘
12
5 Python Functions and Organizing Code
• Function Definition: Function ek block of reusable code hota hai jo ek
specific task perform karta hai.
• Creating Functions: Functions ko def keyword se banaya jata hai.
• Types of Functions:
– User-Defined Functions: Ye functions user ke dwara define kiye
jaate hain.
– Predefined Functions: Ye functions Python ke standard library
mein already defined hote hain.
5.1 Examples
• User-Defined Function:
def add(a, b):
"""
Do numbers ko add karke result return karta hai.
"""
return a + b
result = add(5, 3)
print(result) # Output: 8
• Predefined Function:
# ’len’ ek predefined function hai jo kisi bhi sequence ki length return karta hai.
my_list = [1, 2, 3, 4]
length = len(my_list)
print(length) # Output: 4
13
6 Important Exam Questions
6.1 Question 1: String Slicing
Question: Ek string ’Hello World’ ka slice kaise karte hain taki ’World’ mile?
Answer:
s t r 7 = ” He l lo - World”
print ( s t r 7 [ 6 : ] ) # Output : World
l i s t 4 . remove ( 3 )
print ( l i s t 4 ) # Output : [ 1 , 2 , 4 , 5 , 6 ]
del d [ ’ b ’ ]
print ( d) # Output : { ’ a ’ : 1 , ’ c ’ : 3}
14
r e s u l t = m ul t i pl y ( 4 , 5 )
print ( r e s u l t ) # Output : 20
15
16
Additional Examples
# S tr i n g Operations
# Ek s t r i n g d e f in e k art e hain aur kuch b a s i c o p e ra t io n s perform k art e hain
s t r 1 = ” Hello , World ! ”
p r in t (” O ri g in a l St ri n g : ” , s t r 1 ) # Output : Hello , World !
l o w e r s t r = s t r 1 . lower ()
p r in t (” Lowercase St r i n g : ” , l o w e r s t r ) # Output : h e l lo , world !
# L is t Operations
# Ek l i s t d e f in e k a rt e hain aur m a ni pul at ion perform ka rte hain
my list = [1 , 2 , 3 , 4 , 5]
p r in t (” O ri g in a l Lis t : ” , m y l i s t ) # Output : [ 1 , 2 , 3 , 4 , 5 ]
# Tuple Operations
# Ek t upl e d e f in e k a rte hain aur use k a rte hain
my tuple = ( 10 , 20 , 30 , 40 )
p r in t (” Tuple : ” , my tuple ) # Output : ( 10 , 20 , 30 , 40 )
17
# Di c ti o nary Operations
# Ek d i c t i o n a r y d e f in e ka rte hain aur m a nipul ati o n perform k a rte hain
my dict = { ’ name ’ : ’ Alice ’ , ’ age ’ : 25}
p r in t (” O ri g in a l Di c t i o nary : ” , my dict ) # Output : { ’ name ’ : ’ Alice ’ , ’ age ’ : 25}
# Python Functions
# Function d e f i n i t i o n aur use karna
def m ul t i pl y ( x , y ) :
”””
Do numbers ko m ul t i p l y k art a hai aur r e s u l t re turn k art a hai .
”””
re t urn x ∗ y
r e s u l t = m ul t i pl y ( 4 , 5 )
p r in t (” M u l t ip l i c a t i o n Res ult : ” , r e s u l t ) # Output : 20
d o u b l e d l i s t = do ubl e e l e m e nt s ( [ 1 , 2 , 3 , 4 ] )
p r in t (” Doubled Lis t : ” , d o u b l e d l i s t ) # Output : [ 2 , 4 , 6 , 8 ]
18
Python Programming Notes: Chapter 4
• w: Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists.
• x: Open a file for exclusive creation. If the file already exists, the operation
fails.
• a: Open a file for appending at the end without truncating it. Creates a new
file if it does not exist.
Opening a File: Use the open() function to open a file in read mode ("r").
You can specify the file path as the first argument and the mode as the second
argument.
1 file = open (" example . txt", "r")
Reading the Entire File: Use the read() method to read the entire contents
of the file as a string.
1 content = file . read ()
Reading Line by Line: Use a loop to iterate over the file object. Each iteration
reads a single line from the file using the readline() method.
1 line = file . readline ()
2 while line :
3 print( line )
4 line = file . readline ()
Reading All Lines: Use the readlines() method to read all lines from the file
and return them as a list of strings.
1 lines = file . readlines ()
Closing the File: It’s important to close the file using the close() method
when you’re done reading from it to free up system resources.
1 file . close ()
Using with Statement: It’s recommended to use the with statement to auto-
matically close the file after reading. This ensures that the file is properly closed
even if an exception occurs.
1 with open (" example . txt", " r") as file :
2 content = file . read ()
Opening a File: Use the open() function to open a file in write mode ("w"),
appending mode ("a") or binary write mode ("wb"). You can specify the file path
as the first argument and the mode as the second argument.
1 file = open (" example . txt", "w")
Writing to a File: Use the write() method to write data to the file. The
write() method takes a string as an argument.
1 file . write (" Hello , world !\ n")
Writing Multiple Lines: Use the writelines() method to write multiple lines
to the file. It takes a list of strings as an argument, where each string represents
a line.
1 lines = [" Line 1\ n", " Line 2\ n", " Line 3\ n"]
2 file . writelines( lines)
Closing the File: It’s important to close the file using the close() method
when you’re done writing to it to ensure that all data is flushed to the file and to
free up system resources.
1 file . close ()
Using with Statement: It’s recommended to use the with statement to auto-
matically close the file after writing. This ensures that the file is properly closed
even if an exception occurs.
1 with open (" example . txt", " w") as file :
2 file . write (" Hello , world !\ n")
Remember to handle exceptions that may occur while writing files, such as
IOError if the file cannot be written to.
• offset: The number of bytes to move the file pointer. A positive offset
moves the pointer forward, while a negative offset moves it backward.
• whence: The reference point from where the offset is applied. It can take
one of the following values:
– 0: Beginning of the file (default)
– 1: Current file position
– 2: End of the file
• w: Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists.
• x: Open a file for exclusive creation. If the file already exists, the operation
fails.
Q2. How do you read the contents of a file in Python? You can read the
contents of a file using the read() method for reading the entire file, readline()
for reading one line at a time, or readlines() to get a list of all lines. Here’s an
example:
1 with open (" example . txt", " r") as file :
2 content = file . read () # Reads the entire file content
3 # or
4 lines = file . readlines () # Reads all lines into a list
5 # or
6 for line in file :
7 print( line ) # Reads line by line
Q3. How do you write data to a file in Python? To write data to a file,
open it in write mode ("w") and use the write() method to add text. Here’s an
example:
1 with open (" example . txt", " w") as file :
2 file . write (" Hello , world !\ n") # Writes a line to the file
3 lines = [" Line 1\ n", " Line 2\ n"]
4 file . writelines( lines) # Writes multiple lines to the file
Q4. What is the use of the seek() method in file handling? The seek()
method is used to change the file pointer’s position. It allows you to move the
pointer to a specific location in the file for reading or writing operations. The
method takes an offset and a reference point (beginning, current position, or end).
Syllabus Description
Topic
Python Packages Simple programs using
built-in functions of
packages:
matplotlib, numpy,
pandas, etc.
GUI Programming Tkinter introduction,
Tkinter and Python
Programming,
Tk Widgets, Tkinter ex-
amples
Python Program- Usage of IDEs for
ming with IDE Python development
1 Python Packages
Python packages are essential for extending the functionality of Python by providing reusable functions
and tools. Here are detailed explanations and examples for some popular packages:
1.1 Matplotlib
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in
Python.
11 plt. show ()
Output:
7 plt. pie ( sizes , labels = labels , colors = colors , autopct=’%1.1 f%% ’, startangle =140)
8 plt. title (’ Pie ␣ Chart␣ Ex ample ’)
9
10 plt. show ()
Output:
1.2 NumPy
NumPy is a fundamental package for scientific computing in Python, providing support for arrays and
matrices.
Output:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Mean: 5.0
1.3 Pandas
Pandas is a powerful library for data manipulation and analysis, offering data structures and operations
for manipulating numerical tables and time series.
Output:
First few rows:
Name Age City
0 Alice 30 New York
1 Bob 25 San Francisco
2 Charlie 35 Chicago
Summary statistics:
Age
count 3.000000
mean 30.000000
std 5.773503
min 25.000000
25% 27.500000
50% 30.000000
75% 32.500000
max 35.000000
3 root = Tk ()
4 r o o t . t itl e ( " S i m pl e ␣ Tkin ter␣E x am pl e ")
5
6 label = Label( root , text=" Hello , ␣Tkinter!" , font =(" Arial" , 16))
7 label. pack ( pady =10)
8
9 root. mainloop ()
6 root = Tk ()
7 root. title (" Button ␣Example ")
8
9 button = Button ( root , text=" Click ␣Me", command = on_button_click , bg=" lightgreen "
)
10 button . pack ( pady =10)
11
12 label = Label( root , text=" Not␣clicked ␣yet", font =(" Arial" , 12))
13 label. pack ( pady =10)
14
15 root. mainloop ()
Important Questions
1. What is the role of NumPy in Python programming?
NumPy plays a critical role in Python programming, particularly in scientific computing
and data analysis. Here are seven key points about NumPy:
(a) Array Support: NumPy provides the ndarray object, which is a fast and flexible
multidimensional array that allows efficient storage and manipulation of large data
sets.
(b) Performance: Operations on NumPy arrays are performed at high speed and con-
sume less memory compared to traditional Python lists due to its implementation
in C.
(c) Mathematical Functions: NumPy includes a comprehensive collection of math-
ematical functions that operate on arrays, facilitating complex computations like
linear algebra, Fourier transforms, and random number generation.
(d) Broadcasting: NumPy supports broadcasting, which allows arithmetic operations
on arrays of different shapes, enabling more concise and readable code.
(e) Integration: NumPy can be integrated with other Python libraries like SciPy,
Matplotlib, and Pandas, forming a powerful ecosystem for data analysis and scientific
computing.
(f) Indexing and Slicing: NumPy provides sophisticated ways of indexing and slicing
arrays, allowing for advanced data manipulation and retrieval.
(g) Community and Documentation: With a large community and extensive docu-
mentation, NumPy is well-supported and continuously evolving, making it a reliable
choice for developers.
2. How does Pandas differ from NumPy?
Pandas is built on top of NumPy and adds data manipulation and analysis functionality,
particularly for structured data. Below is a table summarizing the differences between
Pandas and NumPy:
Feature NumPy Pandas
Data Structure Arrays (ndarrays) DataFrames, Series
Data Handling Homogeneous data Heterogeneous data
Indexing Numeric indexing Labeled indexing
Functionality Numerical operations Data manipulation, cleaning
Ease of Use Less user-friendly More user-friendly
Data Alignment Not inherently supported Automatic data alignment
Use Case High-performance operations Data analysis and manipulation
Seven key points about Pandas:
(a) Data Structures: Pandas introduces two primary data structures: Series (1D) and
DataFrames (2D), which allow for easy handling and analysis of labeled data.
(b) Data Cleaning: Pandas provides numerous tools for data cleaning, such as handling
missing values, duplications, and data transformations.
(c) Time Series Analysis: Pandas has powerful support for time series data, making
it easy to perform operations like resampling, time zone handling, and date range
generation.
(d) Data Alignment: Automatic data alignment in Pandas simplifies the process of
combining data from different sources without having to manage the alignment ex-
plicitly.
(e) GroupBy Operations: Pandas provides GroupBy functionality for splitting data,
applying functions, and combining results, which is essential for aggregating and
summarizing data.
(f) Data Import/Export: Pandas can easily read and write data from various file
formats such as CSV, Excel, SQL databases, and more.
(g) Visualization Integration: Pandas integrates well with visualization libraries like
Matplotlib and Seaborn, allowing for quick and effective data visualization.
3. Explain the significance of Matplotlib in data visualization.
Matplotlib is a foundational library for data visualization in Python. Here are seven
points highlighting its significance:
(a) Versatility: Matplotlib can create a wide range of static, interactive, and animated
visualizations, including line plots, bar charts, histograms, scatter plots, and more.
(b) Customization: It offers extensive customization options for plots, including con-
trol over line styles, colors, fonts, and axis properties, allowing for detailed and
tailored visualizations.
(c) Integration: Matplotlib works seamlessly with NumPy, Pandas, and other scientific
libraries, facilitating easy plotting of data structures from these libraries.
(d) Publication Quality: Plots generated by Matplotlib can be of publication quality,
with support for high-resolution output in various formats like PNG, PDF, and SVG.
(e) Interactive Plots: It supports interactive plots that can be embedded in applica-
tions and Jupyter notebooks, enhancing data exploration and presentation.
(f) 3D Plotting: Matplotlib supports 3D plotting, allowing for the visualization of
three-dimensional data and models.
(g) Community and Extensions: With a large community and many extensions,
such as seaborn for statistical plots and basemap for geographical data, Matplotlib
continues to grow and evolve.
4. What are the benefits of using an IDE for Python programming?
Integrated Development Environments (IDEs) offer numerous benefits for Python pro-
gramming, enhancing productivity and efficiency. Here are seven key benefits:
(a) Code Completion: IDEs provide intelligent code completion that suggests and
auto-completes code snippets, function names, and variables, reducing typing effort
and errors.
(b) Syntax Highlighting: They offer syntax highlighting that helps differentiate code
elements like keywords, variables, and strings, improving code readability.
(c) Debugging Tools: Built-in debugging tools allow for setting breakpoints, inspect-
ing variables, and stepping through code to identify and fix errors efficiently.
(d) Project Management: IDEs facilitate project management by organizing code
files, libraries, and dependencies, making it easier to manage large projects.
(e) Version Control Integration: Many IDEs integrate with version control systems
like Git, allowing for seamless tracking of code changes and collaboration.
(f) Refactoring Support: They provide tools for refactoring code, such as renaming
variables and extracting methods, which help improve code quality and maintain-
ability.
(g) Plugins and Extensions: IDEs support plugins and extensions that add additional
functionalities, such as linting, testing frameworks, and language support, to enhance
the development experience.
10
29 root = Tk ()
30 root. title (" Mean ␣Score ")
31
32 label = Label( root , text=" Mean ␣Score ", font =(" Arial", 14))
33 label. pack ( pady =10)
34
35 button = Button ( root , text=" Show ␣Mean ␣Score ", command = show_mean_score , bg="
orange ")
36 button . pack ( pady =10)
37
38 root. mainloop ()
11
12
BTECH
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING
TIME: 3HRS [Link]: 70
Note: 1. Attempt all Sections. If require any missing data; then choose suitably.
SECTION A
BTECH
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING
TIME: 3HRS [Link]: 70
2|Page
BTECH
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING
TIME: 3HRS [Link]: 70
a. Construct a function ret smaller(l) that returns smallest list from a nested list. If 7
two lists have same length then return the first list that is encountered. For
example:
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6 , 7, 8, 9, 10], [11, 12, 13, 14, 15]])
returns [3,4,5]
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [‘a’, ’b’, ’c’, ’d’, 3, 4, 5], [6 , 7, 8, 9, 10], [11,
12, 13, 14, 15]]) returns [6 , 7, 8, 9, 10]
b. Construct following filters: 7
1. Filter all the numbers
2. Filter all the strings starting with a vowel
3. Filter all the strings that contains any of the following noun: Agra,
Ramesh, Tomato, Patna.
Create a program that implements these filters to clean the text.
6. Attempt any one part of the following:
a. Change all the numbers in the file to text. Construct a program for the same. 7
Example:
Given 2 integer numbers, return their product only if the product is equal to or lower
than 10.
And the result should be:
Given two integer numbers, return their product only if the product is equal to or
lower than one zero
b. Construct a program which accepts a sequence of words separated by whitespace 7
as file input. Print the words composed of digits only.
7. Attempt any one part of the following:
a. Construct a program to read [Link] dataset, remove last column and save it in 7
an array. Save the last column to another array. Plot the first two columns.
b. Design a calculator with the following buttons and functionalities like addition, 7
subtraction, multiplication, division and clear.
3|Page
SECTION A
Q1. Attempt all questions in brief.
a. Describe the concept of list comprehension with a suitable example.
Answer: List comprehension provides a concise way to create lists. Ex-
ample:
s q u a r e s = [ x∗∗2 for x in range ( 1 0 ) ]
• Mutable Sequences:
l i s t 1 = [1 , 2 , 3]
list1 [0] = 9
print ( l i s t 1 ) # Output : [ 9 , 2 , 3 ]
• String Concatenation:
s t r 1 = ” He l lo ”
s t r 2 = ”World”
result = str1 + ” - ” + str2
print ( r e s u l t ) # Output : ” H el l o World”
(b) Return a list that starts from the 3rd item to the second last item.
L[ 2 : − 1 ] # Output : [ 3 , 4 , 5 , 6 , 7 , 8 ]
(c) Return a list that has only even position elements of list L to list M.
M = L [ 1 : : 2 ] # Output : [ 2 , 4 , 6 , 8 ]
(d) Return a list that starts from the middle of the list L.
mid = len (L) // 2
L[ mid : ] # Output : [ 5 , 6 , 7 , 8 , 9 ]
(e) Return a list that reverses all the elements starting from element at
index 0 to the middle index only and return the entire list.
L [ : mid ] [ : : − 1 ] + L[ mid : ] # Output : [ 4 , 3 , 2 , 1 , 5 , 6 , 7 , 8 , 9 ]
data = {
’ Food ’ : [ ’ Meat ’ , ’ Banana ’ , ’ Avocados ’ , ’ Sweet - Pot ato es ’ , ’ Spinach ’ ,
’ Ca l o r i e s ’ : [ 2 5 0 , 130 , 140 , 120 , 20 , 20 , 10 , 50 , 40 , 1 9 ] ,
’ Potassium ’ : [ 4 0 , 55 , 20 , 30 , 40 , 32 , 10 , 26 , 25 , 2 0 ] ,
’ Fat ’ : [ 8 , 5 , 3 , 6 , 1 , 1 . 5 , 0 , 2 , 1 . 5 , 2 . 5 ]
}
df = pd . DataFrame ( data )
df . p lo t ( kind=’ bar ’ , x=’ Food ’ , y=[ ’ Ca lo r i e s ’ , ’ Potassium ’ , ’ Fat ’ ] )
p l t . t i t l e ( ’ Nu t r i t i o n a l - I nfo rm a t i o n ’ )
def c h e c k p a s s w o rd va l id i ty ( passwords ) :
va l id p a s s w o rds = [ ]
for password in passwords . s p l i t ( ’ , ’ ) :
i f ( 6 <= len ( password ) <= 12 and
re . se arc h ( ” [ a−z ] ” , password ) and
re . se arch ( ” [ A−Z ] ” , password ) and
re . se arc h ( ” [ 0 −9 ] ” , password ) and
re . se a rc h ( ” [ $#@] ” , password ) ) :
va l id p a s s w o rds . append ( password )
return ’ , ’ . j o i n ( va l id p a s s w o rds )
# Example usage
input pa s s wo r ds = ”ABd1234@1 , aF1#,2w3E∗ , 2 We3345”
print ( c h e c k p a s s w o rd va l id i ty ( input pa s s w o rds ))
• While Loop:
i = 0
while i < 5 :
print ( i ) # Output : 0 1 2 3 4
i += 1
a. Construct a function ret smaller(l) that returns the smallest list from a
nested list.
Answer:
def r e t s m a l l e r ( l i s t s ) :
return min( l i s t s , key=len )
# Example usage
print ( r e t s m a l l e r ( [ [ −2, −1, 0 , 0 . 1 2 , 1 , 2 ] , [ 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 10]
# Output : [ 3 , 4 , 5 ]
print ( r e t s m a l l e r ( [ [ −2, −1, 0 , 0 . 1 2 , 1 , 2 ] , [ ’ a ’ , ’ b ’ , ’ c ’ , ’ d ’ , 3, 4,
# Output : [ 6 , 7 , 8 , 9 , 10 ]
b. Construct the following filters: Filter all the numbers, filter all the strings
starting with a vowel, filter all the strings that contain specific nouns.
Answer:
def f i l t e r n u m b e r s ( seq ) :
return [ x for x in seq i f isinstance ( x , ( int , f loat ) ) ]
def f i l t e r v o w e l s t r i n g s ( seq ) :
return [ x for x in seq i f isinstance ( x , str ) and x [ 0 ] . lower () in ’ ae
# Example usage
seq = [ 1 , ’ apple ’ , ’ orange ’ , ’ banana ’ , 2 , ’ umbrella ’ , ’ e le p h a n t ’ , ’ Agra ’
print ( f i l t e r n u m b e r s ( seq )) # Output : [ 1 , 2 , 3 ]
print ( f i l t e r v o w e l s t r i n g s ( seq )) # Output : [ ’ apple ’ , ’ orange ’ , ’ umbrell
print ( f i l t e r n o u n s ( seq , [ ’ Agra ’ , ’ Ramesh ’ , ’ Tomato ’ , ’ Patna ’ ] ) )
# Output : [ ’ Agra ’ , ’ Ramesh ’ ]
def p l o t c i t i e s ( f i l e ) :
df = pd . re a d c s v ( f i l e )
f i r s t tw o c o lu m n s = df . i l o c [ : , : 2 ] . v a l u e s
las t co lumn = df . i l o c [ : , −1 ] . v a l u e s
p l t . p lo t ( f i r s t tw o c o lu m n s [ : , 0 ] , f i r s t tw o c o lu m n s [ : , 1 ] )
p l t . xla b e l ( ’ Fi r s t - Column ’ )
p l t . y l a b e l ( ’ Second - Column ’ )
p l t . t i t l e ( ’ Fi r s t - Two - Columns - Plot ’ )
p l t . show ()
return f i rs t tw o c o lu m n s , las t co lumn
# Example usage
f i rs t tw o c o lu m n s , las t co l um n = p l o t c i t i e s ( ’ c i t i e s . csv ’ )
def e v a l u a t e ( event ) :
try :
r e s u l t = eval ( e nt ry . get ( ) )
entry . d e l e t e ( 0 , tk .END)
entry . i n s e r t ( tk .END, str ( r e s u l t ))
except :
entry . d e l e t e ( 0 , tk .END)
entry . i n s e r t ( tk .END, ’ Error ’ )
def c l e a r ( event ) :
entry . d e l e t e ( 0 , tk .END)
root = tk . Tk()
entry = tk . Entry ( root )
entry . g r id ( row=0 , column=0 , columnspan=4)
but tons = [
10
root . mainloop ()
11