2013-12-11 127 views
2

即时函数试图在if语句里面调用函数,但它不起作用。这是我第一次尝试使用Python。我究竟做错了什么?if语句里面的调用函数

#!/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() 
+2

什么不行?你得到一个错误代码?请详细说明。 – jramirez

回答

2

您需要在尝试调用它之前定义您的函数。只需在您的if语句上方放置def option1(): #and all that code below it即可。

扔掉太多全局变量也是不好的做法。您不应该按照您的方式使用,而应将其作为参数传递给函数,并让函数在其自己的范围内运行。在能够使用之前,您需要传递函数名称来使用该文件。尝试改为:

def option1(whattosaveinfile): 
    test = open("test.txt","a+") #probably better to use a with statement -- I'll comment below. 
    test.write(whattosaveinfile) #note that you use the parameter name, not the var you pass to it 
    print("Option 1 used") 
    test.close() 

#that with statement works better for file-like objects because it automatically 
#catches and handles any errors that occur, leaving you with a closed object. 
#it's also a little prettier :) Use it like this: 
# 
# with open("test.txt","a+") as f: 
# f.write(whattosaveinfile) 
# print("Option 1 used") 
# 
#note that you didn't have to call f.close(), because the with block does that for you 
#if you'd like to know more, look up the docs for contextlib 

if menu == "1": #no reason to turn this to a string -- you've already defined it by such by enclosing it in quotes 
    savinginfile = raw_input("Please state your name: ") 
    option1(savinginfile) #putting the var in the parens will pass it to the function as a parameter. 

elif menu == "2": #etc 
#etc 
#etc 
+0

你不能以'rw'模式打开文件(它不存在)。我认为最好在这里使用'a +'。 – iCodez

+0

在答案中注明并编辑。 (我并不坦率地处理文件的读/写操作 - 我必须每次查看文件) –

2

建议你通过作为参数:

def option1(savinginfile): 
    test = open ("test.txt", "rw") 
    test.write(savinginfile) 
    print ("Option 1 used") 
    test.close() 

你需要调用之前定义option1。 Python从上到下解释。

+1

只需稍作修改,在JD代码中,作为全局变量的savinginfile不在option1内的范围之外。 option1()会自动搜索全局命名空间。唯一的问题是在调用之前,option1是未定义的。正如你所建议的那样,将savinginfile作为参数传递并在调用之前定义option1是解决问题的正确方法 –

+0

@TwistedMeadow你是对的!仍然不好的做法,但我会更新我的答案(以上)以反映这一点。 –

+0

好抓@TwistedMeadow,没有注意到'如果其他'在顶层。答案改变了 – qwwqwwq