# Description: This program is a function which calculates pi #per Leibniz formula,based on the number of values passed to it.
# Programmer: xxxxx
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))
How many terms: 12
3.058402765927333
HW
In Puthon
Modify the program above so that it includes exception handling, is “debugged”, and allows the user to execute the program multiple times without exiting it. Be sure to correct any issues found if there is any.
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)? ")
Get Answers For Free
Most questions answered within 1 hours.