0% found this document useful (0 votes)
45 views61 pages

Python Programming

Uploaded by

sem3rdvideo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views61 pages

Python Programming

Uploaded by

sem3rdvideo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 61

DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”

Venus Python Programming 1

Unit 1

Basics of Python Programming syntax

Basics of Python Programming Syntax: A Concise Guide


Python, known for its readability and simplicity, employs a syntax designed to be intuitive and easy to learn.
Here’s a breakdown of the fundamental elements:
1. Variables and Data Types:
 Variables: Think of variables as containers holding data. You assign values to them using the = operator.
Example: name = “Alice”
 Data Types: Python supports various data types, each with its own characteristics:
 Integers (int): Whole numbers like 10, -5, 0.
Numbers with decimal points like 3.14, -2.5.
 Strings (str): Sequences of characters enclosed in single or double quotes like “Hello” or ‘World’.
 Booleans (bool): Represent truth values, either True or False.
 Type Casting: You can convert data types using built-in functions like int(), float(), and str().
2. Operators:
 Arithmetic Operators: Used for mathematical operations:
+ (addition), - (subtraction), (multiplication), / (division), % (modulo - remainder), (exponentiation), // (floor
division).
 Comparison Operators: Used for comparing values:
== (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or
equal to).
 Logical Operators: Used to combine or modify boolean expressions:
and, or, not.
 Assignment Operators: Used to assign values to variables:
= (assignment), += (add and assign), -= (subtract and assign), *=, /=, %=, *=, //=.
3. Control Flow:
 Conditional Statements: Used to execute different code blocks based on conditions:
if, elif, else.
Example:
if age >= 18:
print(“You are an adult.”)
elif age >= 13:
print(“You are a teenager.”)
else:
print(“You are a child.”)
Loops: Used to repeat code blocks:
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 2

‘for‘ loop: Iterates over a sequence of items.


‘while‘ loop: Executes code as long as a condition is true.
Example:
for i in range(5):
print(i)
i=0
while i < 5:
print(i)
i += 1
4. Functions:
 Defining Functions: Use the def keyword to create reusable blocks of code:
Example:
def greet(name):
print(“Hello, “ + name + “!”)
greet(“Alice”)
Arguments: Functions can accept input values called arguments.
Return Values: Functions can return output values using the return keyword.
5. Data Structures:
 Lists: Ordered collections of items enclosed in square brackets [].
 Tuples: Ordered, immutable collections enclosed in parentheses ().
 Dictionaries: Unordered collections of key-value pairs enclosed in curly braces {}.
 Sets: Unordered collections of unique items enclosed in curly braces {}.
6. Input and Output:
 Input: Use the input() function to get user input.
 Output: Use the print() function to display output.
7. Indentation:
 Crucial: Python uses indentation to define code blocks.
 Consistent: Use four spaces for each indentation level.
8. Comments:
 Single-line comments: Start with a hash symbol #.
 Multi-line comments: Enclose comments within triple quotes.
9. Modules and Packages:
 Modules: Python files containing functions and variables.
 Packages: Collections of modules organized into directories.
 Import: Use the import keyword to access modules and packages.
10. Exception Handling:
 Errors: Python raises exceptions to handle unexpected events.
 ‘try...except‘: Use this block to handle exceptions gracefully.
11. Object-Oriented Programming (OOP):
 Classes: Blueprints for creating objects.
 Objects: Instances of classes.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 3

 Methods: Functions associated with objects.


12. Standard Library:
 Extensive: Python comes with a rich standard library offering a wide range of modules for various tasks.

Building Blocks of Python: Character Set, Tokens, Variables, Lvalues, Rvalues, and Comments
Understanding the fundamental building blocks of Python is crucial for writing effective code. This guide
delves into the character set, tokens, variables, Lvalues and Rvalues, and the importance of comments.
1. Python Character Set:
The foundation of any programming language is its character set, which defines the basic symbols used. Python’s
character set includes:
 Letters: Uppercase (A-Z) and lowercase (a-z) letters from the English alphabet.
 Digits: 0-9.
 Special Characters: These include symbols like +, -, *, /, =, !, @, #, $, %, ^, &, *, (, ), {, }, [, ], :, ;, <, >, ?, /, |,
~, “, ‘, and whitespace characters (space, tab, newline).
 Unicode Support: Python uses Unicode to represent characters from various languages, ensuring broader
compatibility and internationalization.
2. Python Tokens:
Tokens are the smallest meaningful units in Python code. They are like the words in a sentence, conveying
specific meaning. Python recognizes several types of tokens:
 Identifiers: Names given to variables, functions, classes, and other entities. They must start with a letter or
underscore (_) and can contain letters, digits, and underscores.
 Keywords: Reserved words with predefined meanings in Python, such as if, else, for, while, def, class, etc.
 Literals: Constant values directly represented in code, like numbers (10, 3.14), strings (“Hello”), and booleans
(True, False).
 Operators: Symbols that perform operations on operands, such as +, -, *, /, =, ==, !=, etc.
 Punctuators: Special characters used for syntax and structure, like parentheses (), brackets [], braces {}, commas
,, colons :, etc.
3. Variables:
 Variables are like containers that hold data. They act as placeholders for values that can change during program
execution.
 Declaration: In Python, you don’t explicitly declare the data type of a variable. The interpreter infers it based
on the assigned value.
 Assignment: You assign values to variables using the = operator.
Example:
name = “Alice” # Assigns the string “Alice” to the variable ‘name’
age = 25 # Assigns the integer 25 to the variable ‘age’
4. L values and R values:
 Lvalue (Left-hand value): Represents a memory location where a value can be stored. It is the target of an
assignment operation.
 Rvalue (Right-hand value): Represents the value itself, which is assigned to the Lvalue.
Example:
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 4

x = 10 # Here, ‘x’ is the Lvalue, and ‘10’ is the Rvalue.


5. Comments:
 Comments are explanatory notes within your code that are ignored by the interpreter. They are essential for
