0% found this document useful (0 votes)
12 views68 pages

Python Unit 1

The document outlines the syllabus and course outcomes for a Python Programming course, detailing the skills students will acquire, such as understanding Python syntax, handling data structures, and applying object-oriented programming concepts. It includes a structured syllabus divided into units covering topics like Python variables, control flow, data types, file operations, and GUI programming. Additionally, it lists recommended textbooks and provides notes on fundamental Python concepts, operators, and flow control mechanisms.

Uploaded by

abhay94111
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views68 pages

Python Unit 1

The document outlines the syllabus and course outcomes for a Python Programming course, detailing the skills students will acquire, such as understanding Python syntax, handling data structures, and applying object-oriented programming concepts. It includes a structured syllabus divided into units covering topics like Python variables, control flow, data types, file operations, and GUI programming. Additionally, it lists recommended textbooks and provides notes on fundamental Python concepts, operators, and flow control mechanisms.

Uploaded by

abhay94111
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BCC302 / BCC402/ BCC302H / BCC402H :

PYTHON PROGRAMMING
Course Outcome ( CO) Bloom’s Knowledge Level (KL)
At the end of course , the student will be able to understand
Interpret the fundamental Python syntax and semantics and be fluent in the use of Python control flow
CO 1 K1, K2
statements.
CO 2 Express proficiency in the handling of strings and functions K1, K2
Determine the methods to create and manipulate Python programs by utilizing the data structures like
CO 3 K3
lists, dictionaries, tuples and sets.
CO 4 Identify the commonly used operations involving file systems and regular expressions. K1, K2
Articulate the Object-Oriented Programming concepts such as encapsulation, inheritance and
CO 5 K2, K3
polymorphism as used in Python
DETAILED SYLLABUS
Unit Topic Lecture
I Introduction to Python: Python variables, Python basic Operators, Understanding python
blocks. Python Data Types, Declaring and using Numeric data types: int, float etc. 03

Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
II python, For loop using ranges, string, list and dictionaries. Use of while loops in python,
05
Loop manipulation using pass, continue, break and else. Programming using Python
conditional and loop blocks.
Python Complex data types: Using string data type and string operations, Defining list
and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building
III blocks of python programs, string manipulation methods, List manipulation. Dictionary 04
manipulation, Programming using string, list and dictionary in-built functions. Python
Functions, Organizing python codes using functions.
Python File Operations: Reading files, Writing files in python, Understanding read
IV functions, read(), readline(), readlines(). Understanding write functions, write() and 04
writelines() Manipulating file pointer using seek Programming, using file operations.
Python packages: Simple programs using the built-in functions of packages matplotlib,
V numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter and 04
PythonProgramming, Tk Widgets, Tkinter examples. Python programming with IDE.

Text books:
1. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition , Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition , Cengage Learning publication
3. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley, 2015
4. Jeeva Jose &[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

Rules for Python variable names:

• Must start with a letter or the underscore character.


• Cannot start with a number.

• Can only contain alpha-numeric characters and underscores (A-z, 0-9, and
).
• Are case-sensitive.

• Reserved words (keywords) cannot be used as variable names.

Global and Local Variables


Global variables are defined outside of any function and can be accessed any-
where in the code. Local variables are defined inside a function and can only
be accessed within that function. For example:

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

Operator Description Example


+ Addition 5+3=8
- Subtraction 5-3=2
* Multiplication 5 * 3 = 15
/ Division 6/3=2
** Exponentiation 2 ** 3 = 8
// Floor Division 7 // 2 = 3

Table 1: Arithmetic Operators

Comparison Operators
Equal: ==
Not equal: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=

Operator Description Example


== Equal to 5 == 5
!= Not equal to 5 != 3
¿ Greater than 5¿3
¡ Less than 3¡5
¿= Greater than or equal to 5 ¿= 5
¡= Less than or equal to 3 ¡= 5

Table 2: Comparison Operators

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: //=

Operator Description Example


= Assign x=5
+= Add and assign x += 3 (x = x + 3)
-= Subtract and assign x -= 3 (x = x - 3)
*= Multiply and assign x *= 3 (x = x * 3)
/= Divide and assign x /= 3 (x = x / 3)
**= Exponentiation and assign x **= 3 (x = x ** 3)
//= Floor division and assign x //= 3 (x = x // 3)

Table 3: Assignment Operators

Bitwise Operators
AND: &
OR: |
XOR: ^
NOT: ~
Zero fill left shift: <<
Signed right shift: >>

Operator Description Example


AND
5 3=1
— OR 5—3=7
3
XOR 5 =6
NOT 5 = -6
¡¡ Zero fill left shift 5 ¡¡ 1 = 10
¿¿ Signed right shift 5 ¿¿ 1 = 2

Table 4: Bitwise Operators

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

Table 5: Logical Operators

Understanding Python Blocks


Python uses indentation to define blocks of code. The standard indentation is
4 spaces (or a tab). For example:

for i in range(5):
print(i)
print("Outside the loop")

Python Data Types


Numeric Types:

• int: Integer numbers


• float: Floating point numbers
• complex: Complex numbers

Sequence Types:
• str: String type

• list: List type


• tuple: Tuple type

• range: Range type

Mapping Type:
• dict: Dictionary type

Set Types:

• set: Set type


• frozenset: Immutable set type

Boolean Type:

• bool: Boolean type, can be True or False


Binary Types:

5
• bytes: Byte type

• bytearray: Byte array type


• memoryview: Memory view type
None Type:

• NoneType: Represents the absence of a value or a null value

Figure 1: An example of Python data types

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.

5. Explain different data types available in Python with examples.

Answers
1. Key features of Python:

• Interpreted
• Object-oriented
• High-level language

6
• Dynamically typed
• Garbage-collected
• Large standard library
• Simple and readable syntax

2. Local and Global Variables:

x = "global"

def my_function():
x = "local"
print(x)

my_function() # Output: local


print(x) # Output: global

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

Indentation is used to define blocks of code. The standard indentation is


4 spaces (or a tab).

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!")

Example 2: Function Definition and Call


def greet(name):
return "Hello, " + name

print(greet("Alice"))

Example 3: Conditional Statements


x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

Example 4: Looping
for i in range(5):
print(i)

Example 5: Working with Lists


my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
Figure 2: *
Thank You!

10
Python Programming Notes

Chapter 2: Python Program Flow Control


Syllabus
• Conditional blocks: if, else, and elif

• Simple for loops in Python


• For loop using ranges, string, list, and dictionaries

• Use of while loops in Python


• Loop manipulation using pass, continue, break, and else

• Programming using Python conditional and loop blocks

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)

