Q1. Write a python program to show how to raise an exception in python.
try:
= int(input("Please enter your roll number"))
roll 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))
= int(input("Please enter your number"))
nterms # 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.
=0
num_lineswith open("test.txt", "r") as f:
for line in f:
+= 1
num_lines with open("test.txt", "r") as f:
= f.read()
data for line in f:
+= 1
num_lines = ""
new_data for word in data.split():
= word[::-1]
rev_word += rev_word
new_data += " "
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