improving code readability and understanding.
 Single-line comments: Start with a hash symbol (#).
 Multi-line comments: Enclose comments within triple quotes (“”” “””).
Example:
# This is a single-line comment.
This is a multi-line comment.
It can span multiple lines.

Python Data Types: A Comprehensive Guide


Python offers a rich set of data types, each designed to represent different kinds of information. Understanding
these data types is essential for writing effective and expressive code. This guide provides a comprehensive
overview of Python’s core data types, emphasizing their characteristics and distinctions.
1. Number Data Types:
 Integers (int): Represent whole numbers without decimal points.
Example: 10, -5, 0.
 Floating-point numbers (float): Represent numbers with decimal points.
Example: 3.14, -2.5, 1.0.
Complex numbers (complex): Represent numbers with both real and imaginary parts.
Example: 2 + 3j, -1 - 2j.
2. Boolean Data Type:
 Booleans (bool): Represent truth values, either True or False.
 Used for conditional statements and logical operations.
3. Sequence Data Types:
Sequences: Ordered collections of items.
Strings (str): Immutable sequences of characters enclosed in single or double quotes.
Example: “Hello”, ‘World’.
 Lists (list): Mutable sequences of items enclosed in square brackets.
Example: [1, 2, 3], [“apple”, “banana”, “cherry”].
 Tuples (tuple): Immutable sequences of items enclosed in parentheses.
Example: (1, 2, 3), (“apple”, “banana”, “cherry”).
4. None Data Type:
 None: Represents the absence of a value.
 Used as a placeholder or to indicate that a variable has no assigned value.
5. Mapping Data Type:
 Dictionaries (dict): Unordered collections of key-value pairs enclosed in curly braces.
 Keys must be immutable (like strings, numbers, or tuples).
 Values can be of any data type.
 Example: {“name”: “Alice”, “age”: 25, “city”: “New York”}.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 5

6. Mutable vs. Immutable Data Types:


 Mutable Data Types: Values can be modified after creation.
 Lists, dictionaries, sets.
 Immutable Data Types: Values cannot be changed after creation. New objects are created when modifications
are attempted.
 Integers, floats, strings, tuples.
Key Considerations:
 Data Type Choice: Selecting the appropriate data type for your data is crucial for efficient and accurate
processing.
 Operations: Different data types support different operations. For example, you can add integers but not strings.
 Mutability: Understanding mutability is important for managing data integrity and preventing unintended side
effects.
Example:
# Number data types
age = 25 # integer
height = 1.75 # float
complex_num = 2 + 3j # complex
# Boolean data type
is_active = True
# Sequence data types
name = “Alice” # string
fruits = [“apple”, “banana”, “cherry”] # list
coordinates = (10, 20) # tuple
# None data type
user_input = None
# Mapping data type
person = {“name”: “Alice”, “age”: 25, “city”: “New York”} # dictionary
Python Operators, Expressions, Statements, and Input/Output: A Comprehensive Guide
This guide delves into the fundamental concepts of operators, expressions, statements, type conversion, and
input/output in Python, providing a comprehensive understanding of how these elements work together to
form the foundation of Python programming.
1. Operators:
 Operators are special symbols that perform specific operations on values called operands. Python offers a wide
range of operators categorized as follows:
 Arithmetic Operators: Used for mathematical calculations:
‘+‘ (addition), ‘-‘ (subtraction), ‘ב (multiplication), ‘/‘ (division), ‘%‘ (modulo - remainder), “ (exponentiation),
‘//‘ (floor division).
 Relational Operators: Used for comparing values:
‘==‘ (equal to), ‘!=‘ (not equal to), ‘>‘ (greater than), ‘<‘ (less than), ‘>=‘ (greater than or equal to), ‘<=‘ (less
than or equal to).
 Logical Operators: Used to combine or modify boolean expressions:
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 6

‘and‘, ‘or‘, ‘not‘.


 Assignment Operator: Used to assign values to variables:
‘=‘ (assignment).
 Augmented Assignment Operators: Combine an arithmetic operator with the assignment operator:
‘+=‘, ‘-=‘, ‘=‘, ‘/=‘, ‘%=‘, ‘=‘, ‘//=‘ (e.g., ‘x += 5‘ is equivalent to ‘x = x + 5‘).
2. Expressions:
 Expressions are combinations of values, variables, operators, and function calls that evaluate to a single value.
 Example: ‘2 + 3 * 4‘ is an expression that evaluates to ‘14‘.
3. Statements:
 Statements are instructions that Python executes. They can be simple or compound.
 Simple Statements: Perform a single action, like assigning a value to a variable (‘x = 10‘).
 Compound Statements: Consist of multiple statements grouped together, often using indentation to define
blocks of code (e.g., ‘if‘ statements, ‘for‘ loops).
4. Precedence of Operators:
 Python follows a specific order of precedence to evaluate expressions.
 PEMDAS (Parentheses, Exponents, Multiplication and Division, Addition and Subtraction): This mnemonic
helps remember the order:
Parentheses have the highest precedence.
Exponents are evaluated next.
Multiplication and division have equal precedence and are evaluated from left to right.
Addition and subtraction have equal precedence and are evaluated from left to right.
5. Expression Evaluation:
 Python evaluates expressions step-by-step, following the precedence rules.
 Example: ‘2 + 3 * 4‘ is evaluated as follows:
1. ‘3 × 4 = 12‘ (Multiplication has higher precedence)
2. ‘2 + 12 = 14‘ (Addition is evaluated next)
6. Type Conversion:
 Sometimes, you need to convert values from one data type to another.
 Python provides built-in functions for type conversion:
 ‘int()‘ (convert to integer), ‘float()‘ (convert to float), ‘str()‘ (convert to string).
 Example: ‘int(“10”)‘ converts the string ‘“10”‘ to the integer ‘10‘.
7. Input/Output:
 Input: Use the ‘input()‘ function to get user input from the console.
 Output: Use the ‘print()‘ function to display output to the console.
Example:
python
# Arithmetic operation
result = 2 + 3 * 4 # Evaluates to 14
# Relational comparison
is_greater = 10 > 5 # Evaluates to True
# Logical operation

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 7

is_true = True and False # Evaluates to False


# Assignment
x = 10
# Augmented assignment
x += 5 # Equivalent to x = x + 5
# Type conversion
age = int(input(“Enter your age: “)) # Get age as an integer
# Output
print(“Your age is:”, age)

    Exercises    
Multiple Choice Question
1. In Python, the characters that can be used to write a program are known as the __________.
(a) keywords (b) character set (c) tokens
Ans.(b) character set Explanation: The character set defines the valid characters in a Python program.
2. A variable in Python is an example of a(n) __________.
(a) function (b) identifier (c) object
Ans.(b) identifier Explanation: Variables are identifiers used to reference data in Python.
3. The left side of an assignment is called __________.
(a) Rvalue (b) Lvalue (c) Operand
Ans.(b) Lvalue Explanation: Lvalue refers to a location in memory that can be assigned a value.
4. To leave a comment in Python, you use the __________ symbol.
(a) // (b) # (c) /*
Ans.(b) # Explanation: The hash symbol (#) is used to create single-line comments in Python.
5. An integer, float, and complex are examples of __________ data types.
(a) mutable (b) numeric (c) string
Ans.(b) numeric Explanation: These are classified as numeric data types in Python.
6. A __________ can hold multiple items in an ordered collection.
(a) set (b) list (c) dictionary
Ans.(b) list Explanation: Lists are mutable sequences that can store multiple items.
7. The value None in Python represents __________.
(a) a string (b) a null value (c) a boolean
Ans.(b) a null value Explanation: None signifies the absence of a value or a null value in Python.
8. A dictionary in Python is a __________ type.
(a) mutable (b) immutable (c) sequential
Ans.(a) mutable Explanation: Dictionaries can be modified after creation.
9. Strings in Python are __________ data types.
(a) mutable (b) immutable (c) iterable
Ans.(b) immutable Explanation: Strings cannot be changed after they are created.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 8

10. The operator + is used for __________.


(a) division (b) addition (c) multiplication
Ans.(b) addition Explanation: The + operator adds two numeric values or concatenates strings.
11. The operator == is used to __________.
(a) assign values (b) compare equality (c) concatenate strings
Ans.(b) compare equality Explanation: The == operator checks if two values are equal.
12. The expression x += 1 is an example of __________.
(a) arithmetic operation (b) augmented assignment (c) variable declaration
Ans.(b) augmented assignment Explanation: It adds 1 to the current value of x using a shorthand syntax.
13. A statement in Python is __________.
(a) an instruction (b) a variable (c) a comment
Ans.(a) an instruction Explanation: A statement represents a single action or command in Python code.
14. The expression 5 * (3 + 2) evaluates to __________.
(a) 25 (b) 15 (c) 10
Ans.(a) 25 Explanation: The parentheses indicate that addition occurs before multiplication.
15. The function input() is used for __________.
(a) displaying output (b) taking user input (c) declaring variables
Ans.(b) taking user input Explanation: input() retrieves input from the user.
16. The float value 3.14 is an example of a __________.
(a) integer (b) complex number (c) floating-point number
Ans.(c) floating-point number Explanation: Floating-point numbers represent decimal values.
17. The operation x // y performs __________ division.
(a) floor (b) integer (c) decimal
Ans.(a) floor Explanation: Floor division returns the largest integer less than or equal to the division result.
18. The len() function is used to find the __________ of a sequence.
(a) type (b) length (c) value
Ans.(b) length Explanation: len() returns the number of items in a sequence.
19. The statement x is None checks if __________.
(a) x is a string (b) x has a value (c) x is null
Ans.(c) x is null Explanation: This checks if x is equal to None.
20. The expression not True evaluates to __________.
(a) True (b) False (c) None
Ans.(b) False Explanation: The not operator negates the boolean value.
21. The expression 5 < 3 evaluates to __________.
(a) True (b) False (c) None
Ans.(b) False Explanation: This comparison is false since 5 is not less than 3.
22. In Python, 3 + 2.0 evaluates to __________.
(a) 5 (b) 5.0 (c) 5.00
Ans.(b) 5.0 Explanation: The result is a floating-point number due to type conversion.
23. The operation % is used to find the __________.
(a) sum (b) product (c) modulus
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 9

Ans.(c) modulus Explanation: The modulus operator returns the remainder of a division.
24. The statement x = 5 assigns the value __________ to x.
(a) 5 (b) ‘5’ (c) None
Ans.(a) 5 Explanation: This assigns the integer value 5 to the variable x.
25. The expression x or y returns __________.
(a) the first truthy value (b) the second value (c) None
Ans.(a) the first truthy value Explanation: The or operator returns the first operand that evaluates to True.
26. The keyword used to define a function is __________.
(a) define (b) func (c) def
Ans.(c) def Explanation: def is used to create a function in Python.
27. A tuple is defined by __________.
(a) square brackets (b) curly braces (c) parentheses
Ans.(c) parentheses Explanation: Tuples are enclosed in parentheses ( ).
28. The statement print(type(3.14)) would output __________.
(a) <class ‘int’> (b) <class ‘float’> (c) <class ‘str’>
Ans.(b) <class ‘float’> Explanation: This confirms that 3.14 is of type float.
29. The operator ** is used for __________.
(a) exponentiation (b) addition (c) subtraction
Ans.(a) exponentiation Explanation: The ** operator raises a number to the power of another.
30. A set in Python is a __________ collection.
(a) ordered (b) unordered (c) indexed
Ans.(b) unordered Explanation: Sets do not maintain any order among their elements.
31. The expression x in y checks if __________.
(a) y is a number (b) y contains x (c) x is a string
Ans.(b) y contains x Explanation: It tests for membership of x in y.
32. The statement x = 1, 2, 3 creates a __________.
(a) list (b) tuple (c) dictionary
Ans.(b) tuple Explanation: This creates a tuple with three elements.
33. The operator >= is an example of a __________ operator.
(a) logical (b) arithmetic (c) relational
Ans.(c) relational
34. The function sorted([3, 1, 2]) returns __________.
(a) [1, 2, 3] (b) [3, 1, 2] (c) [2, 3, 1]
Ans.(a) [1, 2, 3] Explanation: sorted() returns a new sorted list.

Important Question
Q1.Define a token in Python. List and describe its types with examples.
Q2. What is the difference between a keyword and an identifier? Provide examples.
Q3. What is the purpose of comments in Python? Write an example showing both single-line and multi-line
comments.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 10

Q4. Explain Lvalue and Rvalue with a suitable Python example.


Q5.What are the rules for naming variables in Python? Write a Python code with valid and invalid variable
names.
Q6.Differentiate between mutable and immutable data types in Python. Provide examples.
Q7.Explain the difference between a list and a tuple with examples.
Q8.Explain Boolean data type with an example.
Q9.List and explain the arithmetic operators in Python with examples.
Q10.What are logical operators in Python? Write a program to demonstrate the use of `and`, `or`, and `not`.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 11

Unit 2

conditional and iterative statements


Controlling the Flow: Conditional and Iterative Statements in Python
Conditional and iterative statements are the backbone of any programming language, enabling you to create
dynamic and intelligent programs. These statements allow you to control the flow of execution, making decisions
based on conditions and repeating code blocks as needed.
1. Conditional Statements:
 Conditional statements allow you to execute different blocks of code based on whether a condition is true or
false.
 ‘if‘ Statement: Executes a block of code if the condition is true.
Syntax:
if condition:
# Code to execute if condition is true
 ‘elif ’ Statement: Used to check additional conditions if the previous if or elif conditions are false.
Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
 ‘else‘ Statement: Executes a block of code if all previous conditions are false.
Syntax:
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false
Example:
age = int(input(“Enter your age: “))
if age >= 18:
print(“You are an adult.”)
elif age >= 13:
print(“You are a teenager.”)
else:
print(“You are a child.”)
2. Iterative Statements (Loops):
 Iterative statements, or loops, allow you to repeat a block of code multiple times.
 ‘for‘ Loop: Iterates over a sequence of items (like a list, tuple, string, or range).
Syntax:
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 12

for item in sequence:


# Code to execute for each item in the sequence
 ‘while‘ Loop: Executes a block of code as long as a condition is true.
Syntax:
while condition:
# Code to execute as long as the condition is true
Example:
# Using a for loop to print numbers from 1 to 5
for i in range(1, 6):
print(i)
# Using a while loop to print numbers from 1 to 5
i=1
while i <= 5:
print(i)
i += 1
Key Considerations:
 Indentation: Python uses indentation to define code blocks within conditional and iterative statements.
Consistent indentation is crucial for correct execution.
 Loop Control Statements:
‘break’: Exits the loop immediately.
‘continue’: Skips the current iteration and continues to the next.
 Nested Loops: You can create nested loops by placing one loop inside another, allowing you to iterate over
multiple sequences or conditions.
Example of Nested Loops:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Conditional Statements in Python: Making Decisions with if, elif, and else
Conditional statements are the building blocks of decision-making in programming. They allow your code to
execute different blocks of instructions based on whether certain conditions are met. Python provides three
main types of conditional statements:
1. Simple ‘if‘ Statement:
 The simplest form of conditional statement, the if statement executes a block of code only if a given condition
is true.
 Syntax:
if condition:
# Code to execute if condition is True
Example:
age = 25
if age >= 18:
print(“You are eligible to vote.”)

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 13

In this example, the code inside the if block will only execute if the variable age is greater than or equal to 18.
2. ‘if-else‘ Statement:
 The if-else statement provides an alternative path of execution if the if condition is false.
 Syntax:
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
Example:
is_raining = True
if is_raining:
print(“Take an umbrella.”)
else:
print(“Enjoy the sunshine.”)
Here, if is_raining is True, the first print statement will execute. Otherwise, the second print statement will
execute.
3. ‘if-elif-else‘ Statement:
 The if-elif-else statement allows you to check multiple conditions sequentially. It executes the first block of
code whose condition is true and skips the rest.
 Syntax:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
elif condition3:
# Code to execute if condition3 is True
else:
# Code to execute if all conditions are False
Example:
score = 85
if score >= 90:
print(“Excellent!”)
elif score >= 80:
print(“Very good!”)
elif score >= 70:
print(“Good.”)
else:
print(“Try harder next time.”)
This example checks the score against different thresholds and prints a corresponding message.
Key Considerations:
 Indentation: Python uses indentation to define code blocks within conditional statements. Consistent indentation
is crucial for correct execution.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 14

 Logical Operators: You can combine multiple conditions using logical operators like and, or, and not to create
more complex conditions.
 Nested Conditions: You can nest conditional statements inside other conditional statements to create more
intricate decision-making logic.
Example of Nested Conditions:
age = 20
is_student = True
if age >= 18:
if is_student:
print(“You are eligible for a student discount.”)
else:
print(“You are an adult.”)
else:
print(“You are not yet an adult.”)
Iterative Statements in Python: Repeating Code with Loops
Iterative statements, or loops, are essential for automating repetitive tasks in programming. They allow you to
execute a block of code multiple times, either for a specific number of iterations or until a certain condition is
met. Python offers two primary loop constructs: while loops and for loops, along with supporting features like
the range function, break and continue statements, and the ability to nest loops.
1. ‘while’ Loop:
 The while loop repeatedly executes a block of code as long as a given condition remains true.
 Syntax:
while condition:
# Code to execute as long as the condition is True
Example:
count = 1
while count <= 5:
print(count)
count += 1
This loop prints numbers from 1 to 5. The condition count <= 5 is checked before each iteration. As long as it’s
true, the code inside the loop executes, incrementing count by 1 in each iteration.
2. ‘for’ Loop:
 The for loop iterates over a sequence of items, executing a block of code for each item in the sequence.
 Syntax:
for item in sequence:
# Code to execute for each item in the sequence
Example:
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
This loop iterates over the fruits list and prints each fruit name.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 15

3. ‘range’ Function:
 The range function generates a sequence of numbers.
 Syntax:
range(start, stop, step)
Example:
for i in range(1, 6):
print(i)
This loop prints numbers from 1 to 5 (excluding 6). range(1, 6) generates a sequence of numbers starting from
1 and ending at 5 (exclusive), with a step of 1.
4. ‘break’ and ‘continue‘ Statements:
 ‘break’: Exits the loop immediately, regardless of the loop condition.
 ‘continue’: Skips the current iteration of the loop and continues to the next iteration.
Example:
for i in range(1, 11):
if i == 5:
break # Exit the loop when i is 5
print(i)
for i in range(1, 11):
if i % 2 == 0:
continue # Skip even numbers
print(i)
5. Nested Loops:
 You can place one loop inside another to create nested loops.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
This code prints all possible combinations of i and j where both range from 1 to 3.
Key Considerations:
 Indentation: Python uses indentation to define code blocks within loops. Consistent indentation is crucial for
correct execution.
 Infinite Loops: Be careful not to create infinite loops by ensuring the loop condition eventually becomes false.
 Loop Control Statements: break and continue statements provide fine-grained control over loop execution.

    Exercises    
Multiple Choice Question
1. In Python, a variable must start with a __________.
(a) Number (b) Letter (c) Special Character
Ans.(b) Letter Explanation: Variables in Python must begin with a letter or an underscore.
2. The Python character set includes __________.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 16

(a) Only ASCII characters (b) ASCII and Unicode characters


(c) Only letters and numbers
Ans.(b) ASCII and Unicode characters
3. An example of an immutable data type is __________.
(a) List (b) Dictionary (c) Tuple
Ans.(c) Tuple Explanation: Tuples cannot be changed after they are created, making them immutable.
4. A variable assigned the value of 10 is an example of an __________.
(a) Lvalue (b) Rvalue (c) Keyword
Ans.(a) Lvalue Explanation: An Lvalue refers to a storage location in memory.
5. The __________ operator is used to perform addition in Python.
(a) - (b) + (c) *
Ans.(b) + Explanation: The + operator is used for addition in arithmetic operations.
6. A __________ statement is used to add comments in Python code.
(a) # (b) // (c) --
Ans.(a) # Explanation: The # symbol denotes a comment in Python.
7. The expression 5 > 3 evaluates to __________.
(a) True (b) False (c) None
Ans.(a) True Explanation: 5 is greater than 3, so the expression is true.
8. The __________ type is used to represent a sequence of characters.
(a) List (b) String (c) Dictionary
Ans.(b) String Explanation: Strings are used for sequences of characters in Python.
9. The output of the expression 10 / 3 is __________ in Python 3.
(a) 3 (b) 3.33 (c) 3.0
Ans.(b) 3.33 Explanation: In Python 3, division returns a float.
10. The __________ operator assigns a value to a variable.
(a) + (b) = (c) ==
Ans.(b) = Explanation: The = operator is used for assignment.
11. A __________ is a collection of key-value pairs in Python.
(a) List (b) Tuple (c) Dictionary
Ans.(c) Dictionary Explanation: Dictionaries store data in key-value format.
12. The expression 'Hello' + ' World' results in __________.
(a) Hello World (b) HelloWorld (c) 'Hello World'
Ans.(a) Hello World Explanation: String concatenation combines two strings.
13. The type conversion function for converting a number to a string is __________.
(a) str() (b) int() (c) float()
Ans.(a) str() Explanation: str() converts a number into a string format.
14. In Python, the __________ operator checks if two values are equal.
(a) = (b) == (c) !=
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 17

Ans.(b) == Explanation: The == operator is used to compare values for equality.


15. The expression 3 + 4 * 2 evaluates to __________ due to operator precedence.
(a) 14 (b) 11 (c) 10
Ans.(b) 11 Explanation: Multiplication is evaluated before addition.
16. The __________ data type can hold True or False values.
(a) String (b) Boolean (c) Integer
Ans.(b) Boolean Explanation: The Boolean type represents truth values.
17. A __________ can be used to create a sequence of numbers in a loop.
(a) Set (b) Range (c) List
Ans.(b) Range Explanation: The range function generates a sequence of numbers.
18. The __________ operator is used for logical conjunction in Python.
(a) & (b) and (c) &&
Ans.(b) and Explanation: The and operator is used to combine Boolean conditions.
19. A variable holding the value of a floating-point number is of type __________.
(a) int (b) float (c) complex
Ans.(b) float Explanation: Float data type represents decimal numbers.
20. To check if a variable x is not None, you can use the __________ operator.
(a) is (b) != (c) is not
Ans.(c) is not Explanation: The is not operator checks for identity comparison.
21. The __________ statement executes a block of code only if a condition is true.
(a) for (b) if (c) while
Ans.(b) if Explanation: The if statement controls flow based on a condition.
22. An if-else statement allows for __________ paths of execution.
(a) One (b) Two (c) Three
Ans.(b) Two Explanation: It provides an alternative path if the condition is false.
23. In a while loop, the loop continues until the __________ evaluates to false.
(a) Condition (b) Variable (c) Statement
Ans.(a) Condition Explanation: The loop checks the condition before each iteration.
24. The __________ statement is used to exit a loop prematurely.
(a) continue (b) break (c) pass
Ans.(b) break Explanation: The break statement terminates the loop immediately.
25. In Python, a loop that runs a fixed number of times is typically a __________ loop.
(a) while (b) for (c) do
Ans.b) for Explanation: The for loop iterates over a sequence.
26. The __________ statement skips the current iteration in a loop.
(a) continue (b) break (c) exit
Ans.(a) continue Explanation: Continue causes the loop to skip to the next iteration.
27. A nested loop is defined as a loop inside __________.
(a) a function (b) another loop (c) a conditional statement
Ans.(b) another loop Explanation: Nested loops allow multiple layers of iteration.
28. The condition in an if statement must evaluate to a __________ value.
(a) Boolean (b) Integer (c) String
Ans.(a) Boolean Explanation: Only true or false values are valid for condition evaluation.
29. The syntax for a for loop includes the __________ keyword.
(a) iterate (b) for (c) loop
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 18

