【问题标题】:Calling function inside if statement在 if 语句中调用函数
【发布时间】:2013-12-11 18:16:13
【问题描述】:

我试图在 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()

【问题讨论】:

  • 什么不起作用??你得到一个错误代码??请详细说明。

标签: python function if-statement


【解决方案1】:

建议您将savinginfile 作为参数传递:

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

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

【讨论】:

  • 只是一个小修正,在JD的代码中,将infile保存为全局变量并没有超出option1的范围。 option1() 将自动搜索全局命名空间。唯一的问题是 option1 在调用之前未定义。正如您所建议的,将 saveinfile 作为参数传递并在调用之前定义 option1 是解决它的正确方法
  • @TwistedMeadow 你说得对!仍然是不好的做法,但我会更新我的答案(上面)以反映这一点。
  • 好消息@TwistedMeadow,没有注意到if else 在顶级。答案变了
【解决方案2】:

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

抛出过多的全局变量也是不好的做法。你不应该像现在这样使用savinginfile——相反,将它作为参数传递给函数,让函数在自己的范围内运行。您需要将要使用的文件名传递给函数,然后它才能使用savinginfile。试试吧:

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

【讨论】:

  • 您无法在rw 模式下打开文件(它不存在)。我认为最好在这里使用a+
  • 在答案中注明和编辑。 (坦率地说,我不太会处理文件的读/写——我每次都必须查一下)
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 2020-06-09
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 2016-06-28
相关资源
最近更新 更多