我有一個關於變量的小問題。我的主要語言是Java語言(我學習Python)的話,我有一個函數調用變量的問題,它不會刷新其新的價值:函數中的Python變量?
# Values
global e1x, e1y, e1c, e2x, e2y, e2c, altx, alty, x, y
def getValues():
print("Taking Ax + By = C:")
e1x = float(input("Value of x in first equation: "))
#...
if(confirm()): # A function I ommited 'cause its irrelevant
return e1x, e1y, e1c, e2x, e2y, e2c
else:
getValues()
def calculateValues():
# Stuff with variables
# MAIN
getValues()
calculateValues()
我試圖把它寫不全球,試圖用自我字,但它不起作用。 (使用Python 3)
錯誤:
Traceback (most recent call last):
File "E002_GaussSeidel.py", line 41, in <module>
calculateValues()
File "E002_GaussSeidel.py", line 34, in calculateValues
print(str(e1x))
NameError: name 'e1x' is not defined
刻錄*全局e1x,e1y,e1c,e2x,e2y,e2c,altx,alty,x,y *。你並不是真的想要使用全局變量。你也可以在類方法中使用'self',其中self表示方法將被調用的實例。如果你想使用這個邏輯,那麼實際上不僅僅是函數創建一個類。 –
「不起作用」不是問題描述。你有錯誤嗎?如果是這樣,完整的追溯是什麼?它表現出意外嗎?如果是這樣,請描述預期的和實際的行爲。 –
當我嘗試在'calculateValues()'上使用它時,Python說「e1x沒有定義」,但是我在頂部聲明並初始化了實際返回這些值的函數@SvenMarnach –