Ans.(b) for Explanation: The for keyword begins the for loop structure.
30. The __________ function generates numbers within a specified range for loops.
(a) list() (b) range() (c) seq()
Ans.(b) range() Explanation: The range function produces a sequence of numbers.
31. In a while loop, the __________ is evaluated before the loop executes.
(a) Condition (b) Statement (c) Body
Ans.(a) Condition Explanation: The loop checks its condition before executing its body.
32. The expression 'if x > 5:' is an example of a __________ statement.
(a) conditional (b) iterative (c) assignment
Ans.(a) conditional Explanation: This statement makes a decision based on x's value.
33. A __________ loop runs at least once, even if the condition is false.
(a) for (b) while (c) do-while
Ans.(c) do-while Explanation: A do-while loop ensures at least one execution.
34. The control structure that executes a block of code multiple times is called a __________.
(a) condition (b) loop (c) function
Ans.(b) loop Explanation: Loops repeat code execution based on conditions.
35. An example of a simple if statement is __________.
(a) if x: (b) if (x > 10): (c) if x == 5:
Ans.(a) if x: Explanation: This checks if x is truthy.
36. The keyword used to define the end of a loop block is __________.
(a) end (b) pass (c) colon (:)
Ans.(c) colon (:) Explanation: The colon indicates the start of an indented block.
37. The __________ statement can be used to implement a fallback mechanism in conditions.
(a) else (b) continue (c) break
Ans.(a) else Explanation: Else executes when the if condition is false.
38. The syntax for breaking out of a loop is __________.
(a) exit (b) stop (c) break
Ans.(c) break Explanation: The break keyword terminates the loop.
39. To create a loop that iterates over a list, you can use __________.
(a) for (b) if (c) while
Ans.(a) for Explanation: The for loop is designed to iterate over iterable objects.
40. The statement 'while True:' creates an __________ loop.
(a) infinite (b) conditional (c) local
Ans.(a) infinite Explanation: It continues indefinitely unless interrupted.
41. The primary purpose of the 'break' statement in a loop is to __________.
(a) skip to the next iteration (b) terminate the loop (c) repeat the loop
Ans.(b) terminate the loop Explanation: Break exits the loop based on a condition.
42. A loop that executes a specific number of times uses __________ in its declaration.
(a) condition (b) range (c) limit
Ans.(b) range Explanation: The range function specifies how many iterations to perform.
43. The keyword __________ indicates a condition that can be checked repeatedly.
(a) if (b) else (c) while
Ans.(c) while Explanation: While allows for repeated execution based on a condition.
44. In nested loops, the __________ loop completes before the outer loop resumes.
(a) inner (b) outer (c) main

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 19

Ans.(a) inner Explanation: Inner loops must finish before the outer loop continues.
45. Using __________ in a loop allows for an immediate iteration skip.
(a) break (b) return (c) continue
Ans.(c) continue Explanation: Continue skips the rest of the current loop iteration.
46. A condition checking multiple cases can use the __________ statement.
(a) if-else (b) switch (c) elif
Ans.(c) elif Explanation: Elif checks additional conditions after an if statement.
47. A loop that counts from 1 to 10 can be created with __________.
(a) while 10: (b) for i in range(1, 11): (c) if i < 10:
Ans.(b) for i in range(1, 11): Explanation: This syntax iterates from 1 to 10 inclusively.
48. The purpose of the ‘pass’ statement in Python is to __________.
(a) skip a block of code (b) terminate the program (c) implement a loop
Ans.(a) skip a block of code Explanation: Pass acts as a placeholder when no action is needed.
49. The syntax for a multi-condition if-elif-else statement ends with __________.
(a) endif (b) colon (:) (c) end
Ans.(b) colon (:) Explanation: A colon indicates the start of the block that follows.
50. In a for loop, the __________ variable represents the current item in each iteration.
(a) iterator (b) index (c) loop variable
Ans.(c) loop variable Explanation: The loop variable takes on each value in the iterable.

Important Question
Q1. Explain the syntax of an `if` statement in Python with an example.
Q2. Differentiate between `if-else` and `if-elif-else` statements with suitable examples.
Q3. What is the significance of indentation in Python's conditional statements?
Q4. Write a Python program to check whether a number entered by the user is positive, negative, or zero.
Q5. Write a program to determine if a year entered by the user is a leap year or not.
Q6. Explain the difference between a `while` loop and a `for` loop.
Q7. What is the role of the `range()` function in loops? Illustrate with an example.
Q8. Define the `break` and `continue` statements. How are they different?
Q9.Write a program to print the first 10 natural numbers using a `while` loop.
Q10.Write a program to calculate the factorial of a number using a `while` loop.
Q11.Write a program to print all the even numbers between 1 and 20 using a `for` loop.
Q12.Write a program to calculate the sum of all elements in a list using a `for` loop.
Q13.Write a program to display the numbers from 10 to 1 in reverse order using the `range()` function.
Q14. Write a program that iterates through numbers from 1 to 10 and breaks the loop when the number 5 is
encountered.
Q15.Write a program that prints all numbers from 1 to 10 except for multiples of 3 using the `continue`
statement.
Q16.Write a program to display the following pattern using nested loops:
*
**
***
****
Q17.Write a program to display a multiplication table from 1 to 5 using nested loops.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 20

Unit 3

string, list, tUPles, set and dictionary

Python Data Structures: Strings, Lists, Tuples, Sets, and Dictionaries


Python provides a variety of built-in data structures that allow you to organize and manipulate data efficiently.
These data structures offer different characteristics and functionalities, making them suitable for various
programming tasks. Here’s a comprehensive guide to the most commonly used data structures in Python:
1. Strings (str):
 Definition: Immutable sequences of characters enclosed in single or double quotes.
Example: “Hello World”, ‘Python’.
Key Features:
 Immutable: Once created, the contents of a string cannot be changed directly.
 Ordered: Characters are stored in a specific order, allowing for indexing and slicing.
 Iteratable: You can loop through each character in a string.
 Methods: Python offers a rich set of string methods for operations like concatenation, formatting, searching,
and replacing.
2. Lists (list):
 Definition: Mutable sequences of items enclosed in square brackets.
Example: [1, 2, 3], [“apple”, “banana”, “cherry”].
Key Features:
 Mutable: Elements in a list can be modified, added, or removed after creation.
 Ordered: Items are stored in a specific order, allowing for indexing and slicing.
 Heterogeneous: Lists can contain elements of different data types.
 Methods: Python provides methods for adding, removing, sorting, and searching elements in a list.
3. Tuples (tuple):
 Definition: Immutable sequences of items enclosed in parentheses.
Example: (1, 2, 3), (“apple”, “banana”, “cherry”).
Key Features:
 Immutable: Elements in a tuple cannot be changed after creation.
 Ordered: Items are stored in a specific order, allowing for indexing and slicing.
 Heterogeneous: Tuples can contain elements of different data types.
 Use Cases: Tuples are often used to store data that should not be modified, such as coordinates or database
records.
4. Sets (set):
 Definition: Unordered collections of unique items enclosed in curly braces.
Example: {1, 2, 3}, {“apple”, “banana”, “cherry”}.
Key Features:

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 21

 Unordered: Elements are not stored in a specific order.


 Unique: Sets cannot contain duplicate items.
 Mutable: Elements can be added or removed after creation.
 Methods: Sets offer methods for performing operations like union, intersection, difference, and membership
testing.
5. Dictionaries (dict):
 Definition: Unordered collections of key-value pairs enclosed in curly braces.
Example: {“name”: “Alice”, “age”: 25, “city”: “New York”}.
Key Features:
 Unordered: Key-value pairs are not stored in a specific order.
 Mutable: Key-value pairs can be modified, added, or removed after creation.
 Keys: Keys must be immutable (like strings, numbers, or tuples).
 Values: Values can be of any data type.
 Use Cases: Dictionaries are ideal for representing data that is naturally associated with key-value pairs, such
as configuration settings, user profiles, or data from a database.
Choosing the Right Data Structure:
 Strings: For storing and manipulating text data.
 Lists: For storing ordered collections of items that may need to be modified.
 Tuples: For storing ordered collections of items that should not be modified.
 Sets: For storing unique items and performing set operations.
 Dictionaries: For storing key-value pairs and accessing data efficiently by key.
Strings in Python: Manipulating Text with Indexing, Operations, and Built-in Functions
Strings are fundamental data types in Python, representing sequences of characters. They are versatile and offer
a wide range of operations for manipulating text data. This guide delves into key string concepts, including
indexing, operations, traversal using loops, and built-in functions.
1. Indexing:
 Strings are ordered sequences, meaning characters are stored in a specific order.
 You can access individual characters using their index, starting from 0 for the first character.
 Syntax: string[index]
Example:
message = “Hello”
print(message[0]) # Output: H
print(message[2]) # Output: l
 Negative Indexing: You can also access characters from the end using negative indices, starting from -1 for
the last character.
Example:
message = “Hello”
print(message[-1]) # Output: o
print(message[-3]) # Output: l
2. String Operations:
 Concatenation: Joining two or more strings together using the + operator.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 22

Example:
greeting = “Hello”
name = “Alice”
full_message = greeting + “ “ + name
print(full_message) # Output: Hello Alice
 Repetition: Repeating a string multiple times using the * operator.
Example:
star_pattern = “*” * 5
print(star_pattern) # Output: P+þP+þP+þ*
 Membership: Checking if a substring exists within a string using the in operator.
Example:
text = “This is a sample text.”
print(“sample” in text) # Output: True
 Slicing: Extracting a portion of a string using the slicing operator [:].
Example:
message = “Hello World”
print(message[0:5]) # Output: Hello
print(message[6:]) # Output: World
3. Traversing a String using Loops:
 You can iterate through each character in a string using a for loop.
Example:
message = “Hello”
for char in message:
print(char)
This loop prints each character of the message string on a separate line.
4. Built-in String Functions:
 Python provides a rich set of built-in functions for working with strings.
 ‘len()’: Returns the length of a string.
 ‘upper()‘: Converts a string to uppercase.
 ‘lower()’: Converts a string to lowercase.
 ‘strip()‘: Removes leading and trailing whitespace from a string.
 ‘find()’: Returns the index of the first occurrence of a substring.
 ‘replace()’: Replaces all occurrences of a substring with another string.
Example:
message = “ Hello World “
print(len(message)) # Output: 14
print(message.upper()) # Output: HELLO WORLD
print(message.strip()) # Output: Hello World
print(message.find(“World”)) # Output: 6
print(message.replace(“World”, “Universe”)) # Output: Hello Universe

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 23

Lists in Python: Organizing and Manipulating Data with Flexibility


Lists are one of the most versatile and commonly used data structures in Python. They allow you to store
collections of items, offering flexibility and ease of manipulation. This guide explores the key features of lists,
including indexing, operations, traversal, built-in functions, and practical examples like linear search and
frequency counting.
1. Introduction:
 Definition: Lists are mutable sequences of items enclosed in square brackets [].
Example: [1, 2, 3], [“apple”, “banana”, “cherry”], [True, False, True].
Key Features:
 Mutable: Elements in a list can be modified, added, or removed after creation.
 Ordered: Items are stored in a specific order, allowing for indexing and slicing.
 Heterogeneous: Lists can contain elements of different data types.
2. Indexing:
 You can access individual elements in a list using their index, starting from 0 for the first element.
 Syntax: list[index]
Example:
numbers = [10, 20, 30, 40]
print(numbers[0]) # Output: 10
print(numbers[2]) # Output: 30
 Negative Indexing: You can also access elements from the end using negative indices, starting from -1 for the
last element.
3. List Operations:
 Concatenation: Combining two or more lists using the + operator.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
 Repetition: Repeating a list multiple times using the * operator.
Example:
numbers = [1, 2]
repeated_list = numbers * 3
print(repeated_list) # Output: [1, 2, 1, 2, 1, 2]
 Membership: Checking if an element exists in a list using the in operator.
Example:
fruits = [“apple”, “banana”, “cherry”]
print(“banana” in fruits) # Output: True
 Slicing: Extracting a portion of a list using the slicing operator [:].
Example:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Output: [20, 30, 40]
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 24

print(numbers[:3]) # Output: [10, 20, 30]


print(numbers[3:]) # Output: [40, 50]
4. Traversing a List:
 You can iterate through each element in a list using a for loop.
Example:
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
5. Built-in List Functions:
 ‘len()’: Returns the number of elements in a list.
• ‘append()’: Adds an element to the end of a list.
• ‘insert()’: Inserts an element at a specific index.
• ‘remove()’: Removes the first occurrence of a specific element.
• ‘pop()’: Removes and returns the element at a specific index (or the last element if no index is provided).
• ‘sort()’: Sorts the elements in a list in ascending order.
• ‘reverse()’: Reverses the order of elements in a list.
6. Linear Search:
 A simple search algorithm that iterates through each element in a list until the target element is found.
Example:
numbers = [10, 20, 30, 40, 50]
target = 30
found = False
for number in numbers:
if number == target:
found = True
break
if found:
print(f”Target {target} found in the list.”)
else:
print(f”Target {target} not found in the list.”)
7. Counting Element Frequency:
 You can use a dictionary to count the frequency of each element in a list.
Example:
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
frequency = {}
for number in numbers:
if number in frequency:
frequency[number] += 1
else:
frequency[number] = 1
print(frequency) # Output: {1: 1, 2: 2, 3: 3, 4: 4}

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 25

