0% found this document useful (0 votes)
7 views27 pages

Python

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

Python

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

Python important questions

1) Explain the following functions in Python with examples. i) str


() ii) input () iii) len () iv) float ()
Ans=i) str():
converts integers, floats, or other data types into a string format, which allows for string-
specific operations like concatenation.
num = 42
str_num = str(num)
print(str_num) # Outputs: '42'
ii) input():
prompts the user to enter something via the keyboard. Whatever the user types is
returned as a string and can be stored in a variable for further use.
name = input("Enter your name: ")
print("Hello, " + name)
iii) len():
can be used on strings, lists, tuples, dictionaries, and other collections to determine their
length. For strings, it counts the number of characters; for lists and tuples, it counts the
number of elements; for dictionaries, it counts the number of key-value pairs.
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # Outputs: 5
iv) float():
converts integers or strings that represent numeric values into floating-point numbers. It's
useful for mathematical operations that require decimal precision.
num_str = "3.14"
num_float = float(num_str)
print(num_float) # Outputs: 3.14

num_int = 42
num_float = float(num_int)
print(num_float) # Outputs: 42.0
Python important questions
2)Explain arithmetic
operators and comparison operators in python
with suitable examples

Arithmetic Operators: are used to Comparison Operators: True or False


perform mathematical operations on numeric values based on the comparison
(operands).

1) Addition (+): 1) Equal to (==):


• Adds two operands • Checks if the values of two operands are equal.
a = 10 a = 10
b=5 b=5
result = a + b
print(a == b) # Outputs: False
print(result) # Outputs: 15
2)Not equal to (!=):
2)Subtraction (-):
• Checks if the values of two operands are not
• Subtracts the right operand from the left operand. equal.
a = 10 a = 10
b=5 b=5
result = a - b
print(a != b) # Outputs: True
print(result) # Outputs: 5
3) Greater than (>):
3) Multiplication (*):
• Checks if the left operand is greater than the
• Multiplies two operands. right operand.
a = 10 a = 10
b=5 b=5
result = a * b print(a > b) # Outputs: True
print(result) # Outputs: 50
4) Less than (<):
4) Division (/):
• Checks if the left operand is less than the right
• Divides the left operand by the right operand operand.
(always results in a float).
a = 10
a = 10
b=5
b=5
print(a < b) # Outputs: False
result = a / b

print(result) # Outputs: 2.0


Python important questions
5) Floor Division (//): 5) Greater than or equal to (>=):
• Divides the left operand by the right operand and • Checks if the left operand is greater than or
returns the integer value (floor) of the quotient. equal to the right operand.
a = 10
a = 10
b=3
b=5
result = a // b
print(a >= b) # Outputs: True
print(result) # Outputs: 3
6) Less than or equal to (<=):
6)Modulus (%):
• Checks if the left operand is less than or equal to
• Returns the remainder of the division of the left the right operand.
operand by the right operand.
a = 10
a = 10
b=5
b=3

result = a % b
print(a <= b) # Outputs: False

print(result) # Outputs: 1

7)Exponentiation (**):

• Performs exponentiation on the left operand by


the right operand.

a=2

b=3

result = a ** b

print(result) # Outputs: 8
Python important questions
3)Explain looping control statements in Python with a
syntax and example to each.
Looping control statements in Python are used to alter the flow of loops. They allow you to
control how and when the loops execute. There are three main looping control statements in
Python: break, continue, and pass. Let's explain each with syntax and examples:

1. break Statement
The break statement is used to terminate the loop prematurely, bypassing the remaining
iterations.

Syntax:

while condition:
if condition_to_break:
break
Example:
i=0
while i < 5:
print(i)
if i == 3:
break
i += 1

# Output: 0
# 1
# 2
# 3

2. continue Statement
The continue statement skips the rest of the current iteration of a loop and proceeds to the
next iteration.

Syntax:

while condition:
if condition_to_skip_iteration:
continue
Python important questions
Example:

# Example of continue statement in a for loop


