In: Computer Science
Python Assignement
Programm Assignement 1
# Description: This program is a function which calculates pi per Leibniz
formula,based on the number of values passed to it.
def calculate_pi(n):
total, sign = 0, 1
for i in range(n):
term = 1 / (2 * i + 1)
total += term * sign
sign *= -1
total *= 4
return total
n = int(input("How many terms: "))
print(calculate_pi(n))
PRogramm Assignement2
# This program is to modify the program for Homewor
k Assignment 1
so that it includes exception
# handling, is
, and allows the user to execute the program
multiple times
# without exiting it.
def calculate_pi(n):
try:
total, sign = 0, 1
for i in range(n):
term = 1 / (2 * i + 1)
total += term * sign
sign *= -1
total *= 4
return total
except Exception as e:
print("Exception occurred..")
return 0
choice = "yes"
while(choice=="yes"):
n = int(input("How many terms: "))
print(calculate_pi(n))
choice = input("Want to run it again (yes/no)? "
)
PB
Divide the program for Assignment 2 into two modules: 1. A class module which contains a class based on the Leibniz formula, including a constructor for use with the class, and 2. A program module which creates an instance of the class defined in the class module and uses the class attribute to perform the functionality required in Assignement 2. Be sure to correct any issues found with Assignement 2.
#source code:
class Leibniz:
def __init__(self):
self.total=0
def calculate_pi(self,n):
try:
self.total, sign
= 0, 1
for i in
range(n):
term = 1 / (2 * i + 1)
self.total += term * sign
sign *= -1
self.total *= 4
return
self.total
except Exception as e:
print("Exception
occurred..")
return 0
class Main_Calc():
choice = "yes"
while(choice!="no"):
try:
n =
int(input("How many terms: "))
Object_pi=Leibniz()
print(Object_pi.calculate_pi(n))
choice =
input("Want to run it again (yes/no)? ")
except:
print("Enter the
Integer")
if __name__=="__main__":
Call_class=Main_Calc()
#output:
#if you have any doubts comment below.,.