[英]Rectangle Area Calculation Function Problem
我嘗試了一個非常簡單的 function 來計算矩形面積,但它不起作用,它甚至沒有得到輸入,任何人都可以看到我的代碼並讓我知道這段代碼中的問題,謝謝?
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)
你的問題是scope; 您正在使用變量a
和b
但是當您在 function 中為它們賦值時,因為您沒有將它們聲明為global
的,賦值不會影響該 function 之外的任何內容。您似乎還聲明a
和b
在某處上方,考慮到您正在執行calculate_area(a,b)
但實際上並未在示例中的 scope 中聲明a
或b
。
您似乎還認為,如果您將a
和b
作為 arguments 傳遞給get_input
,它們將在原始 function 中受到影響。這不是變量在 Python 中的工作方式。如果您傳遞object ,則可以更改該 object 的屬性您將 object 傳遞給 function,但是如果您嘗試更改變量指向的object,那只有在您聲明了global
時才有效。
您所要做的就是從函數的 arguments 中刪除a
和b
,然后從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
如果您改為使用全局變量,您的代碼可能如下所示 - 您不需要返回任何內容,但如果您希望a
和b
的值在 function 之外發生變化,則必須將它們聲明為全局變量:
# 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.