Python 函数参数:未定义ab

Python 函数参数:未定义ab,python,Python,当我运行这段代码时,它说ab没有定义。有什么问题 import math def taylor(ab): ab = float(input("What is the parameter precision? :")) print(f"Calling taylor: {(ab)}") num = 0 x = 1 n = 0 y = 1 while abs(math.pi - num) > ab: num = num +

当我运行这段代码时,它说ab没有定义。有什么问题

import math
def taylor(ab):
    ab = float(input("What is the parameter precision? :"))
    print(f"Calling taylor: {(ab)}")
    num = 0
    x = 1
    n = 0
    y = 1
    while abs(math.pi - num) > ab:
        num = num + (4 * (x / y))
        x = x * -1
        y += 2
        n = n + 1
    print(f"Calling basel : {(ab)} returns {(num), (n)}")
taylor(ab)

您试图在定义变量ab之前使用它。不能将未定义的变量传递给函数。泰勒函数不需要声明任何参数。删除此参数可以解决您的问题:

import math

def taylor():
    ab = float(input("What is the parameter precision? :"))
    print(f"Calling taylor: {(ab)}")
    num = 0
    x = 1
    n = 0
    y = 1
    while abs(math.pi - num) > ab:
        num = num + (4 * (x / y))
        x = x * -1
        y += 2
        n = n + 1
    print(f"Calling basel : {(ab)} returns {(num), (n)}")

taylor()
或:


定义如下函数:def taylor:,并将其称为taylor
import math
def taylor():
    ab = float(input("What is the parameter precision? :"))
    print(f"Calling taylor: {(ab)}")
    num = 0
    x = 1
    n = 0
    y = 1
    while abs(math.pi - num) > ab:
        num = num + (4 * (x / y))
        x = x * -1
        y += 2
        n = n + 1
    print(f"Calling basel : {(ab)} returns {(num), (n)}")
taylor()
import math
def taylor(ab):

    print(f"Calling taylor: {(ab)}")
    num = 0
    x = 1
    n = 0
    y = 1
    while abs(math.pi - num) > ab:
        num = num + (4 * (x / y))
        x = x * -1
        y += 2
        n = n + 1
    print(f"Calling basel : {(ab)} returns {(num), (n)}")
ab = float(input("What is the parameter precision? :"))
taylor(ab)