for i in range(5):
if i == 2:
continue
print(i)

# Output: 0
# 1
# 3
# 4
3. pass Statement
The pass statement is a null operation; it is used when a statement is required syntactically but
you do not want any command or code to execute.

Syntax:

while condition:

if condition_to_do_nothing:

pass

Example:

python
Copy code
# Example of pass statement in a while loop
i=0
while i < 5:
if i == 2:
pass
else:
print(i)
i += 1

# Output: 0
# 1
# 3
# 4
Explanation:

• break: Immediately exits the loop it is in.

• continue: Skips the current iteration and proceeds with the next iteration of the loop.

• pass: Acts as a placeholder for future code, ensuring that Python's syntax requirements are
met without performing any action.
Python important questions
4)Discuss the following list methods with suitable examples.
i) append() ii) insert() iii) sort() iv) remove()
i) append()
The append() method adds a single element to the end of the list.

Syntax:
list_name.append(element)
Example:

fruits = ['apple', 'banana', 'cherry']

fruits.append('orange')

print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'orange']

In this example, 'orange' is added to the end of the fruits list using append().

ii) insert()
The insert() method inserts an element at a specified position in the list.

Syntax:

list_name.insert(index, element)

Example:

numbers = [1, 2, 3, 5, 6]
numbers.insert(3, 4)
print(numbers) # Outputs: [1, 2, 3, 4, 5, 6]
Here, 4 is inserted at index 3 in the numbers list.

iii) sort()
The sort() method sorts the elements of a list in place.

Syntax:

list_name.sort()

Example:

numbers = [5, 2, 8, 1, 6]
numbers.sort()
print(numbers) # Outputs: [1, 2, 5, 6, 8]

The sort() method arranges the elements of numbers in ascending order.


Python important questions
iv) remove()
The remove() method removes the first occurrence of a specified element from the list.

Syntax:

list_name.remove(element)

Example:

fruits = ['apple', 'banana', 'cherry', 'banana']


fruits.remove('banana')
print(fruits) # Outputs: ['apple', 'cherry', 'banana']
In this example, the first occurrence of 'banana' is removed from the fruits list.

Explanation:

• append(): Adds an element to the end of the list.

• insert(): Inserts an element at a specified position in the list.

• sort(): Sorts the elements of the list in ascending order by default.

• remove(): Removes the first occurrence of a specified element from the list.

5) Explain with suitable example how the data structures are


used to model real-world things
1. Lists
Lists in Python can model collections of items where the order matters and duplicates are
allowed. They are versatile and can represent various real-world scenarios:

Example: Modeling a shopping list.

shopping_list = ['apple', 'banana', 'milk', 'bread']

In this example, shopping_list stores items typically found on a shopping list, where each item
maintains its position and can be accessed individually.

2. Dictionaries
Dictionaries are useful for modeling associations between keys and values, akin to real-world
mappings or relationships:

Example: Modeling a person's attributes.

person = {
'name': 'John',
'age': 30,
'city': 'New York'
}
Python important questions
Here, person stores attributes (name, age, city) of a person, allowing quick access to each
attribute using its key.

3. Sets
Sets are collections of unique elements and are suited for modeling collections where
uniqueness is important:

Example: Modeling unique tags for a blog post.

tags = {'python', 'programming', 'data structures'}

In this case, tags stores unique tags associated with a blog post, ensuring each tag appears only
once regardless of how many times it might be added.

4. Objects (Classes and Instances)


In object-oriented programming, classes and instances model complex real-world entities with
attributes and behaviors:

Example: Modeling a car as an object.

class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def display_info(self):
print(f"{self.brand} {self.model} ({self.year})")

car1 = Car('Toyota', 'Camry', 2020)


car2 = Car('Honda', 'Civic', 2021)

car1.display_info()
car2.display_info()
In this example, Car class defines a blueprint for creating car objects (car1 and car2), each with
specific attributes (brand, model, year) and behaviors (display_info() method).

5. Trees and Graphs