2. continue: Skips the current iteration and proceeds to the next.


for i in range(10):
if i % 2 == 0:
continue
print(i)

3. pass: A null operation; does nothing.


for i in range(10):
if i < 5:
pass
else:
print(i)
4. else in loops: Executes a block of code once when the loop condition
is no longer true.
for i in range(5):
print(i)
else:
print("Loop finished")

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

2. Difference Between for and while Loops:

for i in range(5):
print(i)

count = 0
while count < 5:
print(count)
count += 1

3. Purpose of break, continue, and pass Statements:

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)

4. Factorial Program Using for and while Loops:

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)

5. Use of else with Loops:

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:

for num in range(1, 101):


if num % 2 == 0:
print(num)

3. Write a Python program to reverse a given string using a while 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:

num = float(input("Enter a number: "))


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

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

Listing 1: Additional Python Examples

7
July 23, 2024

Syllabus of Chapter 3
• Using string data type and string operations

• Defining list and list slicing

• Use of Tuple data type


• String, List and Dictionary manipulations

• Building blocks of python programs

• String manipulation methods


• List manipulation

• Dictionary manipulation

• Programming using string, list, and dictionary in-built functions


• Python Functions

• Organizing python codes using functions

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.

Listing 1: String Creation


# S t r i n g banane ke teen t a r i k e hain
s t r in g 1 = ’ He l lo ’ # s i n g l e quo te se
s t r in g 2 = ” He l lo ” # do ubl e quote se
s t r in g 3 = ’ ’ ’ H e ll o ’ ’ ’ # t r i p l e quo te se
print ( s tri n g 1 , s t ri n g 2 , s t r in g 3 )

• String Operations:

– Concatenation: Joining two or more strings.


– Repetition: Repeating a string multiple times.
– Slicing: Extracting parts of a string.

Listing 2: String Operations


# S t r i n g Concatenation
s t r 1 = ” He l lo ”
s t r 2 = ”World”
s t r 3 = s t r 1 + ” - ” + s t r 2 # Concatenation
print ( s t r 3 ) # Output : H e ll o World

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

Listing 3: List Creation


# L i s t banane ka t a r i k a
l i s t 1 = [1 , 2 , 3 , 4 , 5]
print ( l i s t 1 ) # Output : [ 1 , 2 , 3 , 4 , 5 ]

2.1 List Operations


• Accessing Elements: Elements are accessed using index positions. In-
dexing starts from 0.

• Slicing: Extracts parts of a list. Syntax: list[start:stop:step] where:

– start - Starting index (inclusive)


– stop - Ending index (exclusive)
– step - Interval between elements

2.2 Types of Slicing


• Basic Slicing: Extracts a part of the list from start to stop.

Listing 4: Basic Slicing


# L i s t ke e le me nts ko s l i c e karna
l i s t 1 = [1 , 2 , 3 , 4 , 5]
print ( l i s t 1 [ 1 : 4 ] ) # Output : [ 2 , 3 , 4 ]

• Slicing with Step: Includes a step value to skip elements.

Listing 5: Slicing with Step


# L i s t ke e le me nt s ko s t ep ke s aat h s l i c e karna
l i s t 1 = [1 , 2 , 3 , 4 , 5]
print ( l i s t 1 [ 0 : 5 : 2 ] ) # Output : [ 1 , 3 , 5 ]

• Negative Indexing: Uses negative indices to access elements from the


end of the list.

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 ]

• Omitting Start and Stop: Omitting start or stop includes elements


from the beginning or to the end.

Listing 7: Omitting Start and Stop


# S t ar t aur s top omit karne par l i s t ke e l e me nts ko s l i c e karna
l i s t 1 = [1 , 2 , 3 , 4 , 5]
print ( l i s t 1 [ : 3 ] ) # Output : [ 1 , 2 , 3]
print ( l i s t 1 [ 2 : ] ) # Output : [ 3 , 4 , 5]
print ( l i s t 1 [ : : 2 ] ) # Output : [ 1 , 3 , 5]

Listing 8: List Operations


# List S l i c i n g
li st2 = [1 , 2 , 3 , 4 , 5]
print ( l i s t 2 [ 0 : 3 ] ) # Output : [ 1 , 2 , 3 ]
print ( l i s t 2 [ 2 : ] ) # Output : [ 3 , 4 , 5 ]

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.

3.1 Tuple Creation

Listing 9: Tuple Creation


