Python Paper 1
11) How to check whether a given number is Armstrong number or not
Ans: example
a = 153
1*1*1 = 1
5*5*5 = 125
3*3*3 = 27
1+125+27 =
n = 153
if a == n :
return Armstrong
else
return Not Armstrong
program :
A = 153
temp = A
sum = 0
while temp > 0:
digit = temp % 10
sum += digit **3
temp = temp / 10
if A == sum :
return Armstrong
else
return Not Armstrong
-----------------------------------------------------------------------------------------------------------------------------
12) What is indexing and negative indexing in Tuple?
my_tuple = ("apple", "banana", "cherry", "date")
# Slicing with positive indices
print(my_tuple[1:3]) # Output: ('banana', 'cherry')
# Slicing with negative indices
print(my_tuple[-3:-1]) # Output: ('banana', 'cherry')
-----------------------------------------------------------------------------------------------------------------------------
13) Consider a Rectangle Class. Write Python code to Check the Area of the First Rectangle is
Greater than Second by Overloading ‘>’ Operator
Example : __gt__(self, other):
program:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# Method to calculate the area of the rectangle
def area(self):
return self.width * self.height
# Overloading the '>' operator to compare areas
def __gt__(self, other):
return self.area() > other.area()
# Creating two Rectangle objects
rect1 = Rectangle(4, 5) # Area = 4 * 5 = 20
rect2 = Rectangle(6, 3) # Area = 6 * 3 = 18
# Checking if the area of rect1 is greater than rect2
if rect1 > rect2:
print("The area of the first rectangle is greater than the second.")
else:
print("The area of the second rectangle is greater than the first.")
-----------------------------------------------------------------------------------------------------------------------------
14) Explain values and items method used in dictionary with example
dict.values()
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
Output :
Program:
Output:
16) Explain in detail about Python Files, its types, functions and operations that can be performed on files with examples.
Python Files: Detailed Explanation
In Python, a file is a collection of data stored in a specific format, either on the local disk or in memory, that can be accessed or modified by a program. Python provides built-in functions and modules to work with files, allowing you to read, write, and manipulate files efficiently.
Python's file handling functions are built into the standard library, and the most commonly used one is the open()
function.
Types of Files in Python
There are two major types of files based on their operations and data storage:
-
Text Files:
- A text file contains human-readable characters (letters, numbers, symbols).
- The contents of text files are encoded in a specific encoding (like UTF-8 or ASCII).
- Common text file extensions:
.txt
,.csv
,.log
.
-
Binary Files:
- A binary file contains non-human-readable data, such as images, videos, executables, etc.
- The data is stored in the form of 0s and 1s (binary format).
- Common binary file extensions:
.jpg
,.png
,.exe
,.mp3
.
File Modes in Python
When working with files, Python uses different modes to define the type of operation that can be performed on the file. These modes are passed as the second argument to the open()
function.
Common File Modes:
'r'
: Read (default mode) – Opens the file for reading.'w'
: Write – Opens the file for writing (creates a new file if it doesn't exist, or truncates the file if it does).'a'
: Append – Opens the file for writing (creates a new file if it doesn't exist, or appends to the file if it does).'b'
: Binary – Used along with other modes (e.g.,'rb'
or'wb'
) to handle binary files.'x'
: Exclusive creation – Creates a new file, but raises an error if the file already exists.'t'
: Text – Default mode (used for text files).'r+'
: Read and Write – Opens the file for both reading and writing.'w+'
: Write and Read – Opens the file for both reading and writing (truncates the file if it exists).'a+'
: Append and Read – Opens the file for both appending and reading.
Opening and Closing Files
The open()
function is used to open a file, and the close()
method is used to close a file once operations are complete.
# Opening a file
file = open("example.txt", "r")
# Perform file operations (e.g., reading or writing)
# Closing the file
file.close()
Important: Always close the file after performing operations to release system resources.
It’s also recommended to use the with
statement, which automatically closes the file once operations are completed:
with open("example.txt", "r") as file:
# Perform file operations (reading or writing)
content = file.read()
print(content)
# File is automatically closed when the block is exited
File Operations in Python
Python provides several operations that can be performed on files, such as reading, writing, and modifying file content.
1. Reading from Files
There are several methods for reading data from files:
-
read()
: Reads the entire content of the file.with open("example.txt", "r") as file: content = file.read() print(content)
-
readline()
: Reads one line from the file at a time.with open("example.txt", "r") as file: line = file.readline() print(line)
-
readlines()
: Reads all lines from the file and returns them as a list of strings.with open("example.txt", "r") as file: lines = file.readlines() print(lines)
2. Writing to Files
You can write data to a file using the write()
or writelines()
methods:
-
write()
: Writes a string to the file.with open("example.txt", "w") as file: file.write("Hello, this is a test.")
-
writelines()
: Writes a list of strings to the file.lines = ["Hello, World!\n", "Welcome to Python.\n"] with open("example.txt", "w") as file: file.writelines(lines)
3. Appending to Files
You can append data to a file using the append()
mode ('a'
):
with open("example.txt", "a") as file:
file.write("Appending new content to the file.")
4. File Positioning (Seek and Tell)
-
seek(offset, whence)
: Moves the file pointer to a specific position.offset
: Number of bytes to move.whence
: Optional argument (default is0
):0
: Start of the file.1
: Current file position.2
: End of the file.
with open("example.txt", "r") as file: file.seek(5) # Move to the 5th byte content = file.read(10) # Read 10 bytes from that position print(content)
-
tell()
: Returns the current position of the file pointer.with open("example.txt", "r") as file: file.seek(5) position = file.tell() # Get the current position print(f"Current position: {position}")
5. File Removal (Deleting Files)
To remove a file, you can use the os.remove()
method from the os
module.
import os
# Deleting a file
os.remove("example.txt")
Example: File Operations in Action
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a test file.\n")
# Reading from the file
with open("example.txt", "r") as file:
content = file.read()
print("File content:\n", content)
# Appending to the file
with open("example.txt", "a") as file:
file.write("Appending more content.\n")
# Reading after appending
with open("example.txt", "r") as file:
content = file.read()
print("\nFile content after appending:\n", content)
File Handling Best Practices
- Always close files: Use
file.close()
or awith
statement to ensure the file is automatically closed after use. - Use
'with'
for better resource management: Thewith
statement automatically handles closing the file, even if an exception occurs. - Handle file exceptions: Use
try-except
to catch exceptions (e.g., file not found).
try:
with open("example.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
Conclusion
Python provides robust file handling capabilities for interacting with both text and binary files. Key operations such as reading, writing, appending, and moving the file pointer are all straightforward and can be easily managed using the built-in open()
, read()
, write()
, and seek()
functions. Using the with
statement simplifies file handling, ensuring that files are properly closed after use.
If you have further questions or need clarification on any of the concepts, feel free to ask!
Comments
Post a Comment