Advanced data structures like trees and graphs can model hierarchical relationships and
networks respectively:

Example: Modeling organizational hierarchy as a tree.

class Employee:
def __init__(self, name, title):
self.name = name
self.title = title
self.subordinates = []
Python important questions
# Creating employees
ceo = Employee('John Doe', 'CEO')
manager1 = Employee('Alice Smith', 'Manager')
manager2 = Employee('Bob Johnson', 'Manager')

# Establishing hierarchy
ceo.subordinates.extend([manager1, manager2])

# Accessing hierarchy
for manager in ceo.subordinates:
print(f"{manager.name}, {manager.title}")
In this example, Employee class models employees with a hierarchical structure (ceo at the
top, with manager1 and manager2 as subordinates).

• Conclusion
Data structures are essential tools in programming for organizing, storing, and manipulating
data in ways that reflect real-world scenarios and relationships. They provide a powerful
framework for handling complexity and representing various entities and their interactions
within software applications.

6) Explain the following Python string handling methods with


suitable examples. i) split() ii) Istrip() iii) ljust() iv) center().
i) split()
The split() method splits a string into a list of substrings based on a delimiter. If no delimiter is
specified, it splits by whitespace.

Syntax:

string.split(separator, maxsplit)

• separator (optional): Specifies the delimiter. Default is whitespace.


• maxsplit (optional): Specifies how many splits to do. Default is -1 (all occurrences).
Example:
sentence = "Hello, world! How are you?"
words = sentence.split()
print(words) # Outputs: ['Hello,', 'world!', 'How', 'are', 'you?']

numbers = "1-2-3-4-5"
num_list = numbers.split('-')
print(num_list) # Outputs: ['1', '2', '3', '4', '5']

ii) strip()
The strip() method removes leading and trailing whitespace (spaces, tabs, newlines) from a
string.
Python important questions
Syntax:

string.strip()

Example:

text = " Hello, world! "


clean_text = text.strip()
print(clean_text) # Outputs: "Hello, world!"

iii) ljust()
The ljust() method left-aligns a string in a field of a given width by padding it with spaces (or
another specified character) on the right.

Syntax:

string.ljust(width, fillchar)

• width: Specifies the width of the field.

• fillchar (optional): Specifies the padding character. Default is space ' '.

Example:

name = "John"
padded_name = name.ljust(10)
print(padded_name) # Outputs: "John "

centered_name = name.ljust(10, '-')


print(centered_name) # Outputs: "John------"

iv) center()
The center() method centers a string in a field of a given width by padding it with spaces (or
another specified character) on both sides.

Syntax:

string.center(width, fillchar)

• width: Specifies the width of the field.

• fillchar (optional): Specifies the padding character. Default is space ' '.

Example:

name = "John"
centered_name = name.center(10)
print(centered_name) # Outputs: " John "

centered_name = name.center(10, '-')


print(centered_name) # Outputs: "---John---"
Python important questions
Explanation:
• split(): Splits a string into a list of substrings based on a delimiter.

• strip(): Removes leading and trailing whitespace from a string.

• ljust(): Left-aligns a string within a specified width, padding it on the right with spaces (or
another specified character).

• center(): Centers a string within a specified width, padding it on both sides with spaces (or
another specified character).

These methods are useful for manipulating strings in various ways, such as splitting them into
parts, removing unwanted whitespace, and formatting them within specific field widths.

7) Explain with suitable Python program segments: i)


os.path.getsize(path) ii) os.listdir(path) iii) os.path.exi
i) os.path.getsize(path)
The os.path.getsize() function returns the size of a file in bytes, given its path.

Syntax:

import os

size = os.path.getsize(path)

Example:

import os

file_path = '/path/to/file.txt'
file_size = os.path.getsize(file_path)
print(f"The size of '{file_path}' is {file_size} bytes.")

ii) os.listdir(path)
The os.listdir() function returns a list of all files and directories in the specified directory path.

Syntax:

import os

contents = os.listdir(path)
Python important questions
Example:

import os