# Tuple banane ka t a r i k a
t upl e 1 = ( 1 , 2 , 3 , 4 , 5 ) # Tuple with in t e g e r s
print ( t upl e 1 ) # Output : ( 1 , 2 , 3 , 4 , 5 )

t upl e 2 = ( ” apple ” , ” banana” , ” c he rry ” ) # Tuple with s t r i n g s


print ( t upl e 2 ) # Output : ( ’ appl e ’ , ’ banana ’ , ’ c her r y ’)

t upl e 3 = ( 1 , 2 , 3 , ( 4 , 5 )) # Tuple c o n t a i ni n g a not her t u p l e


print ( t upl e 3 ) # Output : ( 1 , 2 , 3 , ( 4 , 5 ))

# Tuple wi t h o u t p a r e n t h e s e s ( not recommended , but p o s s i b l e )


t upl e 4 = 1 , 2 , 3 , 4
print ( t upl e 4 ) # Output : ( 1 , 2 , 3 , 4 )

3.2 Accessing Tuple Elements


• Indexing: Elements in a tuple can be accessed using index positions,
starting from 0.

• Negative Indexing: Negative indices can be used to access elements


from the end of the tuple.

Listing 10: Accessing Tuple Elements


# Tuple ke e le me nt s ko acc e s s karna
t upl e 1 = ( 10 , 20 , 30 , 40 , 50 )
print ( t upl e 1 [ 0 ] ) # Output : 10 # Pehla element
print ( t upl e 1 [ 2 ] ) # Output : 30 # Teesra element

# N e g at i v e i n d e x i n g se e l e me nts ko acc e s s karna


print ( t upl e 1 [ − 1 ] ) # Output : 50 # Last element
print ( t upl e 1 [ − 3 ] ) # Output : 30 # Third l a s t element

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

Listing 11: Tuple Slicing


# Tuple ko s l i c e karna
t upl e 1 = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 )
print ( t upl e 1 [ 2 : 5 ] ) # Output : ( 3 , 4 , 5 ) # Elements from index 2 to 4
print ( t upl e 1 [ : 4 ] ) # Output : ( 1 , 2 , 3 , 4 ) # Elements from s t a r t to index 3
print ( t upl e 1 [ 5 : ] ) # Output : ( 6 , 7 , 8 , 9 ) # Elements from inde x 5 to end
print ( t upl e 1 [ : : 3 ] ) # Output : ( 1 , 4 , 7 ) # Every 3 rd element

3.4 Tuple Operations


• Concatenation: Combining two or more tuples using the + operator.
• Repetition: Repeating the elements of a tuple using the * operator.
• Membership Test: Checking if an element is in the tuple using the in
operator.

Listing 12: Tuple Operations


# Tuple c o nc a t e n a t i o n aur re p e t i t i o n
t upl e 1 = ( 1 , 2 , 3 )
t upl e 2 = ( 4 , 5 , 6 )
print ( t upl e 1 + t upl e 2 ) # Output : ( 1 , 2 , 3 , 4 , 5 , 6 ) # Concatenation

print ( t upl e 1 ∗ 3 ) # Output : ( 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 )


# Repetition

# 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

3.5 Tuple Immutability


• Immutable Nature: Tuples cannot be changed once created. Any at-
tempt to modify a tuple will result in an error.

Listing 13: Tuple Immutability


# Tuple ko modify karne k i k o s h i s h
t upl e 1 = ( 1 , 2 , 3 , 4 )
# t u pl e 1 [ 1 ] = 5 # Ye l i n e e r r o r de gi : TypeError : ’ t u p l e ’ o b j e c t does not s uppor

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.

Listing 14: String Manipulation Methods


# S t r i n g Ma n i p ul ati o n Methods
s t r 6 = ” He l lo - World”

# 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

# Replace ’ World ’ with ’ Python ’


print ( s t r 6 . r e p la c e ( ”World” , ” Python” )) # Output : H e ll o Python

# Find the i nd ex o f ’ World ’


print ( s t r 6 . f in d ( ”World” )) # Output : 6

# Find a s u b s t r i ng t hat i s not pre s e nt


print ( s t r 6 . f in d ( ” Java” )) # Output : −1

4.2 List Manipulations


• Common Methods:

– append(item): Adds an item to the end of the list.


– extend(iterable): Extends the list by appending elements from an
iterable.
– insert(index, item): Inserts an item at a specified index.
– remove(item): Removes the first occurrence of the specified item.
– pop(index): Removes and returns the item at the specified index.
If no index is specified, it removes and returns the last item.

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.

Listing 15: List Manipulations


# L i s t M anipulat io ns
my list = [1 , 2 , 3 , 4 , 5]

# Append item to the end


m y l i s t . append ( 6 )
print ( m y l i s t ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 ]

# Extend l i s t with a not her l i s t


m y l i s t . extend ( [ 7 , 8 ] )
print ( m y l i s t ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]

# 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 ]

# Remove the f i r s t o c c u rr e n c e o f item


m y l i s t . remove ( 10 )
print ( m y l i s t ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]

# Pop item from a s p e c i f i c index


popped item = m y l i s t . pop ( 3 )
print ( popped item ) # Output : 4
print ( m y l i s t ) # Output : [ 1 , 2 , 3 , 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 ]

# Find in dex o f an item


in d e x o f 6 = m y l i s t . index ( 6 )
print ( in d e x o f 6 ) # Output : 2

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.

Listing 16: Dictionary Manipulations