Tuples in Python: Immutable Sequences for Data Integrity


Tuples are another fundamental data structure in Python, similar to lists but with a crucial difference: they are
immutable. This means that once a tuple is created, its elements cannot be changed. While this might seem
restrictive, immutability offers several advantages, making tuples ideal for situations where data integrity is
paramount.
1. Creating and Initializing Tuples:
 Syntax: Tuples are created using parentheses () and elements separated by commas.
Example:
coordinates = (10, 20)
colors = (“red”, “green”, “blue”)
empty_tuple = ()
 Single Element Tuple: To create a tuple with a single element, you need to include a trailing comma.
Example:
single_element_tuple = (1,)
2. Accessing Elements:
 You can access individual elements in a tuple using their index, similar to lists.
 Syntax: tuple[index]
Example:
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
print(coordinates[1]) # Output: 20
 Negative Indexing: You can also access elements from the end using negative indices.
3. Tuple Assignment:
 Python allows you to assign multiple values to multiple variables in a single line using tuple assignment.
Example:
x, y = (10, 20)
print(x) # Output: 10
print(y) # Output: 20
4. Operations on Tuples:
 Concatenation: Combining two or more tuples using the + operator.
 Repetition: Repeating a tuple multiple times using the * operator.
 Membership: Checking if an element exists in a tuple using the in operator.
 Slicing: Extracting a portion of a tuple using the slicing operator [:].
Example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2 # Concatenation
repeated_tuple = tuple1 * 3 # Repetition
print(2 in tuple1) # Membership: Output: True
print(tuple1[1:3]) # Slicing: Output: (2, 3)
5. Tuple Methods and Built-in Functions:
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 26

 ‘len()’: Returns the number of elements in a tuple.


 ‘count()’: Returns the number of occurrences of a specific element.
 ‘index()’: Returns the index of the first occurrence of a specific element.
Example:
colors = (“red”, “green”, “blue”, “red”)
print(len(colors)) # Output: 4
print(colors.count(“red”)) # Output: 2
print(colors.index(“green”)) # Output: 1
6. Nested Tuples:
 You can create nested tuples, where a tuple contains other tuples as elements.
Example:
matrix = ((1, 2), (3, 4), (5, 6))
print(matrix[1][0]) # Output: 3
Key Considerations:
 Immutability: Tuples are immutable, meaning you cannot modify their elements after creation. This ensures
data integrity and prevents accidental changes.
 Use Cases: Tuples are ideal for representing data that should not be modified, such as coordinates, database
records, or configuration settings.
 Efficiency: Tuples are generally more memory-efficient than lists because they are immutable.

Sets in Python: Collections of Unique Elements with Powerful Operations


Sets are unordered collections of unique elements in Python. They are particularly useful for tasks involving
membership testing, removing duplicates, and performing set operations like union, intersection, and difference.
Here’s a comprehensive guide to sets in Python:
1. Creating Sets:
 Syntax: Sets are created using curly braces {} or the set() constructor.
Example:
numbers = {1, 2, 3, 4}
fruits = {“apple”, “banana”, “cherry”}
empty_set = set()
 Important Note: Empty sets must be created using the set() constructor, as {} creates an empty dictionary.
2. Traversing Sets:
 Since sets are unordered, you cannot access elements using indexing.
 You can iterate through the elements of a set using a for loop.
Example:
fruits = {“apple”, “banana”, “cherry”}
for fruit in fruits:
print(fruit)
3. Adding and Removing Elements:
 ‘add()’: Adds a single element to the set.
 ‘update()’: Adds multiple elements from an iterable (like a list or another set) to the set.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 27

 ‘remove()’: Removes a specific element from the set. Raises a KeyError if the element is not present.
 ‘discard()’: Removes a specific element from the set. Does not raise an error if the element is not present.
 ‘pop()’: Removes and returns an arbitrary element from the set.
Example:
numbers = {1, 2, 3}
numbers.add(4)
numbers.update([5, 6])
numbers.remove(2)
numbers.discard(7) # No error raised
removed_element = numbers.pop()
print(numbers) # Output: {1, 3, 4, 5, 6}
print(removed_element)
4. Set Operations:
 Union: Combines elements from two sets, creating a new set with all unique elements.
 Syntax: set1 | set2 or set1.union(set2)
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
 Intersection: Returns a new set containing only elements that are present in both sets.
 Syntax: set1 & set2 or set1.intersection(set2)
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set) # Output: {3}
 Difference: Returns a new set containing elements that are present in the first set but not in the second set.
 Syntax: set1 - set2 or set1.difference(set2)
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}
Key Considerations:
 Unordered: Sets do not maintain the order of elements.
 Unique: Sets cannot contain duplicate elements.
 Mutable: Elements can be added or removed after creating a set.
 Use Cases: Sets are ideal for:
Membership testing (in operator)
Removing duplicates from a list
Performing set operations like union, intersection, and difference.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 28

Dictionaries in Python: Organizing Data with Key-Value Pairs


Dictionaries are one of the most versatile and powerful data structures in Python. They allow you to store data
in key-value pairs, providing a highly efficient way to access and manipulate information. This guide explores
the key features of dictionaries, including accessing items, mutability, and built-in functions.
1. Accessing Items:
 Key-Value Pairs: Dictionaries store data as key-value pairs. The key is used to access the corresponding value.
 Syntax: dictionary[key]
Example:
person = {“name”: “Alice”, “age”: 25, “city”: “New York”}
print(person[“name”]) # Output: Alice
print(person[“age”]) # Output: 25
 Key Error: If you try to access a key that doesn’t exist in the dictionary, a KeyError will be raised.
 ‘get()‘ Method: The get() method provides a safer way to access values. It returns None if the key is not found,
avoiding a KeyError.
Example:
person = {“name”: “Alice”, “age”: 25}
print(person.get(“city”)) # Output: None
2. Mutability of Dictionaries:
 Mutable: Dictionaries are mutable, meaning you can modify their contents after creation.
 Adding a New Item:
 Syntax: dictionary[key] = value
Example:
person = {“name”: “Alice”, “age”: 25}
person[“city”] = “New York”
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
 Modifying an Existing Item:
 Syntax: dictionary[key] = new_value
Example:
person = {“name”: “Alice”, “age”: 25}
person[“age”] = 30
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 30}
3. Built-in Dictionary Functions:
 ‘len()’: Returns the number of key-value pairs in the dictionary.
 ‘keys()’: Returns a view object containing all the keys in the dictionary.
 ‘values()’: Returns a view object containing all the values in the dictionary.
 ‘items()’: Returns a view object containing all the key-value pairs as tuples.
 ‘clear()’: Removes all items from the dictionary.
 ‘pop()’: Removes and returns the value associated with a given key.
 ‘popitem()’: Removes and returns an arbitrary key-value pair as a tuple.
Example:
person = {“name”: “Alice”, “age”: 30, “city”: “New York”}

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 29

print(len(person)) # Output: 3
print(person.keys()) # Output: dict_keys([‘name’, ‘age’, ‘city’])
print(person.values()) # Output: dict_values([‘Alice’, 30, ‘New York’])
print(person.items()) # Output: dict_items([(‘name’, ‘Alice’), (‘age’, 30), (‘city’, ‘New York’)])
person.clear()
print(person) # Output: {}
Key Considerations:
 Unordered: Dictionaries do not maintain the order of key-value pairs.
 Keys Must Be Immutable: Keys in a dictionary must be immutable data types like strings, numbers, or tuples.
 Use Cases: Dictionaries are ideal for:
Storing and accessing data associated with specific keys.
Representing configuration settings, user profiles, or data from a database.
Implementing lookup tables or mappings.

    Exercises    
Multiple Choice Question
1. In Python, the index of the first character in a string is __________.
(a) 1 (b) 0 (c) -1
Ans.(b) 0 Explanation: Python uses zero-based indexing for strings.
2. To concatenate two strings, you can use the __________ operator.
(a) + (b) × (c) &
Ans.(a) + Explanation: The + operator combines two strings into one.
3. The expression “hello” * 3 results in __________.
(a) hellohellohello (b) hello 3 (c) 3 hello
Ans.(a) hellohellohello Explanation: The × operator repeats the string three times.
4. In a list, the operation ‘in’ checks for __________.
(a) index (b) membership (c) equality
Ans.(b) membership Explanation: The ‘in’ operator checks if an item exists in a list.
5. The method __________ can be used to convert a string to lowercase.
(a) lower() (b) toLower() (c) down()
Ans.(a) lower() Explanation: The lower() method transforms all characters to lowercase.
6. The syntax for creating an empty list is __________.
(a) [] (b) {} (c) ()
Ans.(a) [] Explanation: Square brackets define a list in Python.
7. The first element of the list [‘apple’, ‘banana’, ‘cherry’] can be accessed using __________.
(a) list[1] (b) list[0] (c) list[-1]
Ans.(b) list[0] Explanation: The first element is at index 0.
8. A tuple is defined using __________.
(a) [] (b) () (c) {}
Ans.(b) () Explanation: Tuples are created with parentheses.
9. The method __________ is used to find the number of occurrences of an element in a list.
(a) count() (b) frequency() (c) total()
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 30

Ans.(a) count() Explanation: The count() method returns the number of occurrences.
10. To remove an item from a set, you can use the __________ method.
(a) delete() (b) remove() (c) discard()
Ans.(b) remove() Explanation: The remove() method deletes a specified element from a set.
11. The expression {1, 2, 3} is an example of a __________.
(a) List (b) Tuple (c) Set
Ans.(c) Set Explanation: Curly braces define a set in Python.
12. A dictionary is created using __________.
(a) [] (b) () (c) {}
Ans.(c) {} Explanation: Dictionaries are defined with curly braces containing key-value pairs.
13. The operation to access the value associated with the key 'name' in {'name': 'Alice'} is __________.
(a) dict.get('name') (b) dict['name'] (c) dict.name
Ans.(b) dict['name'] Explanation: You use square brackets with the key to access the value.
14. In Python, lists are __________, allowing modification of their elements.
(a) Immutable (b) Mutable (c) Static
Ans.(b) Mutable Explanation: Lists can be changed after creation.
15. The slicing operation list[1:4] retrieves elements from index __________ to __________.
(a) 1 to 4 (b) 1 to 3 (c) 0 to 3
Ans.(b) 1 to 3 Explanation: The end index is exclusive in Python slicing.
16. To add a new item to a list, you can use the __________ method.
(a) add() (b) append() (c) insert()
Ans.(b) append() Explanation: The append() method adds an item to the end of the list.
17. A tuple cannot be __________ once created.
(a) accessed (b) modified (c) created
Ans.(b) modified Explanation: Tuples are immutable, meaning their contents cannot change.
18. The set operation that combines two sets is called __________.
(a) union (b) intersection (c) difference
Ans.(a) union Explanation: Union combines elements from both sets.
19. The method __________ can be used to convert a list into a set.
(a) toSet() (b) set() (c) list()
Ans.(b) set() Explanation: The set() function converts a list into a set.
20. The method __________ allows you to traverse items in a dictionary.
(a) items() (b) keys() (c) values()
Ans.(a) items() Explanation: The items() method returns key-value pairs.
21. The method __________ can be used to join two strings.
(a) + (b) join() (c) concatenate()
Ans.(b) join() Explanation: The join() method combines elements of an iterable into a string.
22. A dictionary's keys must be __________.
(a) Strings (b) Immutable (c) Unique
Ans.(b) Immutable Explanation: Keys must be of an immutable type like strings or tuples.
23. To create a set containing unique elements from a list, you can use __________.
(a) list() (b) set() (c) dict()
Ans.(b) set() Explanation: The set() function extracts unique elements from an iterable.
24. The operation 'len(list)' returns the __________ of the list.
(a) Average (b) Length (c) First element
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 31

Ans.(b) Length Explanation: The len() function returns the number of items in a list.
25. The method __________ can be used to find the index of the first occurrence of an element in a list.
(a) find() (b) index() (c) locate()
Ans.(b) index() Explanation: The index() method returns the first index of a specified value.
26. A string can be split into a list using the __________ method.
(a) divide() (b) split() (c) break()
Ans.(b) split() Explanation: The split() method separates a string into a list based on a delimiter.
27. The __________ operation finds common elements between two sets.
(a) Union (b) Intersection (c) Difference
Ans.(b) Intersection Explanation: Intersection returns only the elements found in both sets.
28. The method __________ returns a copy of the set without the specified element.
(a) remove() (b) discard() (c) copy()
Ans.(b) discard() Explanation: Discard removes an element but does not raise an error if it’s not found.
29. The operation to add a new key-value pair in a dictionary is done using __________.
(a) dict[key] = value (b) dict.add(key, value) (c) dict.put(key, value)
Ans.(a) dict[key] = value Explanation: You assign a value to a new key to add it to the dictionary.
30. The method __________ is used to clear all items from a dictionary.
(a) clear() (b) delete() (c) empty()
Ans.(a) clear() Explanation: The clear() method removes all items from the dictionary.
31. The index of the last element in a list can be accessed using __________.
(a) list[-1] (b) list[length] (c) list[last]
Ans.(a) list[-1] Explanation: Negative indexing allows access from the end of the list.
32. A __________ is a collection of unordered unique items.
(a) List (b) Dictionary (c) Set
Ans.(c) Set Explanation: Sets are unordered and contain only unique elements.

Important Question
Q1. Write a program to reverse a string using slicing.
Q2. What is string concatenation? Provide a program that concatenates three strings.
Q3. Explain indexing and slicing in strings with examples.
Q4. Write a program to find the maximum element in a list using a built-in function.
Q5. How is a list different from a tuple? Illustrate with examples.
Q6. Write a Python program to count the occurrence of each element in a list.
Q7. What are tuples? Explain with an example.
Q8. Write a program to access elements of a nested tuple.
Q9. Explain the immutability of tuples with an example.
Q10. Write a program to find the union and intersection of two sets.
Q11. How can you remove an element from a set? Write a program to demonstrate.
Q12. What are the key features of sets in Python?
Q13. Write a Python program to add a new key-value pair to a dictionary.
Q14. Explain the use of the `get()` method in dictionaries with an example.
Q15. Write a program to count the frequency of characters in a string using a dictionary.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 32

Unit 4

Python fUnctions, modUles and Packages


