PYTHON MODULE
PYTHON MODULE
calculator.py:
# calculator.py
# Addition function
return a + b
# Subtraction function
return a - b
# Multiplication function
return a * b
# Division function
# Power function
return a ** b
# main.py
import calculator
Analysis of Output:
8 5.0
print(square_root(25))
Now, you are importing sqrt from the math module using an alias
square_root, and you can use square_root(25) instead of sqrt(25). The
output will still be:
5.0
To import a specific function from a module, you can use the from
module_name import function_name syntax. This allows you to access
only the specific function from the module, rather than importing the
entire module.
# math_operations.py
return a + b
return a - b
return a * b
return a / b
Now, if you only want to use the add function, you can import it
specifically as follows:
result = add(10, 5)
print(result) # Output: 15
This imports only the add function, and you can directly use it in your
script.
except ValueError:
Explanation:
If the input is not a valid number (for example, if the user enters a
string), it will raise a ValueError, which is caught by the except
block, and a message is printed.
import package.module:
Example:
import math_operations
result = math_operations.add(10, 5)
print(result) # Output: 15
This syntax is better when you want to keep the module's namespace
clear and avoid name conflicts.
Example:
result = add(10, 5)
print(result) # Output: 15
This syntax is preferred when you are going to use a specific module's
functionality extensively in the code and want to avoid repeating the
module name.
Conclusion:
Use from package import module when you want to directly use the
module and don't mind importing everything from it.
Without the __init__.py file, Python would not recognize the directory as a
package, and you would not be able to import modules from it.
Example:
# directory structure:
# mypackage/
# ├── __init__.py
# ├── module1.py
# └── module2.py
This allows you to import mypackage and use function1 and function2
directly without referencing the individual modules:
import mypackage
mypackage.function1()
mypackage.function2()
b. Python program to open a file, write some text, and then read
it back
content = file.read()
print(content)
Explanation:
1. The with open() statement ensures that the file is properly closed
after reading or writing.
2. In the first block, we open the file in write mode ("w") and write
some text to it.
3. In the second block, we open the same file in read mode ("r") and
print its contents.
print(100 / num)
Possible Exceptions:
Explanation: The int() function will fail because it cannot parse a non-
numeric string into an integer.
Example input: 0
Conclusion:
Example:
class Person:
def display(self):
p = Person("Alice", 30)
print(p.name) # OK
file.write("Hello, Python!")
content = file.read()
print(content)
Given Code:
try:
x=1/0
except ValueError:
except ZeroDivisionError:
finally:
print("Execution complete")
Step-by-Step Execution:
1. x = 1 / 0 causes a ZeroDivisionError.
7. Execution complete
✅ Final Output:
Execution complete
Class:
A class is a blueprint or template for creating objects. It defines
attributes and methods that the objects created from the class will
have.
Example:
class Dog:
def bark(self):
print("Woof!")
Object:
An object is an instance of a class. It is created using the class and
can use the attributes and methods defined in that class.
Example:
my_dog = Dog()
try:
content = file.read()
print(content)
file.close()
except FileNotFoundError:
my_package/
__init__.py
utils/
__init__.py
Example:
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
def honk(self):
print("Car is honking")
my_car = Car()
Here, Car inherits the move method from Vehicle, so it can use both
move() and honk().
Folder structure:
calculator/
├── __init__.py
└── basic_ops.py
Content of basic_ops.py:
# calculator/basic_ops.py
return a + b
return a - b
# main.py
class Animal:
def speak(self):
class Cat(Animal):
def speak(self):
print("Meow")
pet = Animal()
Explanation:
The user expected "Meow" because they likely thought pet was an
instance of Cat, but it's actually an instance of Animal.
pet = Cat()
Also, the indentation is incorrect in this code, which would cause a syntax
error. It should be properly indented like this:
class Animal:
def speak(self):
class Cat(Animal):
def speak(self):
print("Meow")
pet = Cat()
Sure! Here's the complete answer to question 7, clearly broken down and
written without using functions.
read():
o Example:
o content = file.read()
o print(content)
o file.close()
readline():
o Reads the next line from the file (up to the next newline \n).
o Example:
o line = file.readline()
o print(line)
o file.close()
Folder structure:
shapes
__init__.py
circle.py
rectangle.py
Content of circle.py:
# shapes/circle.py
pi = 3.1416
def area(radius):
Content of rectangle.py:
# shapes/rectangle.py
# main.py
Example:
try:
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
except ValueError:
Absolutely! Here's the full breakdown for each part of your question,
without using functions.
Compile-time Errors:
o Example:
o print("x is 5")
Runtime Errors:
o Example:
o x = 10 / 0 # ZeroDivisionError
name,age,city
Alice,30,New York
Bob,25,London
reader = csv.DictReader(file)
data_list = []
data_list.append(dict(row))
print(data_list)
file.close()
Output:
[{'name': 'Alice', 'age': '30', 'city': 'New York'}, {'name': 'Bob', 'age': '25',
'city': 'London'}]
content = file.read()
words = content.split()
word_count = len(words)
file.close()
This reads the file, splits the content by whitespace, and counts the
number of words.
Sure! Here's a complete and clear explanation for all parts of your
question — all written without using functions, as requested.
try block:
Used to wrap code that might raise an exception.
except block:
Contains the code that runs if an exception occurs in the try block.
finally block:
Runs no matter what — whether an exception was raised or not.
It's often used to release resources (like closing a file or database
connection).
Example:
try:
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
except ValueError:
finally:
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
pass
obj = Child()
obj.show()
Analysis:
Since Child does not override the show() method, it uses the
show() method defined in Parent.
Parent class
Conclusion:
This shows simple inheritance — the child inherits methods and
attributes from the parent unless overridden.
class Student:
self.name = name
self.grade = grade
def display_info(self):
print("Name:", self.name)
print("Grade:", self.grade)
student1.display_info()
Output:
Name: Alice
Grade: A
Absolutely! Here's your answer for all parts of the question, clearly
explained without using functions, as requested.
Example:
x = 10
y=0
result = x / y # Raises ZeroDivisionError
Error Message:
This is a runtime error and will crash the program unless properly
handled with a try-except block.
import os
file_path = "example.txt"
if os.path.exists(file_path):
content = file.read()
print(content)
file.close()
else:
This code checks for the file’s existence before trying to open it, avoiding
a FileNotFoundError.
content = file.read()
print(content)
If an error occurs before closing, the file may stay open, which can
lead to memory leaks or file locking issues.
content = file.read()
print(content)
This approach automatically closes the file once the block is
exited — even if an error occurs inside the block.
It’s safer and cleaner, and is the recommended way for working
with files in Python.