# D i c t i o n ar y Manipulat ions
my dict = { ’ name ’ : ’ Ali c e ’ , ’ age ’ : 25 , ’ c i t y ’ : ’New - York ’ }

# 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 a l l items ( key−value p a i r s )


print ( my dict . items ( ) ) # Output : d i c t i t e m s ( [ ( ’ name ’ , ’ Ali c e ’) , ( ’ age ’ , 25 ) , ( ’

# 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

# Update d i c t io na ry with anot her d i c t io na ry


my dict . update ({ ’ email ’ : ’ alice@ e xam ple . com ’ , ’ age ’ : 26 })
print ( my dict ) # Output : { ’ name ’ : ’ Ali c e ’ , ’ age ’ : 26 , ’ c i t y ’ : ’New York ’ , ’ emai

# Remove item with s p e c i f i e d key


removed value = my dict . pop ( ’ c i t y ’ )
print ( removed value ) # Output : New York

9
print ( my dict ) # Output : { ’ name ’ : ’ A li c e ’ , ’ age ’ : 26 , ’ email ’ : ’ alice@ e xample . c

# Remove and r e t ur n the l a s t item


l a s t i t e m = my dict . popitem ()
print ( l a s t i t e m ) # Output : ( ’ email ’ , ’ alice@ example . com ’)
print ( my dict ) # Output : { ’ name ’ : ’ Ali c e ’ , ’ age ’ : 26}

# 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()‘

Listing 17: List Manipulation


# L is t M anip ulat io n Methods
l i s t 3 = [1 , 2 , 3 , 4 , 5]
l i s t 3 . append ( 6 ) # append () method
print ( l i s t 3 ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 ]

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 ]

l i s t 3 . remove ( 1 0 ) # remove () method


print ( l i s t 3 ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 ]

11
4.5 Dictionary Manipulation Methods
• Common Methods: ‘keys()‘, ‘values()‘, ‘items()‘, ‘update()‘

Listing 18: Dictionary Manipulation


# D i c t i o n a r y Ma ni p u l ati o n Methods
d i c t 1 = {”a” : 1 , ”b” : 2 , ” c” : 3}
print ( d i c t 1 . keys ( ) ) # Output : d i c t k e y s ( [ ’ a ’ , ’ b ’ , ’ c ’ ] )
print ( d i c t 1 . va l ue s ( ) ) # Output : d i c t v a l u e s ( [ 1 , 2 , 3 ] )
print ( d i c t 1 . items ( ) ) # Output : d i c t i t e m s ( [ ( ’ a ’ , 1 ) , ( ’ b ’ , 2 ) , ( ’ c ’ , 3 ) ] )

d i c t 1 . update ({ ”d” : 4 }) # update () method


print ( d i c t 1 ) # Output : { ’ a ’ : 1 , ’ b ’ : 2 , ’ c ’ : 3 , ’ d ’ : 4}

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

Listing 19: Creating Functions


# Function banane ka t a r i k a
def g r e e t ( name ) :
”””
Yeh f u n c t i o n ek naam l e t a hai aur g re e t i ng p r int k ar t a hai .
”””
print ( f ” Hello , - {name } ! ” )

g r e e t ( ” Alic e ” ) # Output : Hello , Al i c e !

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

6.2 Question 2: List Manipulation


Question: Ek list [1, 2, 3, 4, 5] mein 6 ko add kaise karte hain aur 3 ko remove
kaise karte hain?
Answer:
l i s t 4 = [1 , 2 , 3 , 4 , 5]
l i s t 4 . append ( 6 )
print ( l i s t 4 ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 ]

l i s t 4 . remove ( 3 )
print ( l i s t 4 ) # Output : [ 1 , 2 , 4 , 5 , 6 ]

6.3 Question 3: Dictionary Manipulation


Question: Ek dictionary d = { ’a’: 1, ’b’: 2 } mein ek naya key-value
pair ’c’: 3 kaise add karte hain aur key ’b’ ko kaise delete karte hain?
Answer:
d = { ’ a ’ : 1 , ’ b ’ : 2}
d[ ’c’] = 3
print ( d) # Output : { ’ a ’ : 1 , ’ b ’ : 2 , ’ c ’ : 3}

del d [ ’ b ’ ]
print ( d) # Output : { ’ a ’ : 1 , ’ c ’ : 3}

6.4 Question 4: Function Definition and Calling


Question: Ek function multiply(a, b) define karo jo do numbers ko multiply
kar ke result return kare, aur is function ko call karke result print karo.
Answer:
def m ul t i pl y ( a , b ) :
”””
Do numbers ko m ul t ip l y karke r e s u l t r e t ur n k ar t a hai .
”””
return a ∗ b

14
r e s u l t = m ul t i pl y ( 4 , 5 )
print ( r e s u l t ) # Output : 20

6.5 Question 5: List Comprehension


Question: Ek list [1, 2, 3, 4, 5] ke har element ko 2 se multiply karke ek
new list kaise banate hain?
Answer:
o r i g i n a l l i s t = [1 , 2 , 3 , 4 , 5]
n e w l i s t = [ x ∗ 2 for x in o r i g i n a l l i s t ]
print ( n e w l i s t ) # Output : [ 2 , 4 , 6 , 8 , 10 ]

15
16
Additional Examples

Listing 20: Additional Python Examples


# Python Complex Data Types and O pe rati o ns

# 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 !

# St ri n g s l i c i n g : ’ World ’ part ko e xt r a c t karna


s l i c e s t r = str1 [ 7 : 1 2 ]
p r in t (” S l i c e d St ri n g : ” , s l i c e s t r ) # Output : World