# List all files and directories in a directory


dir_path = '/path/to/directory'
contents = os.listdir(dir_path)
print(f"Contents of '{dir_path}':")
for item in contents:
print(item)
iii) os.path.exists(path)
The os.path.exists() function checks whether a file or directory exists at the specified path.

Syntax:

import os
exists = os.path.exists(path)
Example:

import os

file_path = '/path/to/file.txt'
if os.path.exists(file_path):
print(f"'{file_path}' exists.")
else:
print(f"'{file_path}' does not exist.")
Explanation:
• os.path.getsize(path): Retrieves the size of a file specified by path. It's useful for checking
file sizes before performing operations that depend on file size.

• os.listdir(path): Returns a list of names of files and directories in the specified path. This
allows you to iterate over the contents of a directory programmatically.

• os.path.exists(path): Checks whether a file or directory exists at the given path. This is
useful for verifying the existence of files before attempting to open or manipulate them.

7) Explain the following Python string methods with suitable


examples. i) lower() ii) isalpha() iii) endswith() iv) isspace()
i) lower()
The lower() method converts all characters in a string to lowercase.

Syntax:

string.lower()
Python important questions
Example:

message = "Hello World!"

lower_message = message.lower()

print(lower_message) # Outputs: "hello world!"

ii) isalpha()
The isalpha() method checks whether all characters in a string are alphabetic (letters only).

Syntax:

string.isalpha()

Example:

text1 = "Hello"
text2 = "Hello123"

print(text1.isalpha()) # Outputs: True


print(text2.isalpha()) # Outputs: False

iii) endswith()
The endswith() method checks if a string ends with a specified suffix. It returns True if the
string ends with the specified suffix, otherwise False.

Syntax:

string.endswith(suffix)

Example:

file_name = "document.pdf"

print(file_name.endswith(".pdf")) # Outputs: True


print(file_name.endswith(".txt")) # Outputs: False

iv) isspace()
The isspace() method returns True if all characters in the string are whitespace characters
(spaces, tabs, newline), otherwise False.

Syntax:

string.isspace()
Python important questions
Example:

space_str = " "

mix_str = " Hello "

print(space_str.isspace()) # Outputs: True

print(mix_str.isspace()) # Outputs: False

Explanation:

• lower(): Converts all characters in a string to lowercase.


• isalpha(): Checks if all characters in a string are alphabetic.
• endswith(suffix): Checks if a string ends with the specified suffix.
• isspace(): Checks if all characters in a string are whitespace characters.

8) Explain permanent delete and safe delete with a suitable


Python programming example to each.
Permanent Delete
Permanent delete refers to the irreversible removal of data or files from a system, typically
without the ability to recover them afterward. This operation is commonly used when the data
or files are no longer needed and should be completely erased.

Python Example for Permanent Delete:


To achieve permanent deletion of a file in Python, you can use the os.remove() function, which
deletes a file from the filesystem. Here's an example:

import os

file_path = 'path/to/file.txt'

try:
os.remove(file_path)
print(f"File '{file_path}' has been permanently deleted.")
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except PermissionError:
print(f"Permission denied to delete file '{file_path}'.")
In this example:
• os.remove(file_path) attempts to permanently delete the file specified by file_path.

• Error handling (try-except) is used to manage potential exceptions, such as


FileNotFoundError if the file does not exist, or PermissionError if the user does not have
sufficient permissions to delete the file.
Python important questions
Safe Delete
Safe delete involves deleting data or files in a way that allows for potential recovery or backup
before the deletion is finalized. This method ensures that the data can be restored or
recovered if needed, providing a safety net against accidental deletion.

Python Example for Safe Delete:


To implement safe deletion in Python, you might move files to a temporary directory or create
backups before deleting them permanently. Here’s a basic example using the shutil.move()
function to move a file to a temporary directory before deletion:

import os
import shutil
import tempfile

file_path = 'path/to/file.txt'
backup_dir = tempfile.mkdtemp()

