Is there a way to make it so my function prints pi with only two decimal places if the user chooses to input no argument? The below function takes one argument (namely 'n') which in turn returns an error if the user chooses to leave the field blank:
def pi(n):
pi_input = round(math.pi, n)
#None is unfruitful here, I just wanna emphasize my desired objective
if n <= 1 or n == None:
return pi(2)
elif n > 15:
print("Too many decimal places.")
return math.pi
else:
return pi_input
The desired outcome should be as follows:
>>> pi()
3.14
I was wondering if there was a way to somehow short-circuit the function so the function does not necessarily require an input. If not, I wouldn't mind a more intelligent rewriting of the code. I greatly appreciate all help in advance!
CodePudding user response:
Simply add a default argument to your function so that the n
variable is set to 2 if nothing is provided.
def pi(n: int = 2):
pi_input = round(math.pi, n)
if n > 15:
print("Too many decimal places.")
return math.pi
else:
return pi_input
Or simply:
def pi(n: int = 2):
return round(math.pi, n)
Which would produce:
>> result = pi()
>> print(result)
3.14