# St ri n g m a ni pul ati o n : Upper cas e aur Lower c ase co nve rs io n


u p p e r s tr = s t r 1 . upper ()
p r in t (” Uppercase S t r i n g : ” , u p p e r s tr ) # 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 ]

# Lis t s l i c i n g : Pehle 3 e leme nt s ko e xtr a c t karna


s l i c e l i s t = my list [ : 3 ]
p r in t (” S l i c e d Lis t : ” , s l i c e l i s t ) # Output : [ 1 , 2 , 3 ]

# Lis t m a ni pulati o n : Element ko add aur remove karna


m y l i s t . append ( 6 ) # 6 ko l i s t ke end mein add k a rte hain
p r in t (” Lis t a f t e r Append : ” , m y l i s t ) # Output : [ 1 , 2 , 3 , 4 , 5 , 6 ]

m y l i s t . remove ( 3 ) # 3 ko l i s t se remove ka rte hain


p r in t (” Lis t a f t e r Remove : ” , m y l i s t ) # Output : [ 1 , 2 , 4 , 5 , 6 ]

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

# Tuple s l i c i n g : Pehle 2 e leme nt s ko e xtr a c t karna


s l i c e t u p l e = my tuple [ : 2 ]
p r in t (” Sl i c e d Tuple : ” , s l i c e t u p l e ) # Output : ( 10 , 20 )

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}

# Di c t io na ry m a ni pul ati o n : Naya key−value p a i r add karna aur ek key ko remove ka


my dict [ ’ c i ty ’ ] = ’New York ’ # New key−value p a i r add karna
p r in t (” D i c t i o n a r y a f t e r Adding Key : ” , my dict ) # Output : { ’ name ’ : ’ Alice ’ , ’ age

d e l my dict [ ’ age ’ ] # Age key ko d i c t io n a r y se remove karna


p r in t (” D i c t i o n a r y a f t e r Removing Key : ” , my dict ) # Output : { ’ name ’ : ’ Alice ’ , ’ c

# 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

# O r g a niz ing Code us ing Functions


# Ek f u n c t io n banate hain jo l i s t ke e le me nts ko double kare
def do ubl e e l e m e nt s ( l s t ) :
”””
Lis t ke har element ko double ka rta hai .
”””
r et u r n [ x ∗ 2 f o r x in l s t ]

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

Syllabus for Chapter 4


• File Input/Output Operations

• Different Modes to Open a File

• Reading Files in Python

• Writing Files in Python

• Manipulating File Pointer using seek()

Chapter 4: Python File Operation


A file is a container in computer storage devices used for storing data. File In-
put/Output (I/O) operations in Python allow you to read from and write to files
on your computer. Python provides built-in functions and methods to perform file
I/O operations.

Different Modes to Open a File in Python


• r: Open a file for reading (default).

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

• t: Open in text mode (default).

Downloaded by Abhay Chaudhary (abhay94111@[Link])


• b: Open in binary mode.
• +: Open a file for updating (reading and writing).

Reading Files in Python


Reading files in Python involves opening a file and then using various methods to
read its contents. Here’s a basic overview:

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Working with Binary Files: To read binary files (such as images), open the
file in binary mode ("rb") and use the read() method to read bytes.
1 with open (" image . jpg", " rb") as file :
2 image_data = file . read ()
Remember to handle exceptions that may occur while reading files, such as
FileNotFoundError if the file does not exist.

Writing Files in Python


Writing files in Python involves opening a file in write mode ("w"), appending
mode ("a") or binary write mode ("wb") and then using various methods to write
data to the file. Here’s a basic overview:

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Working with Binary Files: To write binary data to a file (such as images),
open the file in binary write mode ("wb") and use the write() method to write
bytes.
1 with open (" image . jpg", " wb") as file :
2 file . write ( image_data )

Remember to handle exceptions that may occur while writing files, such as
IOError if the file cannot be written to.

Manipulating File Pointer using Seek in Python


In Python, the seek() method is used to change the current position of the file
pointer within a file. The file pointer is an indicator that points to the current
position in the file where the next read or write operation will take place. The
seek() method takes two arguments: an offset and a reference point.

1 file . seek( offset , whence )

• 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

Important Questions and Answers

Q1. What are the different modes to open a file in Python?


• r: Open a file for reading (default).

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


• a: Open a file for appending at the end without truncating it. Creates a new
file if it does not exist.
• t: Open in text mode (default).
• b: Open in binary mode.
• +: Open a file for updating (reading and writing).

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

Code Examples with Comments (Hinglish)


Example 1: Reading a File
1 # Example 1: File ko read karna
2 with open (" example . txt", " r") as file :
3 content = file . read () # Yeh pura file content read karega
4 pr i nt ( content) # Content ko print karega

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Example 2: Writing to a File
1 # Example 2: File me data likhna
2 with open (" example . txt", " w") as file :
3 file . write (" Hello , world !\ n") # Yeh line file me likhega
4 lines = [" Line 1\ n", " Line 2\ n"]
5 file . writelines( lines) # Multiple lines file me likhega

Example 3: Using seek()


1 # Example 3: File pointer ko move karna
2 with open (" example . txt", " r") as file :
3 file . seek (10) # File pointer ko 10 bytes aage move karega
4 content = file . read () # Pointer ke baad ka content read
karega
5 pr i nt ( content) # Content ko print karega

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming: Chapter 5 Notes

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

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.

1.1.1 Example: Bar Chart


1 import matplotlib . pyplot as plt
2

