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)
mark2 = [55,88,78,90,79]
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.
num = int(input("Enter a number: "))
factorial = 1
# 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 = factorial*i
print("The factorial of",num,"is",factorial)Enter a number: 6
The factorial of 6 is 720
b. Reverse the given number.num = int(input("Enter a number: "))
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
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: ")
fileName = str(input())
fp = open(fileName, "r")
for content in fp:
newContent = content.title()
totContent = totContent + newContent
print("\n",totContent)
fp.close()
fp = open(fileName, "w")
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