try:
shutil.move(file_path, backup_dir)
print(f"File '{file_path}' moved to '{backup_dir}' for safe deletion.")
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except PermissionError:
print(f"Permission denied to move file '{file_path}'.")
In this example:
• tempfile.mkdtemp() creates a temporary directory (backup_dir) where the file will be
moved.

• shutil.move(file_path, backup_dir) moves the file from its original location (file_path) to
the temporary directory (backup_dir).

After moving the file to a safe location, you can later decide to delete it permanently, knowing
that you have a backup or can recover it if necessary.

Conclusion
• Permanent delete irreversibly removes data or files from the system using methods like
os.remove() in Python.

• Safe delete involves moving data or files to a safe location (e.g., temporary directory or
backup) before considering permanent deletion, using methods like shutil.move() for safer
handling.
Python important questions
9)Explain the role of Assertions in Python with a suitable
program.
Assertions in Python are statements used to assert that a condition is true in the code. They
are primarily used for debugging and testing purposes to check assumptions made during the
program's development. If an assertion fails (i.e., the condition is false), an AssertionError
exception is raised, indicating a problem in the program's logic.

Role of Assertions:
1. Debugging: Assertions help developers identify logical errors and inconsistencies early in
the development process. They act as sanity checks to verify that certain conditions are
met during execution.

2. Testing: Assertions are valuable in unit testing to validate expected behaviors and
assumptions about the program's state at specific points.

3. Documentation: Assertions serve as documentation within the code, stating assumptions


and expectations clearly for future maintenance and understanding.

def calculate_discount(price, discount_rate):


assert 0 <= discount_rate <= 1, "Discount rate must be between 0 and 1"

discounted_price = price * (1 - discount_rate)


return discounted_price

print(calculate_discount(100, 0.2)) # Valid discount rate


print(calculate_discount(200, 1.5)) # Invalid discount rate

Best Practices for Using Assertions:


• Use assertions to check for conditions that should never occur unless there is a bug in the
code (i.e., internal errors).
• Avoid using assertions for input validation or handling user errors; use exceptions or
proper error handling for those cases.
• Ensure assertions do not cause side effects or change the program's state when enabled in
production code (they are typically disabled in production for performance reasons).

10) Explain the following functions with examples i)


shutil.copytree (source, destination) iii) os.unlink(path) ii)
shutil.move(source, destination) iv) shutil.rmtree(path)
Python important questions
i) shutil.copytree(source, destination)
The shutil.copytree() function recursively copies an entire directory tree from source to
destination.
Syntax:
import shutil
shutil.copytree(source, destination)
Example:
import shutil

source_dir = '/path/to/source_directory'
destination_dir = '/path/to/destination_directory'

shutil.copytree(source_dir, destination_dir)
In this example:
• All contents from source_dir (including subdirectories and files) are recursively copied to
destination_dir.

ii) shutil.move(source, destination)


The shutil.move() function moves a file or directory source to destination.
Syntax:
import shutil
shutil.move(source, destination)
Example:
import shutil

source_file = '/path/to/source_file.txt'
destination_file = '/path/to/destination_directory/file.txt'

shutil.move(source_file, destination_file)
In this example:
• The file source_file is moved to destination_file. If destination_file does not exist, it is
created.
iii) os.unlink(path)
The os.unlink() function deletes a file specified by path.
Syntax:
import os
os.unlink(path)
Example:
import os

file_to_delete = '/path/to/file.txt'

os.unlink(file_to_delete)
In this example:
• The file located at file_to_delete is permanently deleted from the filesystem.
Python important questions
iv) shutil.rmtree(path)
The shutil.rmtree() function deletes a directory and all its contents recursively.
Syntax:
import shutil
shutil.rmtree(path)
Example:
import shutil

directory_to_delete = '/path/to/directory'

shutil.rmtree(directory_to_delete)
In this example:
• The directory directory_to_delete and all its contents (subdirectories and files) are
recursively deleted from the filesystem.

11) Discuss how the debugger feature of with suitable example.