3 cat egories = [’ Category ␣A’, ’ Category ␣B’, ’ Category ␣C’]


4 values = [23 , 17 , 35]
5

6 plt. bar( categories , values , color=’ skyblue ’)


7 plt. title (’ B a r␣Chart ␣E xam ple ’)
8 plt. xlabel( ’ Catego ries ’)
9 plt. ylabel(’ Values ’)
10

11 plt. show ()

Output:

1.1.2 Example: Pie Chart


1 import matplotlib . pyplot as plt
2

3 labels = [’ Section ␣1 ’, ’ Section ␣2 ’, ’ Section ␣3 ’]


4 sizes = [15 , 30 , 45]
5 colors = [’ gold ’, ’ lightcoral ’, ’ lightskyblue ’]
6

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:

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

1.2 NumPy
NumPy is a fundamental package for scientific computing in Python, providing support for arrays and
matrices.

1.2.1 Example: Creating a 2D Array and Calculating its Mean


1 import numpy as np
2

3 arr = np. array ([[1 , 2 , 3], [4 , 5 , 6], [7 , 8 , 9]])


4 print(" Array :")
5 print( arr)
6

7 mean = np. mean ( arr)


8 print("\ n Mean :", mean )

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.

1.3.1 Example: Reading a CSV File and Displaying its Content


1 import pandas as pd
2

3 # Assume ’ data . csv ’ contains the following data :


4 # Name , Age , City
5 # Alice , 30 , New York
6 # Bob , 25 , San Francis co
7 # Charlie , 35 , Chicago
8

9 df = pd. read_csv (’ data . csv ’)

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

10 print(" First␣few ␣rows :")


11 print( df. head ())
12

13 print("\ n Summary ␣s t at ist ics :")


14 print( df. describe ())

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

2 GUI Programming with Tkinter


Tkinter is a standard Python interface to the Tk GUI toolkit. It is a simple and intuitive library used
to create GUI applications.

2.1 Basic Tkinter Example


1 from tkinter import *
2

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

2.2 Widgets in Tkinter


- Label: Used to display text or images. - Button: Adds buttons to your application. - Entry: Used to
input single-line text. - Text: Allows multi-line text editing. - Frame: Acts as a container to organize
other widgets.

2.2.1 Example: Using a Button and Label


1 from tkinter import *
2

3 def on_button_click ():


4 label. config ( text=" Button ␣Clicked !", fg=" blue ")
5

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

3 Python Programming with IDE


An Integrated Development Environment (IDE) enhances Python programming by providing features
like code completion, debugging tools, and project management capabilities.

3.1 Popular IDEs


-
PyCharm: A full-featured IDE specifically for Python. -
Visual Studio Code: A lightweight, extensible editor with Python support. -
IDLE: Comes bundled with Python and is great for beginners.

3.2 How to Use an IDE


1. Install an IDE: Choose one that supports Python.
2. Create a New Project: Organize your code into a workspace.
3. Write Your Code: Use features like syntax highlighting and code completion.
4. Run Your Code: Execute directly from the IDE.
5. Debugging: Use tools to find and fix errors.
6. Project Management: Organize your files and manage dependencies.

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

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.

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

