Python Unit-4
Python Unit-4
# output :
['this is a sample']
Advantage :
It is Suitable for reading multiple lines and storing them as a list. It is often used
when you need to manipulate or iterate through all lines of a file.
Example:
with open('my_file.txt', 'r') as file:
content = file.readlines() # Reads a single line from the file.
print(content)
# output : this is sampe
with statement :
The code within the with block executes, and upon exiting the block,
whether due to normal completion or an exception, the file is automatically
closed. This is advantageous as it eliminates the need for explicitly calling the
close() method, reducing the chances of forgetting to close the file and
ensuring proper resource management.
Example:
file.write(“hello\n”)
file.write(“hello2”)
write() method :
write() method in Python is used to write content to a file that has been opened in
a write ('w') or append ('a') mode. It's part of the file object's functionalities and
allows you to add text or data to the file.
Syntax :
file.write(str)
file: File object obtained by opening a file using the open() function.
str: The string or data you want to write to the file.
example -1:
with open('my_file.txt', 'w') as file:
file.write("Hello, this is a text!\n") # Writing a string to the file
file.write("This is text2 .") # Writing another string to the file
example-2 :
file= open('my_file.txt', 'w')
file.write("Hello, this is a text!\n") # Writing a string to the file
file.write("This is text2 .\n")
file.close()
=>The write() method appends the specified string to the end of the file.
=>It doesn’t automatically add newline characters (\n), so if you want to start
a new line, you need to explicitly include \n in the string.
=>If the file doesn't exist, it will be created. If it exists, opening a file in write
mode ('w') will truncate the file, meaning it will erase all existing content
before writing.
Considerations :
=>Ensure that the file is opened in the appropriate mode ('w' for writing or
'a' for appending) before using the write() method.
# code
Q. There is file named input.txt .Enter some positive numbers into the file
named Input.txt . Read the contents of the file and if it is an odd number
write it to odd.txt and if the numbers is even, write it to even.text.
# Open input.txt in write mode to enter numbers
input_file = open("input.txt", "w") # it will creare automatically input.txt
input_file.write("2\n5\n8\n11\n4\n7\n") # if does not exist
input_file.close()
# Open input.txt in read mode to read its contents
input_file = open("input.txt", "r")
odd_file = open("odd.txt", "w")
even_file = open("even.txt", "w")
for i in input_file:
# Convert the line to an integer
number = int(i.strip())
if number % 2 == 0:
even_file.write(f"{number}\n")
else:
odd_file.write(f"{number}\n")
# Close files after processing
input_file.close()
odd_file.close()
even_file.close()
print("Operation completed successfully.")
Q.13 write Python program to write the numbers of letters and digits in
given input string into a File object.
def count_letters_digits(input_str):
letter_count = 0
digit_count = 0
for char in input_str:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
return letter_count, digit_count
user_input = input("Enter a string: ")
r = count_letters_digits(user_input)
output_file = open("output.txt", "w")
output_file.write(f"Letter Count: {r[0]}\n")
output_file.write(f"Digit Count: {r[1]}\n")
output_file.close()
print(f"Counts have written to output.txt. successfully")
Q.14 Write a python code to create file with p.txt name and write your name
and father’s name in this file and then read this file to print it.
file = open("p.txt", "w")
file.write("Your Name: [ajay]\n")
file.write("Father's Name: [vijay]\n")
file.close()
file = open("p.txt", "r")
contents = file.read()
print(contents)
file.close()
#output
Your Name: [ajay]
Father's Name: [vijay]
Q.15 w.a.p to insert data into file and also use seek() function in python ?
file = open("abc.txt", "w")
file.write("ajay")
file.write("vijay")
file.write("kamal")
file.close()
file = open("abc.txt", "r")
content_before_seek = file.read()
print("Contents before seek:")
print(content_before_seek)
file.seek(1)
# Read and print the contents again
content_after_seek = file.read()
print("\nContents after seek:")
print(content_after_seek)
file.close()
#output
contents before seek:
ajayvijaykamal
Contents after seek:
Jayvijaykamal
Q. W.A.P to change a given string to a new string where the first and last
character have been exchanged. ?
def change_first_last(str1):
if len(str1) < 2:
return str1
else:
first_char = str1[0]
last_char = str1[-1]
middle_chars = str1[1:-1] #it will get 1 to -2 characters
new_string = last_char + middle_chars + first_char
return new_string
input_string = "examplp"
new_string = change_first_last(input_string)
print("Original string:", input_string)
print( new_string) #pxample
Q. Write a Python function that generates the Fibonacci sequence up to a given limit and
returns the list of Fibonacci numbers. ?
def fibo(num):
a=0
b=1
L=[]
if num<=0:
print("enter a +ve number ")
elif num==1:
L.append(a)
return L
else:
L.append(a)
for i in range(2,num+1):
L.append(b)
c=a+b
a=b
b=c
return L
r=fibo(8)
Q. Write a Python program that prints all prime numbers within given range ‘n ‘ ?
Method-1
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def print_prime_elements(start, end):
for num in range(start, end + 1):
if is_prime(num):
print(num)
start_range = 1
end_range = 100
print_prime_elements(start_range, end_range)
Q. Write a Python program to convert 12-hour time to 24-hour time format in python .?
def convert24_system(str1):
if str1[-2:11]=="AM" and str1[0:2]=="12":
return "00"+str1[2:8]
elif str1[-2:11]=="AM":
return str1[0:8]
elif str1[-2:11]=="PM" and str1[0:2]=="12":
return str1[0:8]
else:
return str(int(str1[0:2])+12)+str1[2:8]
print(convert24_system("12:05:45 PM")) #12:05:45
print(convert24_system("01:05:45 PM")) #13:05:45
print(convert24_system("12:05:45 AM")) #00:05:45
Q. Write a Python program to check whether a given number is a Fibonacci number or
not. ?
def perfect_sq(n):
sq_root=int(n**0.5)
if sq_root*sq_root==n:
return True
else:
return False
def isfibo(n):
num1=perfect_sq(5*n*n+4)
num2=perfect_sq(5*n*n-4)
if num1 or num2:
return True
else:
return False
num=13
if isfibo(num):
print("it is fibonacci number for value ",num)
else:
print("it is not fibonacci number for value ",num)
Q.1 Write a function less_than(List1,k) to return list of numbers less than k from
a List1 . the function must use list comprehension. Given List1=[1,-2,0,5,-3] , k=0
. return [-2,-3]
def less_than(List1, k):
result_list = []
for i in List1:
if i < k:
result_list.append(i)
return result_list
List1 = [1, -2, 0, 5, -3]
K=0
result = less_than(List1, 0)
print(result)
Q.2 write a python program to add an item in a tuple.?
method-1
original_tuple = (1, 2, 3, 4)
new_item = 5
result_tuple = original_tuple + (new_item,)
print("Original Tuple:", original_tuple)
print("Tuple after adding", new_item, ":", result_tuple)
method-2
original_tuple = (1, 2, 3, 4)
new_item = 5
tuple_list = list(original_tuple)
tuple_list.append(new_item)
result_tuple = tuple(tuple_list)
print("Original Tuple:", original_tuple)
print("Tuple after adding", new_item, " :", result_tuple)
Q.3 write a python function removekth(s,k) that takes as input a string and an
integer k>=0 and removes the character at index k. if k is beyond the length of s ,
the whole of s is returned. ?
def removekth(s, k):
if k < 0 or k >= len(s):
return s
result = ""
for i in range(0,len(s)):
if i != k:
result += s[i]
return result
print(removekth("python", 0)) # ython
print(removekth("python", 1)) # pthon
print(removekth("python", 2)) # pyhon
Q. write a program factors (N) that returns a list of all positive divisors of N (N>=0)
?
def factors(N):
if N < 0:
return "Input should be a non-negative integer."
divisor_list = []
for i in range(1, N + 1):
if N % i == 0:
divisor_list.append(i)
return divisor_list
number = 12
result = factors(number)
print(result)
Q. write a function makePairs that takes as input two lists of equal length and
returns a single list of same length where kth element is the pair of kth elements
from the input lists. For example,
makePairs([1,3,5,7],[2,4,6,8]) ,return [(1,2),(3,4),(5,6),(7,8)] , makePairs([],[])
return []
def makePairs(list1, list2):
if len(list1) != len(list2):
return "Input equal lengths list"
pairs_list = []
for i in range(0,len(list1)):
pairs_list.append((list1[i], list2[i]))
return pairs_list
result1 = makePairs([1, 3, 5, 7], [2, 4, 6, 8])
print(result1)
result2 = makePairs([], [])
print(result2)
#output
[(1, 2), (3, 4), (5, 6), (7, 8)]
[]
Q. write a python program , countSquares(n), that returns the count of perfect
squares less than or equal to n (n>1) .
def countSquares(n):
if n <= 1:
return 0
count = 0
for i in range(1, n + 1):
sq=i*i
if sq <= n:
count += 1
return count
n = 55
result = countSquares(n)
print(result)#7
Q. write a python function , alternating(list1) , that takes as argument a sequence
list. The function returns True if the elements in list1 are alternately odd and even
, starting with an even number, otherwise it returns False.
def alternating(list1):
if len(list1) < 1:
return False
if list1[0] % 2 != 0:
return False
for i in range(1, len(list1)):
if list1[i] % 2 == list1[i-1] % 2:
return False
return True
list1 = [10, 9, 9, 6]
result1 = alternating(list1)
print(f" {result1}") #False
list2 = [10, 15, 8, 7, 90, 11]
result2 = alternating(list2)
print(f"{result2}") # True, bcoz 1st even then odd number are alternatevaly
Q.Write a python function , searchMany(s,x,k), that takes as argument a
sequence s and integers x,k (k>0). The function returns True if there are at most
k orrurrences of x in s. otherwise it returns False.
def searchMany(s, x, k):
count = 0
for i in range(0,len(s)):
if s[i] == x:
count += 1
if count > k:
return False
return True
list1 = [1, 2, 3, 4, 2, 2, 5, 2, 6]
result = searchMany(list1,2,3)
print(f"{result}") #False 2 are repeating more than 3
Q.9 Write a program to print “hello World” using Tkinter.?
import tkinter as tk
# Create the main window
window = tk.Tk()
# Create a label widget and add it to the window
label = tk.Label(window, text="Hello World")
# Pack the label into the window
label.pack()
# Run the Tkinter event loop
window.mainloop()