IDLE can be used to debug a Python program
The debugger is a crucial tool for developers to inspect and analyze their code during
execution, helping to identify and fix errors or bugs efficiently. IDLE, Python's Integrated
Development and Learning Environment, includes a debugger that allows developers to step
through their code, examine variables, and trace the flow of execution. Let's discuss how to use
the debugger in IDLE with a suitable example.
Using IDLE Debugger: Example
Consider a simple Python script that calculates the factorial of a number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

result = factorial(5)
print(f"The factorial of 5 is: {result}")

Steps to Debug in IDLE:


1. Set a Breakpoint: Click on the left margin of the code editor (next to line numbers) to set
a breakpoint. A breakpoint is a point in your code where the debugger will pause
execution.
2. Start Debugging: Run the script in debugging mode by selecting Debug -> Debugger from
the menu, or pressing F5. Alternatively, you can run the script normally (Run -> Run
Module or F5) and it will stop at the first breakpoint.
3. Debugger Controls: Once the debugger is active, you'll see the script paused at the
breakpoint. You can use the following controls to navigate through the code:
o Step Into (F7): Executes the current line of code and stops at the first statement of
the next function called.
Python important questions
o Step Over (F8): Executes the current line of code. If the current line calls a function,
it executes the entire function and stops at the line after the function call.
o Step Out (Shift + F8): Continues execution until the current function returns.
o Resume (F5): Continues execution until the next breakpoint or the end of the
program.
o Toggle Breakpoint: Click on the left margin to add/remove breakpoints.
4. Inspect Variables: While debugging, you can inspect the current value of variables by
hovering over them or by typing their names in the interactive console.
5. Evaluate Expressions: You can also evaluate expressions in the interactive console while
debugging to check their current values.
6. Finish Debugging: Once you've identified and fixed the issue, you can finish debugging by
either closing the debugger window or running the script normally (Run -> Run Module or
F5).
Benefits of Using Debugger in IDLE:
• Error Identification: Helps identify logical errors and unexpected behavior in the code.
• Variable Inspection: Allows developers to inspect the values of variables during execution,
aiding in understanding the state of the program.
• Flow Control: Provides control over the execution flow, allowing step-by-step execution to
trace how values change.
• Efficient Debugging: Facilitates faster debugging and troubleshooting, reducing the time
spent on identifying and fixing issues.
12) Explain the following with syntax and suitable code snippet i)
Class definition ii) instantiation iii) passing an instance (or object)
as an argument iv) instances as return values.
i) Class Definition
In Python, a class is a blueprint for creating objects (instances) that share attributes and
behaviors. It defines the structure and behavior of objects of that type.
Syntax:
class ClassName:

def __init__(self, parameter1, parameter2):


self.parameter1 = parameter1
self.parameter2 = parameter2

def method(self):
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display_info(self):
print(f"Car: {self.brand} {self.model}")

car1 = Car("Toyota", "Camry")


Python important questions
car2 = Car("Honda", "Civic")

# Accessing attributes and methods of instances


car1.display_info() # Outputs: Car: Toyota Camry
car2.display_info() # Outputs: Car: Honda Civic
ii) Instantiation
Instantiation is the process of creating an instance (object) of a class. It involves calling the
class constructor (__init__() method) to initialize the object's attributes.
Syntax:
instance_name = ClassName(arguments)
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person1 = Person("Alice", 30)


person2 = Person("Bob", 25)

print(person1.name, person1.age) # Outputs: Alice 30


print(person2.name, person2.age) # Outputs: Bob 25
iii) Passing an Instance as an Argument
In Python, instances (objects) of a class can be passed as arguments to functions or methods,
allowing operations to be performed on those objects.
Syntax:
def function_name(instance):
function_name(instance_name)
Example:

class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

def print_area(rect):
print(f"Area of the rectangle is: {rect.area()}")

rectangle = Rectangle(5, 3)

print_area(rectangle) # Outputs: Area of the rectangle is: 15


