Python
Python
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
result = a % b
print(a <= b) # Outputs: False
print(result) # Outputs: 1
7)Exponentiation (**):
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:
# 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:
• 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.append('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]
Syntax:
list_name.remove(element)
Example:
Explanation:
• remove(): Removes the first occurrence of a specified element from the list.
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:
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:
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.
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.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).
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.
Syntax:
string.split(separator, maxsplit)
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:
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)
• fillchar (optional): Specifies the padding character. Default is space ' '.
Example:
name = "John"
padded_name = name.ljust(10)
print(padded_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)
• fillchar (optional): Specifies the padding character. Default is space ' '.
Example:
name = "John"
centered_name = name.center(10)
print(centered_name) # Outputs: " John "
• 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.
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
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.
Syntax:
string.lower()
Python important questions
Example:
lower_message = message.lower()
ii) isalpha()
The isalpha() method checks whether all characters in a string are alphabetic (letters only).
Syntax:
string.isalpha()
Example:
text1 = "Hello"
text2 = "Hello123"
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"
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:
Explanation:
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.
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.
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.
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.
result = factorial(5)
print(f"The factorial of 5 is: {result}")
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}")
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)
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.
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:
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.
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
• 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.
Examples:
def __str__(self):
return f"({self.x}, {self.y})"
point1 = Point(1, 2)
Python important questions
point2 = Point(3, 4)
• 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).
rect1 = Rectangle(3, 4)
rect2 = Rectangle(3, 4)
rect3 = Rectangle(5, 6)
• 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:
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()
• 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).
class Duck:
def bounce(self):
return "Quack! Quack!"
def bounce(obj):
return obj.bounce()
ball = Ball()
duck = Duck()
• 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.).
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}")
• 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)
• 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.
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.