Q1. Write a python program to show use of assert keyword.
In Python we can use assert statement in two ways.
- assert statement has a condition and if the condition is not satisfied the program will stop and give AssertionError.
- assert statement can also have a condition and a optional error message. If the condition is not satisfied assert stops the program and gives AssertionError along with the error message.
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
= [55,88,78,90,79]
mark2 print("Average of mark2:",avg(mark2))
= []
mark1 print("Average of mark1:",avg(mark1))
Average of mark2: 78.0
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11928/3890474036.py in <module>
7
8 mark1 = []
----> 9 print("Average of mark1:",avg(mark1))
~\AppData\Local\Temp/ipykernel_11928/3890474036.py in avg(marks)
1 def avg(marks):
----> 2 assert len(marks) != 0,"List is empty."
3 return sum(marks)/len(marks)
4
5 mark2 = [55,88,78,90,79]
AssertionError: List is empty.
Q2. Write a python program to perform following task.
a. Calculate the factorial of given number.
= int(input("Enter a number: "))
num = 1
factorial # check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
= factorial*i
factorial print("The factorial of",num,"is",factorial)
Enter a number: 6
The factorial of 6 is 720
b. Reverse the given number.
= int(input("Enter a number: "))
num = 0
reversed_num while num != 0:
= num % 10
digit = reversed_num * 10 + digit
reversed_num //= 10
num
print("Reversed Number: " + str(reversed_num))
Enter a number: 78945
Reversed Number: 54987
Q2. Write a python program which takes file name as input and print the lines after making only first character of each word in the sentence capitalized.
= ""
totContent print("Enter the Name of File: ")
= str(input())
fileName = open(fileName, "r")
fp
for content in fp:
= content.title()
newContent = totContent + newContent
totContent print("\n",totContent)
fp.close()= open(fileName, "w")
fp
fp.write(totContent)
print("All Words Capitalized Successfully!")
fp.close()
Enter the Name of File:
test.txt
Rahul Sonawane
November July May March Jun
Tal Nsk Rahul
Dist Nashik
Rahul
All Words Capitalized Successfully!
0 Comments:
Post a Comment