尝试跨函数传递变量时的NameError

时间:2014-07-29 03:55:35

标签: python

我正在尝试编写一个可以响应用户输入的脚本,但是当它不知道如何响应时给我发电子邮件。

import time
import smtplib
import random

from email.mime.text import MIMEText

def void():
    print("You find your self hanging in the void.")
    response = input("What do you want to do?")
    if response == "dance":
        dance()
    else:
        bug()
def dance():
    print("You dance your heart out like nobody is watching")
    void()

#if the thing breaks
def bug():
    print(response + " will be in the next release!")

    FROM ='simulation@gendale.net'

    TO = ["sweeney@roerick.me"]

    SUBJECT = "new command request"

    TEXT = response

    message = """\
From: %s
To: %s
Subject: %s

%s

""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

    server = smtplib.SMTP('mail.gendale.net')
    server.login('simulation@gendale.net', 'XXXXXXXXX')
    server.sendmail(FROM, TO, message)
    server.quit
    sys.exit()
def credits():
    print("Welcome to the Everything Simulator.")
    time.sleep(3)
    print("Brought to you by Gendale Entertainment")
    time.sleep(3)
    print("Written and coded by Roerick Sweeney")
    time.sleep(2)
    print()
    time.sleep(2)
    print()
    time.sleep(2)
    void()
credits()

当我运行这个脚本时,我收到错误:“NameError:name'response'未定义”据我所知,我的'response'变量以某种方式迷路了。当我自己调用字符串时,smtp脚本工作正常,但我想将void()中的'response'传递给bug()。我正在使用python3。

2 个答案:

答案 0 :(得分:2)

由于变量scoped in python的方式,为了在responsebug()函数中定义dance(),您需要从void()传递它}。

例如:

def void():
    print("You find your self hanging in the void.")
    response = input("What do you want to do?")
    if response == "dance":
        dance(response)
    else:
        bug(response)

def dance(response):
    print("You dance your heart out like nobody is watching")
    void()

def bug(response):
    print(response + " will be in the next release!")

    FROM ='simulation@gendale.net'

    TO = ["sweeney@roerick.me"]

    SUBJECT = "new command request"

    TEXT = response

    message = ""

答案 1 :(得分:0)

您正在尝试引用在函数(Void())中定义的变量(响应)。

你需要创建一个全局变量来在不同的函数中引用它。

def void():
    global response
    response = raw_input('What do u want:\n')

    if response == 'dance':
        Dance()
    else:
        Bug()

def Dance(response):
    print("You dance your heart out like nobody is watching")
    void()

def Bug():
    global response
    print ">>> Response is :", response
    FROM ='simulation@gendale.net'

    TO = ["sweeney@roerick.me"]

    SUBJECT = "new command request"

    TEXT = response

    message = ""


if __name__ == '__main__':
    void()