我相信我的功能有些不正確,但我仍然對Python和一般功能非常陌生,而且我錯過了我的問題。在下面的代碼中,我沒有向該函數發送任何值,但是一旦函數讀取數據庫,我希望它將數據庫中的值返回到主程序中。我在函數內部放置了一個print語句,以確保它從數據庫中提取值並且一切正常。我在主區域的函數調用之後複製並粘貼了相同的打印行,但我得到了NameError: 'wins' is not defined
。這導致我相信我沒有正確返回值?Python3函數返回值
#Python3
import pymysql
def read_db():
db = pymysql.connect(host='**********',user='**********',password='**********',db='**********')
cursor = db.cursor()
sql = "SELECT * FROM loot WHERE id = 1"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
wins = row[2]
skips = row[3]
lumber1 = row[4]
ore1 = row[5]
mercury1 = row[6]
db.commit()
db.close()
print ("Wins = ",wins," Skips = ",skips," Lumber = ",lumber1," Ore = ",ore1," Mercury = ",mercury1)
return (wins, skips, lumber1, ore1, mercury1)
read_db()
print ("Wins = ",wins," Skips = ",skips," Lumber = ",lumber1," Ore = ",ore1," Mercury = ",mercury1)
在函數(或類)中聲明的變量不存在於函數(或類)之外。這樣你就可以對不同的變量在不同的上下文中使用不同的變量,並且它們不會互相干擾。您也不需要關心您調用的函數中使用的變量名稱。這被稱爲「詞法作用域」,它非常有用,所有現代語言都使用它(儘管發明花了很長時間)。但是,這意味着,正如其他人指出的那樣,如果您想稍後使用它們,則需要爲函數的返回值分配名稱。 –