Python important questions
iv) Instances as Return Values
Functions or methods in Python can return instances (objects) of a class as return values,
allowing for dynamic creation and manipulation of objects.
Syntax:
def function_name(arguments):
return instance
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def create_point(x, y):


return Point(x, y)

point1 = create_point(3, 4)
print(f"Point coordinates: ({point1.x}, {point1.y})") # Outputs: Point coordinates: (3, 4)
Explanation:
• Class Definition: Defines a blueprint for creating objects with attributes and methods.
• Instantiation: Creates instances (objects) of a class using the class constructor (__init__()
method).
• Passing an Instance as an Argument: Allows objects to be passed as arguments to
functions or methods for processing.
• Instances as Return Values: Functions or methods can return newly created instances of a
class, enabling flexible object creation and manipulation.

13) Explain the following with examples: i) Pure functions ii)


Modifiers

i) Pure Functions
A pure function is a function that:
• Given the same input, always returns the same output.
• Produces no side effects, meaning it does not modify any state or cause any observable
change outside the function.
Pure functions are predictable, making them easier to reason about, test, and debug. They are a
key concept in functional programming.

Examples:

1. Pure Function Example:


def add(a, b):
return a + b

result = add(3, 4)
print(result) # Outputs: 7
Python important questions
• The add() function always returns the sum of its two arguments a and b without modifying
any external state or variables. It has no side effects.

2. Impure Function Example:


total = 0

def add_to_total(num):
global total
total += num
return total

result1 = add_to_total(5)
print(result1) # Outputs: 5

result2 = add_to_total(3)
print(result2) # Outputs: 8

• The add_to_total() function modifies the global variable total each time it is called, which
changes the state of the program outside of the function. It produces side effects.

ii) Modifiers
Modifiers, in the context of functions or methods, are operations that modify the state of an
object or data structure directly. They often alter the internal state of an object or variable without
necessarily returning a value.

Examples:

1. Modifier Example:
class Circle:
def __init__(self, radius):
self.radius = radius

def set_radius(self, new_radius):


self.radius = new_radius

# Creating a Circle object


circle = Circle(5)
print(circle.radius) # Outputs: 5

# Using the modifier method to change the radius


circle.set_radius(10)
print(circle.radius) # Outputs: 10

• In this example, the set_radius() method of the Circle class modifies the radius attribute of
the circle object directly. It does not return a value but changes the state of the object
itself.
Python important questions
2. Non-Modifier Example:
def increment(num):
return num + 1

value = 5
new_value = increment(value)
print(value) # Outputs: 5 (original value unchanged)
print(new_value) # Outputs: 6

• The increment() function takes an input num, increments it by 1, and returns the result. It
does not modify the original value of num passed to it, demonstrating a function that does
not act as a modifier.

Summary:
• Pure Functions: Always produce the same output for the same input and have no side
effects.

• Modifiers: Functions or methods that modify the state of objects or variables directly,
often without returning a value.

14) Explain the following with examples: i) Operator overloading ii)


Polymorphism
i) Operator Overloading
Operator overloading refers to the ability to define how operators behave for custom objects or
classes. In Python, this is achieved by defining special methods that correspond to operator
symbols (e.g., +, -, *, /, ==, !=, etc.). These special methods are also known as magic or dunder
(double underscore) methods.

Examples:

1. Adding Two Objects:


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


return Point(self.x + other.x, self.y + other.y)

def __str__(self):
return f"({self.x}, {self.y})"

point1 = Point(1, 2)
Python important questions
point2 = Point(3, 4)

result = point1 + point2


print(result) # Outputs: (4, 6)

• In this example, the __add__() method is defined to overload the + operator for Point
objects. When point1 + point2 is called, it invokes point1.__add__(point2) and returns a
new Point object with coordinates (4, 6).

2. Comparing Two Objects:


class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def __eq__(self, other):


return self.width == other.width and self.height == other.height

rect1 = Rectangle(3, 4)
rect2 = Rectangle(3, 4)
rect3 = Rectangle(5, 6)

