嵌套函数 python 中的名称错误

Name error in python with nested function

我在 python 解释器 运行 嵌套函数中遇到错误

import MySQLdb
import serial
import time
import smtplib


ser=serial.Serial('/dev/ttyACM1',9600)
db=MySQLdb.connect("localhost","root","pass","db")

cursor=db.cursor()

while 1:
  print("Waiting ;;...")
  print("")
  print("collecting")
  print("")

  time.sleep(3)

  x=ser.readline()
  time.sleep(3)
  if x>700:
     send()
     print"send mail"

  print("inserting into Database")
  sql="INSERT INTO vidit2(temp)  VALUES(%s);" %(x)
  cursor.execute(sql)
  db.commit()
  time.sleep(3)



def send():

 content="send"

 mail=smtplib.SMTP("smtp.gmail.com",587)

 mail.ehlo()

 mail.starttls()

 mail.login("emailid","pass")

 mail.sendmail("sender","reciever",content)

 mail.close()

错误: python temp.py 正在等待 ;;...

收集

回溯(最近调用最后): 文件 "temp.py",第 24 行,位于 发送() NameError:名称 'send' 未定义

请帮忙。 提前致谢

不像 JavaScript 那样 "hoist" function definitions during compilation so that they can be called before they are defined in your code (just learned about this the other day so forgive me if this is an oversimplification), in Python you need to define functions before you call them (interesting discussion here)。这意味着你需要做:

def send():
...

之前:

send()