【发布时间】:2013-11-07 14:03:50
【问题描述】:
我目前正在编写的一段代码遇到了一些问题。
使用以下代码,我得到 NameError: global name 'doc' is not defined。
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
def createTitle():
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=doc) #</head>
我知道这是因为文档仅在 createHtml 函数中定义。但是,如果我想让同一个文档在不同的函数中调用时工作,我该如何让它工作呢?我不能将它排除在 createHtml 函数之外,因为它会弄乱我的程序,因为我有一个允许用户从不同功能中进行选择的菜单。 像这样:
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
createHtml()
elif menu == "2":
createTitle()
elif menu == "3":
createBody()
else:
print ("Good bye!")
break
doc.close()
并且文档由name变量定义在:
name = input("\nEnter the name for your HTML-page: ")
有没有办法从 createHtml-function 获取 doc 到我的其他函数?
【问题讨论】:
-
在
while循环之前创建doc。将其传递给每个函数。
标签: python function python-3.x defined