Organizing Code with Functions, Modules, and Packages in Python
As your Python programs grow in complexity, it becomes increasingly important to organize your code effectively.
Functions, modules, and packages provide powerful mechanisms for structuring your code, promoting reusability,
modularity, and maintainability.
1. Functions:
 Definition: Functions are reusable blocks of code that perform specific tasks. They encapsulate logic and can
be called multiple times with different inputs.
Syntax:
def function_name(parameters):
# Code to execute
return value # Optional return statement
 Parameters: Functions can accept input values called parameters.
 Return Values: Functions can return output values using the return keyword.
Example:
def greet(name):
Prints a greeting message.
print(f”Hello, {name}!”)
greet(“Alice”) # Output: Hello, Alice!
2. Modules:
 Definition: Modules are Python files (.py) containing functions, classes, and variables. They provide a way to
organize related code into logical units.
 Importing Modules: Use the import keyword to access modules.
Example:
# my_module.py
def add(x, y):
return x + y
# main.py
import my_module
result = my_module.add(5, 3)
print(result) # Output: 8
 ‘from...import’: You can import specific functions or variables from a module.
Example:
from my_module import add
result = add(5, 3)

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 33

print(result) # Output: 8
3. Packages:
 Definition: Packages are collections of modules organized into directories. They provide a hierarchical structure
for managing larger projects.
 Creating Packages: Create a directory for your package and include an __init__.py file inside it. This file can
contain initialization code for the package.
 Importing Packages: Use the import keyword to access packages.
Example:
Directory structure:
my_package/
__init__.py
module1.py
module2.py
Importing:
import my_package.module1
 ‘from...import‘: You can import specific modules or functions from a package.
Key Considerations:
 Reusability: Functions, modules, and packages promote code reusability, reducing redundancy and improving
maintainability.
 Modularity: They break down complex programs into smaller, manageable units, making code easier to
understand and debug.
 Maintainability: They allow you to modify and update code in specific modules or packages without affecting
other parts of the program.
 Namespaces: Modules and packages create namespaces, preventing naming conflicts between different parts
of your code.
Functions in Python: Building Blocks of Reusable Code
Functions are fundamental building blocks in Python, enabling you to organize code into reusable units that
perform specific tasks. They promote code modularity, readability, and reusability, making your programs
more efficient and maintainable. Here’s a comprehensive guide to functions in Python, covering their types,
creation, arguments, parameters, scopes, and special cases like lambda functions.
1. Types of Functions:
 Built-in Functions: Functions provided by Python itself, readily available for use.
Examples: print(), len(), input(), abs(), round(), max(), min(), sum(), sorted(), type().
 Functions Defined in Modules: Functions provided within external modules, requiring import before use.
Examples: math.sqrt(), random.randint(), os.path.exists().
 User-Defined Functions: Functions created by the programmer to perform specific tasks within their code.
2. Creating User-Defined Functions:
Syntax:
def function_name(parameter1, parameter2, ...):
Docstring: Description of the function’s purpose.
# Code to execute
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 34

return value # Optional return statement


 Docstring: A multiline string within the function definition that describes its purpose, parameters, and return
value.
Example:
def greet(name):
Prints a greeting message.
print(f”Hello, {name}!”)
greet(“Alice”) # Output: Hello, Alice!
3. Arguments and Parameters:
 Parameters: Variables defined within the function’s parentheses, representing the inputs the function expects.
 Arguments: Actual values passed to the function when it’s called.
Example:
def add(x, y):
Adds two numbers.
return x + y
result = add(5, 3) # 5 and 3 are arguments
print(result) # Output: 8
4. Default Parameters:
 Syntax: Assign a default value to a parameter using the = operator.
Example:
def greet(name, greeting=”Hello”):
Prints a greeting message.
print(f”{greeting}, {name}!”)
greet(“Alice”) # Output: Hello, Alice!
greet(“Bob”, “Hi”) # Output: Hi, Bob!
5. Positional Parameters:
 Arguments are matched to parameters based on their position in the function call.
Example:
def subtract(x, y):
Subtracts two numbers.
return x - y
result = subtract(10, 5) # 10 is x, 5 is y
print(result) # Output: 5
6. Lambda Functions (Anonymous Functions):
 Syntax:
lambda arguments: expression
Example:
square = lambda x: x × x
print(square(5)) # Output: 25
 Use Cases: Short, concise functions that can be defined inline.
7. Returning Values:

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 35

 ‘return’ Statement: Used to send a value back to the caller of the function.
Example:
def multiply(x, y):
Multiplies two numbers.
return x × y
product = multiply(5, 3)
print(product) # Output: 15
8. Scope of a Variable:
 Global Scope: Variables declared outside any function have global scope and can be accessed from anywhere
in the program.
 Local Scope: Variables declared inside a function have local scope and are only accessible within that function.
Example:
global_var = 10
def my_function():
local_var = 20
print(global_var) # Accessing global variable
print(local_var) # Accessing local variable
my_function()
# print(local_var) # Error: local_var is not accessible outside the function
Expanding Your Python Toolkit: Modules, Packages, and Beyond
As your Python projects grow in complexity, you’ll find yourself needing to leverage pre-written code and
functionalities provided by others. This is where modules, packages, and the rich ecosystem of Python libraries
come into play.
1. Modules:
 Definition: Modules are Python files (.py) containing functions, classes, and variables. They encapsulate related
code and provide a way to organize your project.
 Importing Modules: Use the import keyword to bring a module into your current script.
 Syntax: import module_name
Example:
import math
result = math.sqrt(25)
print(result) # Output: 5.0
 Accessing Module Elements: Use the module name followed by a dot (.) to access its functions, classes, or
variables.
Example: math.sin(math.pi)
2. Packages:
 Definition: Packages are collections of modules organized into directories. They provide a hierarchical structure
for managing larger projects and libraries.
 Creating Packages: Create a directory for your package and include an __init__.py file inside it. This file can
contain initialization code for the package.
 Importing Packages: Use the import keyword to access packages.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 36

Example:
import my_package.module1
 ‘from...import’: You can import specific modules or functions from a package.
Example:
from my_package.module1 import my_function
3. Regular Expressions:
 Definition: Regular expressions (regex) are powerful tools for pattern matching in text. They provide a concise
and flexible way to search, extract, and manipulate text data.
 Module: Use the re module in Python to work with regular expressions.
Example:
import re
text = “The quick brown fox jumps over the lazy dog.”
match = re.search(r”quick”, text)
if match:
print(match.group()) # Output: quick
4. Exception Handling:
 Definition: Exception handling is a mechanism for dealing with errors or unexpected events that occur during
program execution. It allows you to gracefully handle errors and prevent your program from crashing.
 ‘try...except‘ Block:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
Example:
try:
number = int(input(“Enter a number: “))
result = 10 / number
print(result)
except ZeroDivisionError:
print(“Cannot divide by zero.”)
except ValueError:
print(“Invalid input. Please enter a number.”)
5. PyPI (Python Package Index):
 Definition: PyPI is a repository of publicly available Python packages. It’s the central location for finding and
installing third-party libraries.
6. Pip (Python Package Manager):
 Definition: Pip is the standard package manager for Python. It allows you to install, upgrade, and manage
Python packages from PyPI.
 Installation:
pip install package_name
7. Importing Libraries and Functions:

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 37

 Libraries: Collections of modules and packages that provide pre-built functionalities for specific tasks.
 Importing Libraries: Use the import keyword to import libraries.
Example:
import numpy as np
import pandas as pd
 Functions: Use the library name followed by a dot (.) to access its functions.
Example: np.mean(data), pd.DataFrame(data)

    Exercises    
Multiple Choice Question
1. A function defined by the user is called a __________ function.
(a) built-in (b) user-defined (c) standard
Ans.(b) user-defined Explanation: User-defined functions are created to perform specific tasks.
2. The __________ keyword is used to define a function in Python.
(a) define (b) func (c) def
Ans.(c) def Explanation: The def keyword begins the function definition.
3. A function that does not return a value is known as a __________ function.
(a) void (b) None (c) returnless
Ans.(a) void Explanation: Void functions do not return any value.
4. The term __________ refers to values passed to a function when it is called.
(a) parameters (b) arguments (c) inputs
Ans.(b) arguments Explanation: Arguments are the actual values supplied to the function.
5. A function that takes no arguments is called a __________ function.
(a) empty (b) no-arg (c) parameterless
Ans.(c) parameterless Explanation: These functions do not require any input values.
6. Default parameters are defined in a function by assigning a value in the __________.
(a) return statement (b) function definition (c) call statement
Ans.(b) function definition
7. A function can return multiple values using a __________.
(a) list (b) tuple (c) dictionary
Ans.(b) tuple Explanation: Functions can return a tuple containing multiple values.
8. The __________ keyword is used to define an anonymous function.
(a) def (b) lambda (c) func
Ans.(b) lambda Explanation: Lambda functions are defined with the lambda keyword.
9. In Python, the scope of a variable defined inside a function is __________.
(a) local (b) global (c) universal
Ans.(a) local Explanation: Local variables are accessible only within their defining function.
10. To declare a variable as global inside a function, you use the __________ keyword.
(a) global (b) extern (c) scope
Ans.(a) global Explanation: The global keyword allows access to a global variable.
11. To import a module in Python, you use the __________ statement.
(a) require (b) import (c) include
Ans.(b) import Explanation: The import statement brings in a module for use in the program.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 38

13. A collection of modules bundled together is called a __________.


(a) library (b) package (c) framework
Ans.(b) package Explanation: Packages are organized collections of modules.
14. The __________ library is used for regular expression operations in Python.
(a) regex (b) re (c) expression
Ans.(b) re Explanation: The re module provides support for regular expressions.
15. The Python Package Index is commonly referred to as __________.
(a) PIP (b) PyPI (c) PPM
Ans.(b) PyPI Explanation: PyPI is the official repository for third-party Python packages.
16. The command used to install packages from PyPI is __________.
(a) pip install (b) install pip (c) python package
Ans.(a) pip install Explanation: The pip command is used to manage Python packages.
17. A __________ is a predefined function available in Python without needing to import a module.
(a) built-in function (b) user-defined function (c) external function
Ans.(a) built-in function Explanation: Built-in functions are readily available in Python.
18. The method __________ allows you to handle multiple exceptions in one block.
(a) except (b) try (c) except (Type1, Type2)
Ans.(c) except (Type1, Type2) Explanation: This syntax allows handling different exception types together.
19. The __________ function can be used to retrieve the type of an object in Python.
(a) type() (b) object_type() (c) get_type()
Ans.(a) type() Explanation: The type() function returns the type of an object.
20. To access a specific function within a module, you can use the syntax __________.
(a) module.function() (b) function.module() (c) import.function()
Ans.(a) module.function() Explanation: This syntax specifies which function to use from a module.
21. To raise an exception manually, you use the __________ keyword.
(a) throw (b) raise (c) except
Ans.(b) raise Explanation: The raise statement generates an exception.
22. A user-defined function can take any number of __________ as needed.
(a) parameters (b) arguments (c) variables
Ans.(b) arguments Explanation: Functions can be designed to accept various numbers of arguments.
23. The function __________ can be used to list all the attributes and methods of an object.
(a) dir() (b) list() (c) show()
Ans.(a) dir() Explanation: The dir() function provides a list of an object's properties.
24. In a user-defined function, the __________ clause specifies what the function returns.
(a) return (b) output (c) give
Ans.(a) return Explanation: The return statement ends the function and sends a value back.
25. The keyword __________ is used to define a function that can take variable-length arguments.
(a) *args (b) ... (c) varargs
Ans.(a) *args Explanation: Using *args allows for passing a variable number of arguments.
26. The __________ function is commonly used to combine a list of strings into a single string.
(a) join() (b) concat() (c) combine()
Ans.(a) join() Explanation: The join() method concatenates elements of a list into a string.
27. The built-in function __________ can be used to convert a string to an integer.
(a) int() (b) str() (c) float()
Ans.(a) int() Explanation: The int() function converts a string representation of a number into an integer.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 39

28. A package must contain a special file named __________ to be recognized as a package.
(a) init.py (b) package.py (c) setup.py
Ans.(a) init.py Explanation: This file allows Python to recognize the directory as a package.
29. The __________ function allows you to import only specific functions from a module.
(a) import specific (b) from module import function (c) select function
Ans.(b) from module import function Explanation: This syntax imports specific functions directly.
30. To prevent the program from crashing, you can use __________ to handle exceptions.
(a) print statements (b) exception handling (c) debug tools
Ans.(b) exception handling Explanation: Exception handling allows graceful management of errors.
31. The __________ module allows you to work with regular expressions in Python.
(a) regex (b) re (c) match
Ans.(b) re Explanation: The re module provides functionality for regular expressions.
32. The __________ keyword is used to define a function with no name.
(a) def (b) lambda (c) unnamed
Ans.(b) lambda Explanation: Lambda defines an anonymous function.
33. When defining a function, parameters specified in the function definition are known as __________.
(a) local (b) default (c) formal parameters
Ans.(c) formal parameters Explanation: Formal parameters are placeholders for the arguments passed to the
function.
34. The __________ statement is used to exit a function and return a value.
(a) finish (b) stop (c) return
Ans.(c) return Explanation: Return sends a value back to the caller and ends the function.
35. A function that returns a function can be termed as a __________ function.
(a) higher-order (b) nested (c) callback
Ans.(a) higher-order
36. The __________ method is useful for searching for a pattern in a string using regular expressions.
(a) search() (b) find() (c) locate()
Ans.(a) search() Explanation: The search() method looks for a pattern in the string.
37. The command __________ is used to uninstall a package with pip.
(a) pip delete (b) pip remove (c) pip uninstall
Ans.(c) pip uninstall Explanation: This command removes a specified package from the environment.
38. In Python, variables defined outside of a function are in the __________ scope.
(a) local (b) global (c) module
Ans.(b) global Explanation: Global scope allows access to variables throughout the module.
39. The __________ function in Python can take an arbitrary number of keyword arguments.
(a) kwargs (b) args (c) any
Ans.(a) kwargs Explanation: kwargs allows passing keyword arguments as a dictionary.
40. To check the type of an argument passed to a function, you can use __________.
(a) check_type() (b) type() (c) instance()
Ans.(b) type() Explanation: The type() function retrieves the data type of an object.
41. In Python, the __________ statement is used to indicate that an error should be raised if a condition is
not met.
(a) raise (b) assert (c) fail
Ans.(b) assert Explanation: The assert statement verifies that a condition is true.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 40

