Q1. Write a python program to show how to raise an exception in python.
try:
roll = int(input("Please enter your roll number"))
if roll <= 0:
raise ValueError("The number entered is not positive")
print(num)
except ValueError as v:
print("ValueError Exception thrown")
print(v)
except:
print("Roll Number Is Valid")
print("\n\nOutside of try-except clauses.")Please enter your roll number-5
ValueError Exception thrown
The number entered is not positive
Outside of try-except clauses.
Q2. Write a python program to display ‘n’ terms of Fibonacci series using recursion
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = int(input("Please enter your number"))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))Please enter your number7
Fibonacci sequence:
0
1
1
2
3
5
8
Q2. Write a python program to reverse each word of sentence of a file and also count total lines.
num_lines=0
with open("test.txt", "r") as f:
for line in f:
num_lines += 1
with open("test.txt", "r") as f:
data = f.read()
for line in f:
num_lines += 1
new_data = ""
for word in data.split():
rev_word = word[::-1]
new_data += rev_word
new_data += " "
#Writing the new data in text file
with open("output.txt","w") as f:
f.write(new_data)
print("Number of lines:")
print(num_lines)Number of lines:
5
0 Comments:
Post a Comment