Win 24
Win 24
Page 1 / 23
Page 2 / 23
Page 3 / 23
if-else Statement
The if-else statement is used to test a condition. If the condition is
True, the code inside the if block is executed. If the condition is
False, the code inside the else block is executed.
Syntax:
if condition:
# Code block to execute if the condition is True
else:
# Code block to execute if the condition is False
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
if-elif-else Statement
The if-elif-else statement is used when there are multiple conditions
to check. Python evaluates each if or elif condition in sequence. If
one of the conditions evaluates to True, the corresponding block of
code is executed, and the rest are skipped. If none of the if or elif
conditions are True, the code inside the else block is executed.
Page 4 / 23
Syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition1 is False and condition2 is
True
else:
# Code block to execute if both condition1 and condition2 are
False
Example:
age = 25
if age < 13:
print("You are a child.")
elif 13 <= age <= 19:
print("You are a teenager.")
elif 20 <= age <= 59:
print("You are an adult.")
else:
print("You are a senior.")
Page 5 / 23
Example:
fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana') # Removes the first occurrence of 'banana'
print(fruits)
Page 6 / 23
Page 7 / 23
Page 8 / 23
Page 9 / 23
Method Description
Page 10 / 23
Page 11 / 23
Example:
def square( x ):
print("Square=",x*x)
# Driver code
square(2)
Output:
Square= 4
Page 12 / 23
def disp_price(self):
print("Price=$",self.price)
car1=Category()
car1.display()
car1.disp_price()
Output:
Name= Maruti
Price=$ 2000
Page 13 / 23
2) Continue statement
This command skips the current iteration of the loop. The statements
following the continue statement are not executed once the Python
interpreter reaches the continue statement.
Example :
for letter in 'python program':
if letter == 'y' or letter == 'm':
continue
print('Current Letter :', letter)
Current Letter : p
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current Letter : p
Current Letter : r
Current Letter : o
Current Letter : g
Current Letter : r
Current Letter : a
Page 14 / 23
3) Pass statement
The pass statement is used when a statement is syntactically
necessary, but no code is to be executed.
Last Letter : n
b) Illustrate with example Method overloading 4M
Ans. It is the ability to define the method with the same name but with a
2M for
different number of arguments and data types. With this ability one explanation
method can perform different tasks, depending on the number of
arguments or the types of the arguments given. 2M for
example
Method overloading is a concept in which a method in a class
performs operations according to the parameters passed to it. As in
other languages we can write a program having two methods with
same name but with different number of arguments or order of
arguments but in python if we will try to do the same we will get the
following issue with method overloading in Python:
# to calculate area of rectangle
def area(length, breadth):
calc = length * breadth
print calc
#to calculate area of square
def area(size):
calc = size * size
print calc
area(3)
area(4,5)
Output:
9
TypeError: area() takes exactly 1 argument (2 given)
Page 15 / 23
Python does not support method overloading, that is, it is not possible
to define more than one method with the same name in a class in
Python.
This is because method arguments in python do not have a type. A
method accepting one argument can be called with an integer value, a
string or a double as shown in next
example.
class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2
Same method works for three different data types. Thus, we cannot
define two methods with the same name and same number of
arguments but having different type as shown in the above example.
They will be treated as the same method. It is clear that method
overloading is not supported in python but that does not mean that we
cannot call a method with different number of arguments. There are a
couple of alternatives available in python that make it possible to call
the same method but with different number of arguments.erample
method overloading
Page 16 / 23
try:
ans=a/b
print("ANS :",ans)
except ZeroDivisionError:
print("Division by Zero........")
output :
Enter the value of a : 10
Enter the value of b : 0
Division by Zero..........
d) Write the output for the following if the variable fruit : .banana 4M
Ans. >> fruit [:3] Each
Output : ban correct
output 1M
>> fruit [3:]
Output : ana
>> fruit [3:3]
Output :
>> fruit [:]
Output : banana
e) Write a Python program to read contents from "a.txt" and write 4M
same contents in "b.txt". Any suitable
Ans. with open("a.txt", "r") as read_file, open("b.txt", "w") as write_file: program
with correct
content = read_file.read() syntax 4M
write_file.write(content)
5. Attempt any TWO of the following: 12M
a) Explain basic operation performed on set with suitable example. 6M
Ans. In Python, sets are a built-in data structure that allows you to perform 2M for each
a variety of operations. Python provides methods and operators to operation
perform the basic set operations, such as union, intersection,
difference, symmetric difference
1. Union ( | or union() )
The union of two sets combines all elements from both sets,
removing duplicates.
A = {1, 2, 3}
B = {3, 4, 5}
print( A | B) # Output: {1, 2, 3, 4, 5}
print( A.union(B)) # Output: {1, 2, 3, 4, 5}
Page 17 / 23
3. Difference ( - or difference() )
The difference of two sets returns a set containing elements present in
the first set but not in the second.
A = {1, 2, 3}
B = {3, 4, 5}
print( A– B) # Output: {1, 2}
print(A.difference(B))# Output: {1, 2}
Page 18 / 23
defprint_details(self):
print("Student Details:")
print(f"Name: {self.name}")
print(f"Roll No: {self.roll_no}")
print(f"Address: {self.address}")
Page 19 / 23
student.print_details()
OUTPUT:
Enter the student's name:
Alice
Enter the student's roll number:101
Enterthestudent'saddress:123MainSt
Student Details:
Name:Alice
Roll No:101
Address:123MainSt
6. Attempt any TWO of the following: 12M
a) Determine various data types available in Python with example. 6M
Ans. Python provides a variety of built-in data types, which can be
classified into several categories based on their characteristics. Here's 2M for each
a detailed description of the most common data types in Python with category
examples:
1. Numeric Types
Numeric types are used to store numbers.
a. Integer (int)
An integer is a whole number without a decimal point.
x = 10 # Integer
y = -25 # Negative integer
print(x, type(x))
# Output: 10 <class 'int'>
b. Floating-Point (float)
A float is a number that has a decimal point or is in exponential form.
x = 3.14 # Float
y = -2.71 # Negative float
print(x, type(x))
# Output: 3.14 <class 'float'>
Page 20 / 23
2. Sequence Types
Sequence types store an ordered collection of items.
a. String (str)
A string is a sequence of characters enclosed within single (') or
double (") quotes.
name = "John" # String
message = 'Hello, World!'
print(name, type(name)) # Output: John <class 'str'>
. List (list)
A list is an ordered, mutable collection that can contain elements of
any data type, including other lists.
fruits = ['apple', 'banana', 'cherry'] # List
print(fruits, type(fruits)) # Output: ['apple', 'banana', 'cherry'] <class
'list'>
3. Mapping Type
Mapping types store key-value pairs.
a. Dictionary (dict)
A dictionary is an unordered, mutable collection of key-value pairs,
where each key is unique.
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(person, type(person)) # Output: {'name': 'Alice', 'age': 25, 'city':
'New York'} <class 'dict'>
4. Set Types
Set types are used to store unordered collections of unique elements.
a. Set (set)
A set is an unordered collection of unique elements, and it is mutable
(you can add or remove items).
fruits = {'apple', 'banana', 'cherry'} # Set
print(fruits, type(fruits)) # Output: {'banana', 'apple', 'cherry'} <class
'set'>
Page 21 / 23
Explanation:
Opening first.txt:
The open() function is used with the 'r' mode to open first.txt in read
mode.
with open() is used to ensure the file is properly closed after the
operation is complete.
Reading the contents:
file1.read() reads the entire content of first.txt into the variable
content.
Opening second.txt:
The open() function is used with the 'w' mode to open second.txt in
write mode.
If second.txt does not exist, it will be created automatically.
Writing the contents:
file2.write(content) writes the content read from first.txt into
second.txt.
c) Explain Try-except-else-finally block used in exception handling 6M
in Python with example.
Ans. The try-except-else-finally block is a comprehensive way to handle Each
exceptions in Python. It allows you to test a block of code for errors explanatio
(try), handle the errors if they occur (except), execute code if no n ,syntax
errors occur (else), and execute cleanup code regardless of whether an and
error occurred or not (finally). example
2M
try:
# Code that might raise an exceptionexcept ExceptionType:
# Code to handle the exception
else:
Page 22 / 23
Explanation of Components
try Block: Contains the code that might raise an exception.
except Block: Catches and handles the exception.
else Block: Executes if the try block succeeds without any exceptions.
finally Block: Executes regardless of whether an exception was raised
or not. Typically used for cleanup tasks.
Example:
try:
# Try to open and read a file
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
# Handle the specific exception if the file doesn't exist
print("Error: The file was not found.")
except IOError:
# Handle other I/O errors
print("Error: An IOError occurred.")
else:
# Executes if no exceptions were raised
print("File was read successfully!")
finally:
# Always executes, used to clean up resources
try:
file.close()
print("File has been closed.")
except NameError:
print("File object does not exist.")
Page 23 / 23