42. To handle cleanup actions after a try block, you can use a __________ block.
(a) cleanup (b) finally (c) last
Ans.(b) finally Explanation: Finally executes after try and except blocks, regardless of errors.
43. The __________ command displays the current version of pip installed.
(a) pip version (b) pip --version (c) pip status
Ans.(b) pip --version Explanation: This command shows the version of the pip package manager.
44. The __________ keyword is used in a function to unpack arguments from a list.
(a) * (b) ** (c) &
Ans.(a) * Explanation: The * operator allows unpacking a list into individual arguments.
45. In Python, modules are essentially __________ files containing Python code.
(a) .py (b) .txt (c) .exe
Ans.(a) .py Explanation: Python modules are saved with a .py file extension.
46. A __________ is a way to organize related functions, classes, and variables in a module.
(a) namespace (b) package (c) collection
Ans.(a) namespace Explanation: Namespaces prevent naming conflicts between identifiers.
47. The __________ function returns the documentation string for a function, module, or class.
(a) help() (b) doc() (c) info()
Ans.(a) help() Explanation: The help() function provides information about the specified object.
48. You can catch specific exceptions by naming them in the __________ clause.
(a) except (b) try (c) finally
Ans.(a) except Explanation: The except clause specifies which exceptions to handle.
49. The command __________ can be used to upgrade an existing package with pip.
(a) pip update (b) pip upgrade (c) pip install --upgrade
Ans.(c) pip install --upgrade Explanation: This command updates an installed package to the latest version.

Important Question
Q1.Define a function in Python. What are the advantages of using functions in programming?
Q2.Explain the difference between positional parameters and default parameters with examples.
Q3.What is the purpose of a lambda function? Write a simple example to illustrate its usage.
Q4.Differentiate between local scope and global scope with examples.
Q5.List any five commonly used built-in Python functions and explain their usage.
Q6.Write a Python program to create a user-defined function to calculate the factorial of a number.
Q7.Write a program using a lambda function to find the square of a given number.
Q8.Define a function that takes a string as an input and counts the frequency of vowels in it.
Q9.Write a program to demonstrate the use of global and local variables in Python.
Q10.Write a function to calculate the nth Fibonacci number using recursion.
Q11. What is the difference between a module and a package in Python?
Q12. Explain the purpose of the `import` statement. How can you import only specific functions from a
module?
Q13. What is PyPI (Python Package Index), and how is it used in Python development?
Q14. Explain the role of the `pip` package manager in Python. How do you install and uninstall packages
using `pip`?
Q15. What are regular expressions? Give an example of a practical use case in Python.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 41

Unit 5

oBject oriented Programming (ooP)


Object-Oriented Programming (OOP) in Python: Modeling the Real World
Object-oriented programming (OOP) is a powerful programming paradigm that provides a structured and
modular approach to software development. It allows you to model real-world entities and their relationships
as objects, making code more organized, reusable, and maintainable. Here’s a breakdown of key OOP concepts
in Python:
1. Classes:
 Definition: Classes are blueprints for creating objects. They define the attributes (data) and methods (functions)
that objects of that class will have.
 Syntax:
class ClassName:
# Attributes (data)
# Methods (functions)
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f”{self.name} barks!”)
my_dog = Dog(“Buddy”, “Golden Retriever”)
my_dog.bark() # Output: Buddy barks!
2. Objects:
 Definition: Objects are instances of classes. They represent real-world entities and possess the attributes and
methods defined by their class.
 Creating Objects: Use the class name followed by parentheses to create an object.
Example:
my_dog = Dog(“Buddy”, “Golden Retriever”)
3. Attributes:
 Definition: Attributes are data associated with an object. They represent the object’s characteristics or state.
 Accessing Attributes: Use the dot (.) operator to access an object’s attributes.
Example:
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
4. Methods:
 Definition: Methods are functions associated with an object. They define the object’s behavior or actions.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 42

 Accessing Methods: Use the dot (.) operator to call an object’s methods.
Example:
my_dog.bark() # Output: Buddy barks!
 ‘self ’ Parameter: The first parameter of every method is self, which refers to the object itself. It allows methods
to access and modify the object’s attributes.
5. Inheritance:
 Definition: Inheritance allows you to create new classes (child classes) that inherit attributes and methods
from existing classes (parent classes).
 Benefits:
Code reusability
Hierarchical relationships between classes
Polymorphism (ability to perform the same action in different ways)
 Syntax:
class ChildClass(ParentClass):
# Additional attributes and methods
6. Encapsulation:
 Definition: Encapsulation hides data and methods within a class, controlling access to them.
 Benefits:
Data protection
Reduced complexity
Example: Use private attributes (prefixed with __) to restrict access from outside the class.
7. Polymorphism:
Definition: Polymorphism allows objects of different classes to respond to the same method call in different
ways.
Example:
class Animal:
def speak(self):
print(“Generic animal sound”)
class Dog(Animal):
def speak(self):
print(“Woof!”)
class Cat(Animal):
def speak(self):
print(“Meow!”)
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.speak()
Mastering Object-Oriented Programming (OOP) in Python: Concepts and Techniques
Object-Oriented Programming (OOP) is a powerful paradigm that structures code around objects, representing
real-world entities and their interactions. It emphasizes modularity, reusability, and maintainability, making
code easier to understand, debug, and extend. Here’s a breakdown of key OOP concepts and techniques in
Python:
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 43

1. OOP Concepts and Approach:


 Objects: Objects are instances of classes, representing real-world entities with attributes (data) and methods
(functions).
 Classes: Blueprints for creating objects, defining the structure and behavior of objects of that type.
 Encapsulation: Hiding data and methods within a class, controlling access and protecting internal state.
 Abstraction: Simplifying complex systems by exposing only essential features and hiding implementation
details.
 Inheritance: Creating new classes (child classes) that inherit attributes and methods from existing classes
(parent classes), promoting code reusability and hierarchical relationships.
 Polymorphism: Allowing objects of different classes to respond to the same method call in different ways,
enabling flexible and dynamic behavior.
2. Abstraction:
 Definition: Abstraction focuses on presenting only the essential features of an object, hiding unnecessary
details.
 Example: A car object might have methods like start(), accelerate(), and brake(), but the internal workings of
the engine are hidden.
 Benefits:
Simplifies code complexity
Promotes modularity and code reusability
Enables easier maintenance and modification
3. Encapsulation:
 Definition: Encapsulation bundles data (attributes) and methods (functions) within a class, controlling access
to them.
 Example: Using private attributes (prefixed with __) to restrict access from outside the class.
 Benefits:
Data protection: Prevents accidental modification of internal state.
Reduced complexity: Enforces a clear separation between internal and external interactions.
4. Class vs. Object:
 Class: A blueprint or template for creating objects. It defines the common structure and behavior of all objects
of that type.
 Object: An instance of a class, representing a specific entity with its own unique state (attribute values).
5. Class Methods vs. Static Methods:
 Class Methods: Bound to the class itself, not individual objects. They can access and modify class variables.
 Syntax: Decorator @classmethod
Example:
class MyClass:
class_var = 0
@classmethod
def increment_class_var(cls):
cls.class_var += 1
 Static Methods: Not bound to the class or its objects. They can’t access or modify class variables.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 44

 Syntax: Decorator @staticmethod


Example:
class MyClass:
@staticmethod
def my_static_method(x, y):
return x + y
6. Class and Static Variables:
 Class Variables: Belong to the class itself, shared by all instances of the class.
 Static Variables: Belong to the class itself, not to individual objects. They are accessed using the class name.
7. Constructor and Destructor:
 Constructor (‘__init__’): Special method called automatically when an object is created. It initializes the
object’s attributes.
 Destructor (‘__del__’): Special method called automatically when an object is destroyed (garbage collected).
It performs cleanup tasks.

Inheritance in Python: Building upon Existing Code with Different Types


Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new
classes (child classes) that inherit attributes and methods from existing classes (parent classes). This promotes
code reusability, reduces redundancy, and establishes hierarchical relationships between classes. Python supports
various types of inheritance:
1. Single Inheritance:
 Definition: A child class inherits from only one parent class.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(“Generic animal sound”)
class Dog(Animal):
def speak(self):
print(“Woof!”)
my_dog = Dog(“Buddy”)
my_dog.speak() # Output: Woof!
Here, Dog inherits from Animal, inheriting the __init__ method and overriding the speak method.
2. Multiple Inheritance:
 Definition: A child class inherits from multiple parent classes.
Example:
class Flyer:
def fly(self):
print(“Flying...”)
class Swimmer:

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 45

def swim(self):
print(“Swimming...”)
class Bird(Flyer, Swimmer):
pass
my_bird = Bird()
my_bird.fly() # Output: Flying...
my_bird.swim() # Output: Swimming...
Bird inherits from both Flyer and Swimmer, gaining the fly and swim methods.
3. Multilevel Inheritance:
 Definition: A child class inherits from a parent class, which itself inherits from another parent class.
Example:
class Grandparent:
def greet(self):
print(“Hello from Grandparent”)
class Parent(Grandparent):
def greet(self):
print(“Hello from Parent”)
class Child(Parent):
def greet(self):
print(“Hello from Child”)
my_child = Child()
my_child.greet() # Output: Hello from Child
Child inherits from Parent, which inherits from Grandparent. The greet method is overridden in each class.
4. Hierarchical Inheritance:
 Definition: Multiple child classes inherit from a single parent class.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(“Generic animal sound”)
class Dog(Animal):
def speak(self):
print(“Woof!”)
class Cat(Animal):
def speak(self):
print(“Meow!”)
Both Dog and Cat inherit from Animal.
Key Considerations:
 Method Resolution Order (MRO): Python uses a specific algorithm to determine the order in which methods
are searched for in multiple inheritance scenarios.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 46

 Overriding Methods: Child classes can override methods inherited from parent classes, providing specialized
behavior.
 Super() Function: Use super() to call methods from the parent class within a child class.
 Diamond Problem: A potential issue in multiple inheritance where a child class inherits from multiple parent
classes that share a common ancestor, leading to ambiguity in method resolution. Python’s MRO helps mitigate
this problem.

Polymorphism in Python: Making Objects Behave Flexibly


Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes
to respond to the same method call in different ways. This flexibility makes code more adaptable, reusable, and
easier to maintain. Here’s a breakdown of polymorphism in Python, exploring its implementation with class
methods, inheritance, method overriding, and overloading:
1. Polymorphism with Class Methods:
 Definition: Class methods can be called on the class itself, not just on instances of the class. Polymorphism
allows you to define different behaviors for the same class method based on the class it’s called on.
Example:
class Shape:
@classmethod
def area(cls):
raise NotImplementedError(“Area method not implemented.”)
class Circle(Shape):
@classmethod
def area(cls, radius):
return 3.14159 * radius * radius
class Square(Shape):
@classmethod
def area(cls, side):
return side * side
circle = Circle()
square = Square()
print(circle.area(5)) # Output: 78.53975
print(square.area(4)) # Output: 16
Here, area is a class method that is overridden in Circle and Square to provide specific area calculations.
2. Polymorphism with Inheritance:
 Definition: When a child class inherits from a parent class, it can override methods defined in the parent class.
This allows objects of different classes to respond differently to the same method call.
Example:
class Animal:
def speak(self):
print(“Generic animal sound”)
class Dog(Animal):

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 47

def speak(self):
print(“Woof!”)
class Cat(Animal):
def speak(self):
print(“Meow!”)
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.speak()
Each animal class overrides the speak method, resulting in different sounds based on the object’s type.
3. Method Overriding:
 Definition: Overriding occurs when a child class provides a new implementation for a method inherited from
its parent class.
 Example: In the previous animal example, Dog.speak() and Cat.speak() override the Animal.speak() method.
4. Method Overloading:
 Definition: Overloading is the ability to define multiple methods with the same name but different parameters.
Python does not directly support method overloading in the same way as some other languages.
 Workaround: Use default parameters or variable-length arguments (*args, *kwargs) to achieve similar behavior.
Example:
def add(x, y=0):
return x + y
print(add(5, 3)) # Output: 8
print(add(5)) # Output: 5
Key Considerations:
 Duck Typing: Python often relies on “duck typing,” where the type of an object is less important than the
methods it implements. If an object “walks like a duck and quacks like a duck,” then it’s considered a duck,
regardless of its actual class.
 Dynamic Dispatch: Python dynamically determines which method to call at runtime based on the object’s
type. This allows for flexible and adaptable behavior.

    Exercises    
Multiple Choice Question
1. The main principle of OOP that involves hiding implementation details is called __________.
(a) encapsulation (b) abstraction (c) inheritance
Ans.(b) abstraction Explanation: Abstraction hides complex realities while exposing only the necessary parts.
2. In OOP, a blueprint for creating objects is called a __________.
(a) module (b) class (c) function
Ans.(b) class Explanation: A class defines the structure and behavior of objects.
3. An instance of a class is referred to as an __________.
(a) object (b) variable (c) function
Ans.(a) object Explanation: Objects are created from classes and represent real-world entities.
4. A __________ is a special method in a class that initializes new objects.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 48

(a) destructor (b) constructor (c) initializer


