Python Programming
Python Programming
Unit 1
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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
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
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
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
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
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
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
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)