(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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

Comprehensive Python Program


Here is a comprehensive Python program that utilizes Matplotlib, NumPy, Pandas, and Tkinter:
1 import numpy as np
2 import pandas as pd
3 import mat plotlib . pyplot as plt
4 from tkinter import *
5

6 # Create a Data Frame using Pandas


7 data = {’ Name ’: [’ Alice ’, ’ Bob ’, ’ Charlie ’],
8 ’ Age ’: [23 , 25 , 27],
9 ’ Score ’: [85 , 90 , 88]}
10

11 df = pd. Data Frame ( data )


12 print( df)
13

14 # Calculate the mean of the Scores using Num Py


15 mean_score = np. mean ( df[’ Score ’])
16 print("\ n Mean ␣Score :", mean_score )
17

18 # Create a bar chart using Matplotlib


19 plt. bar( df[’ Name ’], df[’ Score ’], colo r= ’ cyan ’)
20 plt. title (’ Student␣S co res ’)
21 plt. xlabel(’ Name ’)
22 plt. ylabel(’ Score ’)
23 plt. show ()
24

25 # Create a simple GUI using Tkinter


26 def s ho w _mean_score ():
27 label. config ( text=f" Mean ␣Score : ␣{ mean_score :.2 f}")
28

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Python Programming Chapter 5 Notes

12

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Printed Page: 1 of 3
Subject Code: BCC302
Roll No:

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

1. Attempt all questions in brief.


Q no. Question Marks
a. Describe the concept of list comprehension with a suitable example 2
b. Differentiate between / and // operator with an example 2
c. Compute the output of the following python code: 2
def count(s):
for str in [Link]():
s = “&”.join(str)
return s
print(count(“Python is fun to learn.”))
d. How to use the functions defined in [Link] in [Link] 2
e. Describe the difference between linspace and argspace. 2
f. Explain why the program generates an error. 2
x = [‘12’, ’hello’, 456]
x[0] *= 3
x[1][1]=’bye’
g. Describe about different functions of matplotlib and pandas. 2
SECTION B

2. Attempt any three of the following:


a. Illustrate Unpacking tuples, mutable sequences, and string concatenation with 7
examples
b. Illustrate different list slicing constructs for the following operations on the 7
following list:
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
1. Return a list of numbers starting from the last to second item of the list
2. Return a list that start from 3rd item to second last item.
3. Return a list that has only even position elements of list L to list M.
4. Return a list that starts from the middle of the list L.
5. Return a list that reverses all the elements starting from element at index
0 to middle index only and return the entire list.
Divide each element of the list by 2 and replace it with the remainder.
c. Construct a function perfect_square(number) that returns a number if it is a perfect 7
square otherwise it returns -1.
For example:
perfect_square(1) returns 1
perfect_square (2) returns -1
d. Construct a program to change the contents of the file by reversing each character 7
separated by comma:
Hello!!
Output
H,e,l,l,o,!,!
e. Construct a plot for following dataset using matplotlib : 7
1|Page

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Printed Page: 2 of 3
Subject Code: BCC302
Roll No:

BTECH
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING
TIME: 3HRS [Link]: 70

Food Calories Potassium fat


Meat 250 40 8
Banana 130 55 5
Avocados 140 20 3
Sweet
Potatoes 120 30 6
Spinach 20 40 1
Watermelon 20 32 1.5
Coconut
water 10 10 0
Beans 50 26 2
Legumes 40 25 1.5
Tomato 19 20 2.5
SECTION C
3. Attempt any one part of the following:
a. Determine a python function removenth(s,n) that takes an input a string and an 7
integer n>=0 and removes a character at index n. If n is beyond the length of s,
then whole s is returned. For example:
removenth(“MANGO”,1) returns MNGO
removenth(“MANGO”,3) returns MANO

b. Construct a program that accepts a comma separated sequence of words as input 7


and prints the words in a comma-separated sequence after sorting them
alphabetically.
Suppose the following input is supplied to the program:
without, hello, bag, world
Then, the output should be:
bag, hello, without, world
4. Attempt any one part of the following:
a. A website requires the users to input username and password to register. Construct 7
a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will
check them according to the above criteria. Passwords that match the criteria are
to be printed, each separated by a comma
b. Explore the working of while, and for loop with examples. 7
5. Attempt any one part of the following:

2|Page

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Printed Page: 3 of 3
Subject Code: BCC302
Roll No:

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Odd Semester Question Paper Solution
Discussion

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

This generates a list of squares of numbers from 0 to 9.


b. Differentiate between / and // operator with an example.
Answer: The / operator performs floating-point division, while // per-
forms integer (floor) division.
print ( 7 / 2 ) # Output : 3 . 5
print ( 7 // 2 ) # Output : 3

c. Compute the output of the following Python code:


def count ( s ) :
for str in s . s p l i t ( ) :
s = ”&” . j o i n ( str )
return s
print ( count ( ” Python - i s - fun - to - l e a rn . ” ))

Answer: The output is ”Python”.


d. How to use the functions defined in [Link] in [Link]
Answer: Use the import statement to include functions from [Link]:
import l i b r a r y
l i b r a r y . function name ()

e. Describe the difference between linspace and arange.


Answer: linspace generates evenly spaced numbers over a specified inter-
val, while arange generates numbers in a specified range with a specified
step.

Downloaded by Abhay Chaudhary (abhay94111@[Link])


import numpy as np
np . l i n s p a c e ( 0 , 1 , 5 ) # Output : [ 0 . 0 . 25 0.5 0 . 75
1.]
np . arange ( 0 , 1 , 0 . 2 5 ) # Output : [ 0 . 0 . 25 0.5 0 . 75 ]

f. Explain why the program generates an error:


x = [ ’ 12 ’ , ’ h e l l o ’ , 45 6 ]
x [ 0 ] ∗= 3
x [ 1 ] [ 1 ] = ’ bye ’

Answer: The error occurs because strings are immutable in Python, so


you cannot assign a new value to an index in a string.

g. Describe different functions of matplotlib and pandas.


Answer: Matplotlib is used for plotting graphs, e.g., [Link](). Pandas
is used for data manipulation, e.g., [Link]().

Downloaded by Abhay Chaudhary (abhay94111@[Link])


SECTION B
Q2. Attempt any three of the following:

a. Illustrate Unpacking tuples, mutable sequences, and string concatenation


with examples.
Answer:
• Unpacking Tuples:
a , b , c = (1 , 2 , 3)
print ( a , b , c ) # Output : 1 2 3

• 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. Illustrate different list slicing constructs for operations on the following


list: L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Answer:
(a) Return a list of numbers starting from the last to the second item of
the list.
L[:: −1][1:] # Output : [ 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ]

(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 ]

Downloaded by Abhay Chaudhary (abhay94111@[Link])


(f) Divide each element of the list by 2 and replace it with the remainder.
[ x % 2 for x in L] # Output : [ 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 ]

c. Construct a function perfect square(number) that returns a number if it


is a perfect square otherwise it returns -1.
Answer:
import math
def p e r f e c t s q u a r e ( number ) :
i f math . i s q r t ( number )∗∗ 2 == number :
return number
else :
return −1
# Example usage
print ( p e r f e c t s q u a r e ( 1 ) ) # Output : 1
print ( p e r f e c t s q u a r e ( 2 ) ) # Output : −1

d. Construct a program to change the contents of the file by reversing each


character separated by comma.
Answer:
def r e v e r s e f i l e c o n t e n t s ( f i le na me ) :
with open( f i le na m e , ’ r ’ ) as f i l e :
co nte nts = f i l e . read ()
r e ve r s e d c o n te n t s = ’ , ’ . j o i n ( co nte nts [ : : − 1 ] )
with open( f i l e na m e , ’w ’ ) as f i l e :
f i l e . w r i te ( r e ve r s e d c o n te n t s )
# Example usage
r e v e r s e f i l e c o n t e n t s ( ’ example . txt ’ )

e. Construct a plot for the following dataset using matplotlib.


Answer:
import m a tp lo t l ib . py plot as p l t
import pandas as pd

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


p l t . xl a b e l ( ’ Food ’ )
p l t . y l a b e l ( ’ Values ’ )
p l t . show ()

Downloaded by Abhay Chaudhary (abhay94111@[Link])


SECTION C
Q3. Attempt any one part of the following:

a. Determine a python function removenth(s, n) that takes an input a string


and an integer n¿=0 and removes a character at index n. If n is beyond
the length of s, then whole s is returned.
Answer:
def removenth ( s , n ) :
i f n >= len ( s ) :
return s
return s [ : n ] + s [ n + 1 : ]
# Example usage
print ( removenth ( ”MANGO” , 1 )) # Output : ”MNGO”
print ( removenth ( ”MANGO” , 3 )) # Output : ”MANO”

b. Construct a program that accepts a comma separated sequence of words


as input and prints the words in a comma-separated sequence after sorting
them alphabetically.
Answer:
def s o rt w o rds ( words ) :
w o r d l i s t = words . s p l i t ( ’ , - ’ )
w o r d l i s t . s o r t ()
return ’ , - ’ . j o i n ( w o r d l i s t )
# Example usage
input words = ” without , - h e l lo , - bag , - world ”
print ( s o rt w o rds ( input words )) # Output : ” bag , he l l o , witho ut , world ”

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Q4. Attempt any one part of the following:

a. Construct a program to check the validity of password input by users


based on given criteria.
Answer:
import re

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

b. Explore the working of while and for loop with examples.


Answer:
• For Loop:
for i in range ( 5 ) :
print ( i ) # Output : 0 1 2 3 4

• While Loop:
i = 0
while i < 5 :
print ( i ) # Output : 0 1 2 3 4
i += 1

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Q5. Attempt any one part of the following:

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

def f i l t e r n o u n s ( seq , nouns ) :


return [ x for x in seq i f isinstance ( x , str ) and any( noun in x for n

# 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 ’ ]

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Q6. Attempt any one part of the following:

a. Change all the numbers in the file to text.


Answer:
def number to text ( f i le na me ) :
num text = {
’ 0 ’ : ’ zero ’ , ’ 1 ’ : ’ one ’ , ’ 2 ’ : ’ two ’ , ’ 3 ’ : ’ thre e ’ , ’ 4 ’ : ’ f o ur ’ ,
’ 5 ’ : ’ f i v e ’ , ’ 6 ’ : ’ s i x ’ , ’ 7 ’ : ’ seven ’ , ’ 8 ’ : ’ e ig h t ’ , ’ 9 ’ : ’ nine ’
}
with open( f i l e na m e , ’ r ’ ) as f i l e :
co nte nts = f i l e . read ()
for num, te xt in num text . items ( ) :
co nte nts = co nte nts . r e p la c e (num, te xt )
with open( f i l e na m e , ’w ’ ) as f i l e :
f i l e . w r i te ( co nte nts )
# Example usage
num ber to text ( ’ example . txt ’ )

b. Construct a program which accepts a sequence of words separated by


whitespace as file input. Print the words composed of digits only.
Answer:
def p r i n t d i g i t w o r d s ( f i le name ) :
with open( f i l e na m e , ’ r ’ ) as f i l e :
co nte nts = f i l e . read ()
words = co nte nts . s p l i t ()
d ig i t w o r d s = [ word for word in words i f word . i s d i g i t ( ) ]
print ( ’ - ’ . j o i n ( d ig i t w o r d s ))
# Example usage
p r i n t d i g i t w o r d s ( ’ example . txt ’ )

Downloaded by Abhay Chaudhary (abhay94111@[Link])


Q7. Attempt any one part of the following:

a. Construct a program to read [Link] dataset, remove last column and


save it in an array. Save the last column to another array. Plot the first
two columns.
Answer:
import pandas as pd
import m a tp lo t l ib . py plot as p l t

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

b. Design a calculator with buttons and functionalities like addition, sub-


traction, multiplication, division, and clear.
Answer:
import t k i n t e r as tk

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

Downloaded by Abhay Chaudhary (abhay94111@[Link])


( ’7 ’ , 1, 0) , ( ’8 ’ , 1, 1) , ( ’9 ’ , 1, 2) , ( ’/ ’ , 1, 3) ,
( ’4 ’ , 2, 0) , ( ’5 ’ , 2, 1) , ( ’6 ’ , 2, 2) , ( ’∗ ’ , 2, 3) ,
( ’1 ’ , 3, 0) , ( ’2 ’ , 3, 1) , ( ’3 ’ , 3, 2) , ( ’− ’ , 3, 3) ,
( ’0 ’ , 4, 0) , ( ’C ’ , 4, 1) , ( ’=’ , 4, 2) , ( ’+’ , 4, 3)
]

for ( text , row , column ) in but tons :


button = tk . Button ( root , te xt=te xt )
button . g r id ( row=row , column=column )
i f te xt == ’=’ :
button . bind ( ’<Button−1> ’ , e v a l ua t e )
e l i f te xt == ’C ’ :
button . bind ( ’<Button−1> ’ , c l e a r )
else :
button . bind ( ’<Button−1> ’ , lambda event , t=te xt : entry . i n s e r t ( tk .

root . mainloop ()

11

Downloaded by Abhay Chaudhary (abhay94111@[Link])

You might also like