Ans.(b) constructor Explanation: Constructors set initial values for object attributes.
5. The method that is called when an object is about to be destroyed is called a __________.
(a) destructor (b) finalizer (c) cleaner
Ans.(a) destructor Explanation: Destructors perform cleanup tasks before an object is removed.
6. A class variable is shared across all instances of a class, while an instance variable is __________.
(a) local to the class (b) specific to each object (c) static
Ans.(b) specific to each object Explanation: Instance variables hold data unique to each object.
7. A __________ method is defined within a class and takes the instance as its first parameter.
(a) static (b) class (c) instance
Ans.(c) instance Explanation: Instance methods operate on individual object data.
8. A __________ method belongs to the class rather than any specific instance.
(a) class (b) instance (c) static
Ans.(a) class Explanation: Class methods can be called on the class itself, not on instances.
9. The __________ keyword is used to define a class method.
(a) @staticmethod (b) @classmethod (c) @instance
Ans.(b) @classmethod Explanation: This decorator defines a method that operates on the class itself.
10. A __________ variable is defined within a class and can be accessed by all instances of that class.
(a) instance (b) static (c) local
Ans.(b) static Explanation: Static variables are shared among all instances of a class.
11. Inheritance allows a new class to inherit attributes and methods from an __________ class.
(a) derived (b) base (c) child
Ans.(b) base Explanation: A base class provides common functionality to derived classes.
12. __________ inheritance involves a class inheriting from multiple parent classes.
(a) Multilevel (b) Hierarchical (c) Multiple
Ans.(c) Multiple Explanation: Multiple inheritance allows a class to derive features from several classes.
13. In __________ inheritance, a class inherits from another class which, in turn, inherits from a base class.
(a) multilevel (b) single (c) multiple
Ans.(a) multilevel Explanation: Multilevel inheritance creates a chain of classes.
14. A __________ relationship is established when a class derives from one base class and multiple derived
classes share that base class.
(a) multilevel (b) hierarchical (c) multiple
Ans.(b) hierarchical Explanation: Hierarchical inheritance allows multiple classes to inherit from a single
class.
15. Polymorphism allows methods to do different things based on the __________.
(a) object type (b) method name (c) class type
Ans.(a) object type
16. Method __________ allows a subclass to provide a specific implementation of a method that is already
defined in its superclass.
(a) overloading (b) overridin (c) hiding
Ans.(b) overriding Explanation: Overriding modifies the behavior of inherited methods.
17. In Python, method __________ allows multiple methods to have the same name but different parameters.
(a) overriding (b) overloading (c) redefining
Ans.(b) overloading
18. When a class method is decorated with __________, it can be called without creating an instance of the
class.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 49

(a) @staticmethod (b) @classmethod (c) @property


Ans.(a) @staticmethod Explanation: Static methods do not require an instance to be invoked.
19. The principle of __________ allows the same interface to be used for different underlying forms.
(a) encapsulation (b) polymorphism (c) abstraction
Ans.(b) polymorphism Explanation: Polymorphism promotes flexibility in code.
20. A class that cannot be instantiated directly is called an __________ class.
(a) abstract (b) interface (c) derived
Ans.(a) abstract Explanation: Abstract classes serve as blueprints for derived classes.
21. To define an abstract method in Python, you use the __________ module.
(a) abc (b) abstract (c) base
Ans.(a) abc Explanation: The abc module provides the foundation for defining abstract classes.
22. Encapsulation is the bundling of data and methods that operate on that data within a single __________.
(a) object (b) function (c) class
Ans.(c) class Explanation: Encapsulation groups related properties and behaviors together.
23. The __________ method is called before an object is destroyed to perform cleanup actions.
(a) finalize (b) delete (c) del
Ans.(c) del Explanation: The del method is invoked during object destruction.
24. Inheritance enables code __________ by allowing new classes to use existing code.
(a) duplication (b) reuse (c) complication
Ans.(b) reuse Explanation: Inheritance promotes code reuse, reducing redundancy.
25. A method that behaves differently depending on the object that calls it is a demonstration of __________.
(a) encapsulation (b) polymorphism (c) inheritance
Ans.(b) polymorphism Explanation: Polymorphism allows methods to adapt to different object types.
26. The __________ keyword is used to create a subclass from a superclass.
(a) extends (b) inherits (c) class
Ans.(c) class Explanation: Subclasses are defined using the class keyword followed by the parent class.
27. If you want to restrict access to an attribute, you can prefix it with a __________.
(a) (single underscore) (b) # (hash) (c) @ (at symbol)
Ans.(a) _ (single underscore)
28. The __________ method allows you to convert a class to a string when using print().
(a) str (b) repr (c) string
Ans.(a) str Explanation: The str method provides a user-friendly string representation of an object.
29. When you define a method in a derived class with the same name as one in the base class, this is called
__________.
(a) overloading (b) overriding (c) shadowing
Ans.(b) overriding Explanation: Overriding allows redefining the behavior of inherited methods.
30. The principle of __________ ensures that only relevant details are exposed to the user, while other details
are hidden.
(a) encapsulation (b) abstraction (c) inheritance
Ans.(b) abstraction Explanation: Abstraction simplifies complex systems by hiding unnecessary details.
31. A static method cannot access __________ within the class.
(a) instance variables (b) class variables (c) both
Ans.(a) instance variables Explanation: Static methods do not operate on instance-specific data.
32. In Python, a derived class inherits methods and properties from its __________ class.
(a) parent (b) base (c) both
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 50

Ans.(c) both Explanation: The derived class gets features from both its direct and indirect parent classes.
33. __________ methods are used to define behavior that applies to the class itself rather than individual
instances.
(a) Class (b) Instance (c) Static
Ans.(a) Class Explanation: Class methods can modify class-level attributes.
34. A __________ class can have both implemented methods and abstract methods.
(a) concrete (b) abstract (c) derived
Ans.(b) abstract
35. The __________ operator can be used to check if a class is a subclass of another class.
(a) isinstance() (b) type() (c) issubclass()
Ans.(c) issubclass() Explanation: The issubclass() function checks for subclass relationships.
36. A method that takes variable-length arguments can be defined using the __________ syntax.
(a) *args (b) **kwargs (c) both
Ans.(c) both Explanation: Both *args and **kwargs allow for flexible argument handling.
37. The concept of __________ allows a function to use a subclass object in place of a superclass object.
(a) encapsulation (b) polymorphism (c) inheritance
Ans.(b) polymorphism Explanation: Polymorphism promotes substitutability of objects.
38. When defining a class in Python, attributes can be initialized within the __________ method.
(a) init (b) start (c) begin
Ans.(a) init Explanation: The init method initializes instance variables.
39. A class can inherit from multiple parent classes using __________ syntax.
(a) class A(B, C) (b) class A extends B, C (c) class A inherits B, C
Ans.(a) class A(B, C) Explanation: This syntax defines class A to inherit from both B and C.
40. __________ is a key feature of OOP that promotes the reuse of code across classes.
(a) encapsulation (b) abstraction (c) inheritance
Ans.(c) inheritance Explanation: Inheritance enables the creation of new classes from existing ones.
41. A private variable in a class is prefixed with a __________.
(a) __ (double underscore) (b) # (hash) (c) _ (single underscore)
Ans.(a) __ (double underscore) Explanation: Double underscores invoke name mangling, restricting access.
42. The __________ operator can be used to check if an object is an instance of a class.
(a) type() (b) isinstance() (c) objtype()
Ans.(b) isinstance() Explanation: isinstance() verifies the object's type against a class or tuple of classes.
43. In method overriding, the derived class can change the behavior of the base class method by defining its
own version with the __________ name.
(a) different (b) same (c) unique
Ans.(b) same Explanation: The method name must match for overriding to occur.
44. The principle of __________ allows classes to be treated as instances of their parent class.
(a) polymorphism (b) encapsulation (c) inheritance
Ans.(a) polymorphism Explanation: This feature enables objects of different classes to be treated uniformly.
45. A method defined within a class that modifies its instance variables is an __________ method.
(a) accessor (b) mutator (c) constructor
Ans.(b) mutator Explanation: Mutator methods modify the state of an object.
46. Abstract methods must be implemented in __________ classes.
(a) base (b) abstract (c) derived
Ans.(c) derived Explanation: Derived classes must provide concrete implementations of abstract methods.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 51

47. The __________ keyword is used to inherit a class in Python.


(a) inherit (b) extends (c) class
Ans.(c) class Explanation: The class keyword introduces class definitions, including inheritance.
48. In OOP, a __________ is a collection of related functions and data that act on that data.
(a) module (b) class (c) interface
Ans.(b) class Explanation: Classes encapsulate data and functions into reusable components.
49. The __________ operator is used to indicate that a variable is class-specific.
(a) @ (b) # (c) *
Ans.(a) @ Explanation: The @ symbol denotes decorators for class and static methods.
50. Method overloading is not natively supported in Python; instead, you can achieve similar functionality
using __________.
(a) default parameters (b) decorators (c) variable arguments
Ans.(c) variable arguments

Important Question
Q1.Explain the four pillars of object-oriented programming: abstraction, encapsulation, inheritance, and
polymorphism.
Q2.What is the difference between a class and an object in Python?
Q3.Define and differentiate between class methods and static methods in Python. Provide examples.
Q4.What is the purpose of a constructor in Python? How is it different from a destructor?
Q5.Explain the use of class variables and instance variables with examples.
Q6.Write a Python program to create a class `Student` with attributes `name`, `roll_no`, and `marks`, and a
method to display student details.
Q7.Write a Python program to implement and differentiate between a class method and a static method.
Q8.What is inheritance? List and explain the types of inheritance supported in Python.
Q9.Differentiate between single inheritance and multiple inheritance with examples.
Q10.Explain the concept of multilevel inheritance and give a practical scenario where it can be used.
Q11.What is polymorphism in OOP? How is it achieved in Python?
Q12.Explain method overriding with an example.
Q13.What is method overloading? Is it supported in Python? If yes, how can it be implemented?

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 52

Unit 6

excePtion and file handling in Python

Handling Errors and Working with Files in Python


Python provides robust mechanisms for handling exceptions (errors) and interacting with files. Mastering
these concepts is crucial for writing robust and reliable programs.
1. Exception Handling:
 Definition: Exceptions are events that occur during program execution that disrupt the normal flow of the
program. They can be caused by various factors, such as invalid user input, file errors, network issues, or
division by zero.
 ‘try...except‘ Block: The try...except block is used to handle exceptions gracefully.
 Syntax:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
Example:
try:
number = int(input(“Enter a number: “))
result = 10 / number
print(result)
except ZeroDivisionError:
print(“Cannot divide by zero.”)
except ValueError:
print(“Invalid input. Please enter a number.”)
 ‘else‘ Block: The else block executes if no exception is raised in the try block.
 ‘finally‘ Block: The finally block always executes, regardless of whether an exception is raised or not. It’s often
used for cleanup tasks, like closing files or releasing resources.
 Raising Exceptions: You can raise custom exceptions using the raise keyword.
2. File Handling:
 Opening Files: Use the open() function to open a file.
 Syntax: file_object = open(filename, mode)
 Modes:
‘r’ (read): Opens the file for reading.
‘w’ (write): Opens the file for writing. Creates a new file if it doesn’t exist, or overwrites an existing file.
‘a’ (append): Opens the file for appending. Creates a new file if it doesn’t exist.
‘x’ (create): Creates a new file. Raises an error if the file already exists.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 53

‘b’ (binary): Opens the file in binary mode.


‘t’ (text): Opens the file in text mode (default).
 Reading Files:
‘read()’: Reads the entire contents of the file.
‘readline()’: Reads a single line from the file.
 ‘readlines()’: Reads all lines from the file into a list.
 Writing Files:
‘write()’: Writes a string to the file.
 Closing Files: Use the close() method to close the file.
Example:
try:
with open(‘my_file.txt’, ‘r’) as file:
content = file.read()
print(content)
except FileNotFoundError:
print(“File not found.”)
finally:
file.close()
 ‘with’ Statement: The with statement automatically closes the file when you’re done with it, even if an exception
occurs.
Key Considerations:
 Error Handling: Always handle exceptions gracefully to prevent program crashes and provide informative
error messages.
 File Modes: Choose the appropriate file mode based on your intended operations.
 File Closing: Ensure you close files after you’re done with them to release resources and prevent data corruption.
 File Paths: Use absolute or relative paths to specify the location of files.
 Data Types: When working with files, remember that data is typically read as strings. You may need to convert
data to other types, such as integers or floats, as needed.
Exception Handling in Python: Gracefully Managing Errors
Exception handling is a crucial aspect of robust programming. It allows your program to gracefully handle
unexpected events or errors that occur during execution, preventing crashes and providing a more controlled
and informative experience for the user. Here’s a comprehensive guide to exception handling in Python:
1. Syntax Errors vs. Exceptions:
 Syntax Errors: These occur when the Python interpreter encounters invalid code syntax. The program cannot
be executed until the syntax error is fixed.
 Exceptions: These occur during program execution when an unexpected event happens, disrupting the normal
flow of the program. Examples include:
ZeroDivisionError: Division by zero.
TypeError: Attempting to perform an operation on an incompatible data type.
ValueError: Attempting to convert an invalid value to a specific data type.
FileNotFoundError: Trying to access a file that doesn’t exist.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 54

IndexError: Accessing an element in a sequence using an invalid index.


2. Need for Exception Handling:
 Preventing Program Crashes: Without exception handling, unexpected events can cause the program to
terminate abruptly, leading to data loss or unpredictable behavior.
 Providing Informative Error Messages: Exception handling allows you to catch errors and provide meaningful
messages to the user, guiding them on how to fix the issue.
 Maintaining Program Flow: Exception handling enables you to handle errors without completely halting the
program. You can choose to recover from errors or log them for later analysis.
3. User-Defined Exceptions:
 Creating Custom Exceptions: You can create your own exception classes by inheriting from the built-in
Exception class.
Example:
class InvalidInputError(Exception):
pass
def get_age():
age = int(input(“Enter your age: “))
if age < 0:
raise InvalidInputError(“Age cannot be negative.”)
return age
try:
age = get_age()
print(f”Your age is: {age}”)
except InvalidInputError as e:
print(f”Error: {e}”)
4. Raising Exceptions:
 ‘raise’ Keyword: Use the raise keyword to explicitly raise an exception.
Example:
def divide(x, y):
if y == 0:
raise ZeroDivisionError(“Cannot divide by zero.”)
return x / y
try:
result = divide(10, 0)
print(result)
except ZeroDivisionError as e:
print(f”Error: {e}”)
5. Handling Exceptions:
 ‘try...except‘ Block: The try block encloses the code that might raise an exception. The except block handles
the exception if it occurs.
 Catching Exceptions: The except block specifies the type of exception to catch. You can catch multiple
exceptions using multiple except blocks.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 55

Example:
try:
# Code that might raise an exception
except ExceptionType1:
# Handle ExceptionType1
except ExceptionType2:
# Handle ExceptionType2
6. ‘try...except...else‘ Clause:
 ‘else’ Block: The else block executes if no exception is raised in the try block.
Example:
try:
# Code that might raise an exception
except ExceptionType:
# Handle ExceptionType
else:
# Execute if no exception is raised
7. ‘try...finally’ Clause:
 ‘finally’ Block: The finally block always executes, regardless of whether an exception is raised or not. It’s used
