0% found this document useful (0 votes)
5 views5 pages

Python File Handling and Functions Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Python File Handling and Functions Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

. Which methods are used to read from a file?

Explain any two with


examples.
○ The following methods can be used to read from a file:

read(): Reads the entire content of the file.


with open('[Link]', 'r') as file:
content = [Link]()

readline(): Reads a single line from the file.


with open('[Link]', 'r') as file:
line = [Link]() # Reads the first line
3
readlines(): Reads all the lines and returns them as a list.
with open('[Link]', 'r') as file:
lines = [Link]() # Reads all lines into a list

. What are the usages of the dictionary methods copy(), gets(),


items(), and keys()?
copy(): Creates a shallow copy of the dictionary.
dict1 = {'a': 1, 'b': 2}
dict2 = [Link]()

get(key, default): Returns the value for key if it exists in the dictionary; otherwise,
returns default.
value = [Link]('c', 'Not Found') # Returns 'Not Found'

items(): Returns a view object that displays a list of a dictionary's key-value tuple
pairs.
2
items = [Link]() # Returns a view of (key, value) pairs

keys(): Returns a view object that displays a list of all the keys in the dictionary.
keys = [Link]() # Returns the keys of the dictionary

. Explain union and intersection with examples.


Union: Combines elements from two sets and removes duplicates.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = [Link](set2) # {1, 2, 3, 4, 5}

Intersection: Returns elements that are common to both sets.


intersection_set = [Link](set2) # {3}
1
. Explain the following statements:
i) if: Used to execute a block of code if a condition is true.
4
if condition:
# Code to execute

ii) if-else: Executes one block of code if the condition is true and another if false.

if condition:
# Code if true
else:
# Code if false

iii) break: Terminates the nearest enclosing loop.

for i in range(5):
if i == 2:
break # Exits the loop when i is 2
iv) continue: Skips the current iteration and moves to the next iteration of the
loop.

for i in range(5):
if i == 2:
continue # Skips the iteration when i is 2

. List features of Python.


○ Easy to Learn: Python has a simple and easy-to-read syntax.
○ Interpreted Language: Python code is executed line by line, making

debugging easier.
○ Dynamic Typing: No need to declare the data type of a variable

explicitly.
○ Extensive Libraries: Python has a wide range of libraries and

frameworks for various applications.


○ Community Support: Python has a large community that contributes

to its growth and improvement.

Write a Python program to calculate X^Y.

def power(x, y):


return x ** y

result = power(2, 3)
print(f"2 raised to 3 is {result}") # Output: 8

Write a Python program to accept a number and check whether it is a perfect


number or not.
def is_perfect(n):
divisors_sum = sum(i for i in range(1, n) if n % i == 0)
return divisors_sum == n

number = 6
if is_perfect(number):
print(f"{number} is a perfect number.") # Output: 6 is a perfect number.
else:
print(f"{number} is not a perfect number.")

What is the use of seek() and tell() functions?


● seek(offset, whence): Changes the file position to a specified byte.
● tell(): Returns the current position of the file cursor.

Demonstrate list slicing.


my_list = [10, 20, 30, 40, 50]
slice1 = my_list[1:4] # Gets elements from index 1 to 3
slice2 = my_list[:3] # Gets elements from the start to index 2
print(slice1) # Output: [20, 30, 40]
print(slice2) # Output: [10, 20, 30]

A tuple is an ordered collection of items. Comment.


● Yes, tuples are ordered collections of items that are immutable. The order
of elements is maintained, and they cannot be changed after creation.

What is a package? Explain with an example how to create a package.


● A package is a way of organizing related Python modules in a directory
hierarchy. A package must contain an __init__.py file to be recognized as
a package.
example:
mypackage/
__init__.py
[Link]
[Link]
What are the usages of tuple methods zip(), tuple(), count(), and index()
functions?
zip(): Combines two or more iterables (like lists or tuples) into a tuple of tuples.
tuple(): Converts an iterable (like a list) into a tuple.
count(): Returns the number of times a specified value appears in the tuple.
index(): Returns the first index of a specified value. Raises ValueError if the
value is not found.

What is an anonymous function? How to create it? Explain with an example.


● An anonymous function is a function defined without a name using the
lambda keyword. It can have any number of arguments but can only have
one expression.

multiply = lambda x, y: x * y
print(multiply(3, 4)) # Output: 12

Explain the following loops with examples:\


i) While Loop: Repeats a block of code as long as the condition is true.
count = 0
while count < 5:
print(count)
count += 1
# Output: 0, 1, 2, 3, 4

ii) For Loop: Iterates over a sequence (like a list or string).


for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4

How to perform input-output operations? Explain with an example.


● Input and output operations in Python can be performed using input() for
input and print() for output.

name = input("Enter your name: ") # Taking input from user


print(f"Hello, {name}!") # Outputting a greeting

You might also like