print(rect1 == rect2) # Outputs: True


print(rect1 == rect3) # Outputs: False

• Here, the __eq__() method is defined to overload the == operator for Rectangle objects. It
checks if two Rectangle objects have the same width and height.

ii) Polymorphism
Polymorphism is the ability of different objects to respond to the same method or function in
different ways based on their own implementations. It allows for flexibility in programming by
enabling objects of different classes to be treated as objects of a common superclass.

Examples:

1. Polymorphism with Inheritance:


class Animal:
def sound(self):
pass

class Dog(Animal):
def sound(self):
return "Woof!"

class Cat(Animal):
def sound(self):
Python important questions
return "Meow!"

def make_sound(animal):
return animal.sound()

dog = Dog()
cat = Cat()

print(make_sound(dog)) # Outputs: "Woof!"


print(make_sound(cat)) # Outputs: "Meow!"

• In this example, Animal is a superclass with a sound() method. Dog and Cat are subclasses
that override the sound() method with their own implementations. The make_sound()
function demonstrates polymorphism by calling sound() on different Animal objects (dog
and cat).

2. Polymorphism with Duck Typing:


class Ball:
def bounce(self):
return "Bouncing ball!"

class Duck:
def bounce(self):
return "Quack! Quack!"

def bounce(obj):
return obj.bounce()

ball = Ball()
duck = Duck()

print(bounce(ball)) # Outputs: "Bouncing ball!"


print(bounce(duck)) # Outputs: "Quack! Quack!"

• Here, Ball and Duck are unrelated classes with a bounce() method. The bounce() function
demonstrates polymorphism by accepting objects of different types (Ball and Duck) that
both respond to bounce().

Summary:
• Operator Overloading: Enables custom behavior for operators (+, -, ==, etc.) in user-defined
classes by defining corresponding special methods (__add__(), __eq__(), etc.).

• Polymorphism: Allows objects of different classes to be treated as objects of a common


superclass, enabling flexibility and reusability in code.
Python important questions
15)Explain the methods_init_and_str_ with suitable examples.
__init__() Method
The __init__() method is a constructor method that is automatically called when an instance
(object) of the class is created. It initializes the attributes of the object and can accept parameters
to set initial values for those attributes.

Syntax:
class ClassName:
def __init__(self, parameter1, parameter2, ...):
self.attribute1 = parameter1
self.attribute2 = parameter2
...

Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")

person1 = Person("Alice", 30)


person2 = Person("Bob", 25)

person1.display_info() # Outputs: Name: Alice, Age: 30


person2.display_info() # Outputs: Name: Bob, Age: 25

• In this example, the __init__() method initializes each Person object with name and age
attributes. These attributes are set when instances (person1 and person2) are created,
allowing each instance to store specific data about different people.

__str__() Method
The __str__() method is used to define a string representation of an object. It is automatically
called when you use the str() function or print() function on an object. This method should return a
human-readable string that represents the object.

Syntax:
class ClassName:
def __str__(self):
return "String representation of the object"
Example:
class Point:
def __init__(self, x, y):
self.x = x
Python important questions
self.y = y

def __str__(self):
return f"Point({self.x}, {self.y})"

point1 = Point(3, 4)
point2 = Point(-1, 2)

print(point1) # Outputs: Point(3, 4)


print(point2) # Outputs: Point(-1, 2)

• In this example, the __str__() method in the Point class defines how instances of Point are
represented as strings. When print(point1) is called, it invokes point1.__str__(), which
returns "Point(3, 4)", providing a clear and descriptive representation of the Point object's
coordinates.

Summary:
• __init__(): Initializes the attributes of an object when it is created, allowing for customized
initialization based on parameters passed to the constructor.

• __str__(): Provides a string representation of an object, allowing developers to define how


instances of a class are displayed when converted to strings or printed.

These special methods enhance the usability and readability of Python classes by defining
initialization behavior (__init__()) and string representations (__str__()) that reflect the state and
purpose of objects in a clear and concise manner.

You might also like