for cleanup tasks, like closing files or releasing resources.
Example:
try:
# Code that might raise an exception
except ExceptionType:
# Handle ExceptionType
finally:
# Always execute cleanup tasks
8. Built-in Exception Classes:
 Python provides a hierarchy of built-in exception classes, organized into categories like:
 BaseException: The base class for all exceptions.
 SystemExit: Raised when the sys.exit() function is called.
 KeyboardInterrupt: Raised when the user interrupts the program (e.g., by pressing Ctrl+C).
 Exception: The base class for most standard exceptions.
 ArithmeticError: Base class for arithmetic errors.
 ZeroDivisionError: Division by zero.
 ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.
 TypeError: Raised when an operation or function is applied to an object of an inappropriate type.
 IOError: Raised when an input/output operation fails.
 FileNotFoundError: Raised when a file is not found.
 IndexError: Raised when a sequence subscript is out of range.
 KeyError: Raised when a dictionary key is not found.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 56

File Handling in Python: Working with Text and Binary Data


File handling is a fundamental aspect of programming, allowing you to interact with data stored in files.
Python provides a straightforward and powerful way to work with both text files and binary files. Here’s a
comprehensive guide to file handling in Python, covering file types, opening and closing files, reading and
writing data, and file access modes.
1. Text Files vs. Binary Files:
 Text Files: Contain human-readable characters, typically encoded using ASCII or Unicode. Examples include
plain text documents, configuration files, and source code files.
 Binary Files: Contain raw, uninterpreted data, often represented as sequences of bytes. Examples include
images, audio files, and compiled programs.
2. File Types:
 File Extension: The file extension (e.g., .txt, .csv, .jpg, .mp3) typically indicates the file type.
 MIME Type: A more formal way to identify file types, often used in web applications. Examples include text/
plain, text/html, image/jpeg, audio/mpeg.
3. Opening and Closing Files:
 ‘open()‘ Function: Use the open() function to open a file.
 Syntax: file_object = open(filename, mode)
 ‘filename’: The path to the file.
 ‘mode’: Specifies the mode in which the file is opened.
File Access Modes:
 ‘r’ (read): Opens the file for reading.
 ‘w’ (write): Opens the file for writing. Creates a new file if it doesn’t exist, or overwrites an existing file.
 ‘a’ (append): Opens the file for appending. Creates a new file if it doesn’t exist.
 ‘x’ (create): Creates a new file. Raises an error if the file already exists.
 ‘b’ (binary): Opens the file in binary mode.
 ‘t’ (text): Opens the file in text mode (default).
 ‘close()’ Method: Use the close() method to close the file after you’re done with it.
4. Reading and Writing Text Files:
Reading:
 ‘read()’: Reads the entire contents of the file into a string.
 ‘readline()’: Reads a single line from the file.
 ‘readlines()’: Reads all lines from the file into a list.
Writing:
 ‘write()’: Writes a string to the file.
Example:
with open(‘my_file.txt’, ‘r’) as file:
content = file.read()
print(content)
with open(‘my_file.txt’, ‘a’) as file:
file.write(“\nThis is a new line.”)
5. Reading and Writing Binary Files:

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 57

Reading:
 ‘read()’: Reads the entire contents of the file into a byte string.
 ‘read(n)’: Reads n bytes from the file.
Writing:
 ‘write()’: Writes a byte string to the file.
Example:
with open(‘image.jpg’, ‘rb’) as file:
data = file.read()
with open(‘new_image.jpg’, ‘wb’) as file:
file.write(data)
6. File Access Modes:
 ‘r’ (read): Opens the file for reading.
 ‘w’ (write): Opens the file for writing. Creates a new file if it doesn’t exist, or overwrites an existing file.
 ‘a’ (append): Opens the file for appending. Creates a new file if it doesn’t exist.
 ‘x’ (create): Creates a new file. Raises an error if the file already exists.
 ‘b’ (binary): Opens the file in binary mode.
 ‘t’ (text): Opens the file in text mode (default).
 Combining Modes: You can combine modes, for example, ‘rb’ for reading a binary file or ‘wt’ for writing a
text file.

    Exercises    
Multiple Choice Question
1. A __________ error is a syntax issue in the code that prevents it from running.
(a) runtime (b) logical (c) syntax
Ans.(c) syntax Explanation: Syntax errors occur when the code does not conform to Python’s rules.
2. An __________ is an event that disrupts the normal flow of a program’s execution.
(a) error (b) exception (c) interruption
Ans.(b) exception Explanation: Exceptions signal that something went wrong during execution.
3. The need for exception handling arises because programs must be able to __________ unexpected
situations.
(a) ignore (b) recover from (c) terminate on
Ans.(b) recover from Explanation: Exception handling allows programs to manage errors gracefully.
4. A user-defined exception is created by extending the __________ class.
(a) Exception (b) Error (c) Base
Ans.(a) Exception
5. To raise an exception in Python, you use the __________ keyword.
(a) throw (b) raise (c) assert
Ans.(b) raise Explanation: The raise keyword triggers an exception manually.
6. The __________ block is used to handle exceptions in Python.
(a) catch (b) try (c) handle
Ans.(b) try Explanation: The try block contains code that might raise an exception.
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 58

7. If no exception occurs in the try block, the __________ block is executed.


(a) finally (b) else (c) except
Ans.(b) else Explanation: The else block runs when the try block is successful.
8. The __________ block will always execute, regardless of whether an exception was raised.
(a) finally (b) except (c) else
Ans.(a) finally Explanation: Finally is used for cleanup actions that need to happen no matter what.
9. To recover from an exception and continue executing the program, you can use the __________ block.
(a) finally (b) except (c) else
Ans.(b) except Explanation: The except block allows handling of specific exceptions.
10. The __________ clause is used to execute code that should run if the try block does not raise an exception.
(a) finally (b) else (c) except
Ans.(b) else Explanation: Else executes when the try block completes without errors.
11. Python provides a set of built-in exception classes that can be used to handle specific error types, such as
__________.
(a) ValueError (b) SyntaxError (c) all of the above
Ans.(c) all of the above Explanation: Both ValueError and SyntaxError are examples of built-in exceptions.
12. To handle multiple exceptions in a single block, you can specify them as a __________.
(a) list (b) tuple (c) set
Ans.(b) tuple Explanation: A tuple allows specifying multiple exception types in one except block.
13. The __________ statement is used to perform cleanup actions after exception handling.
(a) finally (b) cleanup (c) end
Ans.(a) finally Explanation: Finally ensures that cleanup code runs regardless of errors.
14. The __________ method is used to open a file in Python.
(a) open() (b) create() (c) new()
Ans.(a) open() Explanation: The open() function initiates file operations.
15. To close a file that was opened, you use the __________ method.
(a) close() (b) end() (c) finish()
Ans.(a) close() Explanation: Closing a file releases the resources associated with it.
16. Files can be opened in different __________ modes, such as read, write, and append.
(a) access (b) execution (c) operation
Ans.(a) access Explanation: Access modes determine how files are opened and manipulated.
17. The mode for opening a file in read-only mode is __________.
(a) "w" (b) "r" (c) "a"
Ans.(b) "r" Explanation: The "r" mode allows reading the contents of a file.
18. If you want to write to a file, you would open it in __________ mode.
(a) "a" (b) "r" (c) "w"
Ans.(c) "w" Explanation: The "w" mode enables writing to a file, overwriting existing content.
19. To append data to an existing file, you use the __________ mode.
(a) "a" (b) "r" (c) "w"
Ans.(a) "a" Explanation: The "a" mode adds new data to the end of a file without deleting existing content.
20. The __________ method reads the entire content of a text file at once.
(a) readlines() (b) read() (c) readfile()
Ans.(b) read() Explanation: The read() method retrieves all contents of a file.
21. To read a file line by line, you can use the __________ method.
(a) read() (b) readline() (c) readlines()
FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 59

Ans.(b) readline() Explanation: The readline() method fetches one line at a time from a file.
22. The __________ method reads all lines of a file and returns them as a list.
(a) readlines() (b) read() (c) getlines()
Ans.(a) readlines() Explanation: The readlines() method returns each line in a file as an element in a list.
23. To write text to a file, you use the __________ method.
(a) write() (b) append() (c) insert()
Ans.(a) write() Explanation: The write() method writes data to a file.
24. When writing binary data to a file, you should open it in __________ mode.
(a) "t" (b) "b" (c) "x"
Ans.(b) "b" Explanation: The "b" mode is used for binary file operations.
25. The __________ method is used to write multiple lines to a file at once.
(a) writelines() (b) write() (c) append()
Ans.(a) writelines() Explanation: The writelines() method takes a list of strings and writes them to a file.
26. When you open a file, you can specify whether to create a new file if it doesn't exist by using the __________
mode.
(a) "w" (b) "x" (c) "a"
Ans.(b) "x" Explanation: The "x" mode creates a new file and fails if it already exists.
27. The __________ method can be used to seek to a specific position in a file.
(a) seek() (b) move() (c) locate()
Ans.(a) seek() Explanation: The seek() method changes the file's current position.
28. The __________ function is used to check if a file exists before performing file operations.
(a) file_exists() (b) exists() (c) os.path.exists()
Ans.(c) os.path.exists() Explanation: This function checks for the presence of a file at a given path.
29. The __________ module in Python provides tools for file and directory manipulation.
(a) io (b) os (c) sys Correct Answer: b) os
30. In a context manager, the __________ statement is used to open a file safely.
(a) with (b) as (c) open
Ans.(a) with Explanation: The with statement ensures proper acquisition and release of resources.
31. The __________ block ensures that resources are released after file operations, even if an error occurs.
(a) finally (b) except (c) else
Ans.(a) finally Explanation: Finally executes cleanup code regardless of errors.
32. To handle exceptions that arise from file operations, you would typically wrap file code in a __________
block.
(a) try (b) finally (c) else
Ans.(a) try Explanation: The try block allows for catching and handling file-related exceptions.
33. If a file is opened with the 'r' mode and does not exist, a __________ will be raised.
(a) IOError (b) FileNotFoundError (c) Exception
Ans.(b) FileNotFoundError Explanation: This error indicates that the specified file was not found.
34. When reading a binary file, the data returned is of type __________.
(a) str (b) bytes (c) list
Ans.(b) bytes Explanation: Binary files return data in byte format.
35. The __________ access mode allows you to open a file for both reading and writing.
(a) "r+" (b) "w+" (c) "a+"
Ans.(a) "r+"
36. When you use the write() method on a file opened in "w" mode, the file will be __________ if it already

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 60

exists.
(a) preserved (b) opened (c) truncated
Ans.(c) truncated
37. To handle a specific exception type, you can specify it in the __________ clause.
(a) except (b) finally (c) else
Ans.(a) except Explanation: The except clause is designed to catch specific exception types.
38. To read a file as a binary, you open it in __________ mode.
(a) "rb" (b) "wb" (c) "ab"
Ans.(a) "rb" Explanation: The "rb" mode opens a file for reading binary data.
39. The __________ method allows you to read data until the end of the file.
(a) read() (b) readall() (c) readuntil()
Ans.(a) read() Explanation: The read() method continues until it reaches the EOF.
40. To write binary data to a file, use the __________ mode.
(a) "wt" (b) "wb" (c) "rt"
Ans.(b) "wb" Explanation: The "wb" mode is specifically for writing binary data.
41. The __________ keyword allows you to catch any exception, regardless of its type.
(a) catch (b) except (c) any
Ans.(b) except Explanation: The except keyword can be used to catch all exceptions.
42. If you want to read a specific number of bytes from a binary file, you can use the __________ method.
(a) read() (b) readline() (c) readn()
Ans.(a) read() Explanation: The read() method can take an argument to limit the number of bytes read.
43. To ensure that a file is closed automatically after its block of code is executed, use the __________
statement.
(a) with (b) try (c) as
Ans.(a) with Explanation: The with statement manages file resources effectively.
44. A file opened in __________ mode allows you to read and write data, and does not truncate the file.
(a) "a+" (b) "r+" (c) "w+"
Ans.(b) "r+" Explanation: The "r+" mode allows for both reading and writing without truncation.
45. If you want to copy data from one file to another in binary mode, you typically open both files in __________
mode.
(a) "r" (b) "rb" and "wb" (c) "a"
Ans.(b) "rb" and "wb"
46. A common exception raised when attempting to divide by zero is a __________.
(a) ZeroDivisionError (b) ArithmeticError (c) ValueError
Ans.(a) ZeroDivisionError Explanation: This specific error indicates a division by zero situation.
47. The __________ exception is raised when a variable is not defined or initialized.
(a) NameError (b) ValueError (c) KeyError
Ans.(a) NameError Explanation: NameError occurs when a variable is referenced before it is assigned.
48. To read the first n bytes of a file, you can pass n as an argument to the __________ method.
(a) read() (b) readline() (c) readlines()
Ans.(a) read() Explanation: The read() method allows specifying the number of bytes to read.
49. To open a file for reading and writing, while creating it if it doesn't exist, you can use the __________
mode.
(a) "a+" (b) "r+" (c) "x+"
Ans.(c) "x+" Explanation: The "x+" mode opens a file for reading and writing, creating it if absent.

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)
DOWNLOAD OUR PLAY STORE APP FOR SEMESTER COURSES: “ENGINEER’S STUDY ZONE”
Venus Python Programming 61

50. The __________ method is used to write a list of strings to a file.


(a) write() (b) writelines() (c) append()
Ans.(b) writelines() Explanation: The writelines() method writes each string from a list to a file.

Important Question
Q1. What are syntax errors and exceptions? How do they differ in Python?
Q2. Why is exception handling important in programming?
Q3. Explain the usage of the `try-except` block with an example.
Q4. What is the difference between `try-except` and `try-finally` in exception handling?
Q5. How do you define a user-defined exception in Python? Provide a simple example.
Q6. List and explain any five built-in exception classes in Python.
Q7. What is the purpose of the `else` clause in exception handling?
Q8. Write a Python program to handle a division by zero exception.
Q9. What is the difference between a text file and a binary file?
Q10. Explain the various file access modes (`r`, `w`, `a`, `r+`, `w+`, `a+`) in Python.
Q11. How do you open and close files in Python? Why is it important to close a file after performing file
operations?
Q12. Differentiate between reading a file in text mode and binary mode.
Q13. Explain the methods `read()`, `readline()`, and `readlines()` with examples.
Q14. What is the difference between `write()` and `writelines()` in Python?

FOR ANY QUERY MESSAGE OUR SUPPORT TEAM ON “ +91 8051030133” (ONLY WHAT’SAPP MESSAGE)

You might also like