Python 定义和接收值时出错
你好,这是我的代码:Python 定义和接收值时出错,python,Python,你好,这是我的代码: def main(): #Define Variables HomesSold = [0] Amount = 0 HomePrice = [0] Amount = GetAmount(Amount) HomesSold = AmountHomesSold(Amount) #print(HomesSold) def GetAmount (Amount): global amount ConvertAm
def main():
#Define Variables
HomesSold = [0]
Amount = 0
HomePrice = [0]
Amount = GetAmount(Amount)
HomesSold = AmountHomesSold(Amount)
#print(HomesSold)
def GetAmount (Amount):
global amount
ConvertAmount = float()
ErrorFlag = False
Amount = input("Enter the amount of homes sold this year:")
while not Amount.isdigit():
Amount = input("Please try again, make sure you are entering a positive number (No commas needed): ")
print("The amount of houses sold were: ",Amount)
ConvertAmount = float(Amount)
return ConvertAmount
def AmountHomesSold(HomePrice):
HomePrice = 0
index = 0
while (index < Amount):
HomePrice = GetHomePrice()
HomesSold[index] = HomePrice
index = index + 1
print(HomePrice)
return HomePrice
def GetHomePrice():
HomePrice = input("How much did the homes sell for?")
while not HomePrice.isdigit():
HomePrice = input("Please try again, make sure you are entering a positive number (No commas needed): ")
return HomePrice
main()
所以,当我试图为index
def AmountHomesSold():
global Amount
HomePrice = 0
index = 0
while (index < Amount):
HomePrice = GetHomePrice()
HomesSold[index] = HomePrice
index = index + 1
print(HomePrice)
return HomePrice
有关更多信息,请参阅。范围。。。您需要将其作为变量传递给函数。或者创建一个类并使用一个类变量。或者使用全局变量,这不是最好的选择。该变量未在该函数的作用域中定义。它是在main和GetAmount函数中定义的。我如何接收另一个函数返回到单独的函数,而不在main中重复整个函数。。。homesald=amounthomesoldamount和定义函数的位置。。。def AmountHomeSoldAmount。。。我建议您在尝试自己编写任何程序之前先阅读完整的官方python教程,这是一个很好的编程入门,只需跳过您还不理解的部分,然后再重新阅读。penguin解决了我的问题。现在我有了一个新问题,我必须更好地告诉他不要使用globalvariable@LudovicViaud这是解决问题的正确方法。是的,它是有效的,但应尽可能避免使用全局变量,这是一种不好的做法,尤其是在执行不同函数时发生变化的做法。你不需要全局语句来“读”一个全局语句,只需要写它就行了