我试图在if语句中调用函数,但它不起作用。这是我第一次尝试使用Python。我做错什么了?
#!/usr/bin/python
menu = raw_input ("Hello, please choose form following options (1,2,3) and press enter:\n"
"Option 1\n"
"Option 2\n"
"Option 3\n")
if menu == str("1"):
savinginfile = raw_input ("Please, state your name: ")
option1()
elif menu == str("2"):
print ("Option 2")
elif menu == str("3"):
print ("Option 3")
def option1():
test = open ("test.txt", "rw")
test.write(savinginfile)
print ("Option 1 used")
test.close()
建议将
savinginfile
作为参数传递:在调用之前,需要定义
option1
。Python从上到下解释。在调用函数之前,需要先定义函数。把
def option1(): #and all that code below it
放在if语句的上方。抛出太多全局变量也是一种不好的做法。您不应该像现在这样使用
savinginfile
——而是将它作为参数传递给函数,让函数在自己的作用域中运行。在使用savinginfile
之前,需要将要使用的文件名传递给函数。请改为:相关问题 更多 >
编程相关推荐