[英]How do I send a variable back to the main program from a function?
我的代码有问题
我希望我的代码将用户命令创建的文件名返回到主程序,但我不知道如何,我尝试过返回文件名,但这没有用,这是代码:
#File Creator
def Create(filename):
UserFile = open(str(filename), "wt")
file = (str(filename))
return file
#Main program
Create(input("filename: "))
print(file)
我正在使用python 3.3,如何将文件设置为可以在代码中的任何位置使用的变量?
我在考虑添加file = Create(input("filename: "))
但是我不确定是否还有其他方法
为什么返回文件不起作用? 尽管您在代码中有几个错误。 试试这个,它应该可以解决问题:
# File Creator
def create(filename):
userFile = open(filename, "rw")
return userFile # this is a file object
# Main program
theFile = create(input("filename: "))
print(str(theFile)) # string representation of the file object
绝对不要在没有真正需要的情况下使用全局变量 -全局变量是一种非常糟糕的编程习惯。 在这种简单的情况下,只需在结构良好的程序中将值作为参数和/或返回值传递即可,足以满足您的需求。
您可以使用global
:
def Create(filename):
global file
UserFile = open(str(filename), "wt")
file = (str(filename))
#return file -- I commented this since there is no real reason to return now with a global
file
现在将在全局范围内。
虽然我个人认为您的file = Create(input("filename: "))
是最好的。 像这样使用全局变量被很多人所反对,并且经常可以避免。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.