Python3:有没有办法让我的函数在用户选择不输入参数的情况下只打印两位小数的 pi?

Python3: Is there a way to make it so my function prints pi with only two decimals if the user chooses to input no argument?

有没有办法让我的函数在用户选择不输入参数的情况下只打印两位小数的圆周率?下面的函数接受一个参数(即 'n'),如果用户选择将该字段留空,则该参数 returns 会引发错误:

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

期望的结果应该如下:

>>> pi()
3.14

我想知道是否有办法以某种方式使该功能短路,以便该功能不一定需要输入。如果没有,我不介意更智能地重写代码。非常感谢提前提供的所有帮助!

只需将 default argument 添加到您的函数中,以便在未提供任何内容时将 n 变量设置为 2。

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

或者简单地说:

def pi(n: int = 2):
    return round(math.pi, n)

这会产生:

>> result = pi()
>> print(result)
3.14