矩形面积计算函数题

Rectangle Area Calculation Function Problem

我尝试了一个非常简单的函数来计算矩形面积,但它不起作用,它甚至没有得到输入,任何人都可以看到我的代码并让我知道我在这段代码中的问题是什么,拜托,谢谢?

def get_input(a,b):
    a = int(input("Please enter the width: \n"))
    b = int(input("Please enter the length: \n"))

def show_area(c):
    print("The area of the rectangle is: {c}".format(c))
    
def calculate_area(a,b):
    get_input(a,b)
    c=a*b
    show_area(c)    
    
calculate_area(a,b)

你的问题是范围;你正在使用变量 ab 但是当你在一个函数中给它们赋值时,因为你没有声明它们 global,赋值不会影响函数之外的任何东西那个功能。考虑到您正在执行 calculate_area(a,b) 但实际上并未声明 [​​=13=] 或 b,您似乎也在某处声明了 ab在您的示例中的那个范围内。

您似乎还认为,如果将 ab 作为参数传递给 get_input,它们将在原始函数中受到影响。这不是变量在 Python 中的工作方式。如果传递 object,则可以在将对象传递给函数时更改该对象的 properties,但是如果您尝试更改 变量指向哪个对象,只有当你声明一个global.

时才有效

您所要做的就是从函数的参数中删除 ab,取而代之的是,从中删除 return get_input。此外,使用 f-strings 使打印更简单:

def get_input(): # No need to pass in a and b; we're creating them here
    a = int(input("Please enter the width: \n"))
    b = int(input("Please enter the length: \n"))
    return a, b # return a tuple of (a, b)


def show_area(c):
    print(f"The area of the rectangle is: {c}") #f-strings are more straightforward


def calculate_area(): #no need to pass in a and b; they're created in the middle of this function
    a, b = get_input() # you can assign multiple variables at once if the function returns a tuple
    c = a * b
    show_area(c)


calculate_area() # there is no a or b declared in this scope so no need to pass them in

如果您改为使用全局变量,您的代码可能如下所示 - 您不需要 return 任何内容,但您必须将 ab 声明为globals 如果你想让它们的值在函数之外改变:

# a and b must be defined within the module scope in order to use them within functions
a = 0
b = 0


def get_input():
    global a
    global b
    a = int(input("Please enter the width: \n"))
    b = int(input("Please enter the length: \n"))


def show_area(c):
    print(f"The area of the rectangle is: {c}")


def calculate_area():
    get_input()
    c = a * b
    show_area(c)


calculate_area()

最后,您可以使用 class 来存储 a 和 b,这样您就不必将它们声明为全局变量:

class AreaCalculator:
    def __init__(self, a=0, b=0):  # default a and b to zero
        self.a, self.b = a, b

    def get_input(self):
        self.a = int(input("Please enter the width: \n"))
        self.b = int(input("Please enter the length: \n"))

    @staticmethod  # this method is declared as "static" because it doesn't use any "self" variables
    def show_area(c):
        print(f"The area of the rectangle is: {c}")

    def calculate_area(self):
        self.get_input()
        c = self.a * self.b
        self.show_area(c)


ac = AreaCalculator()
ac.calculate_area()