简体   繁体   中英

Calling function inside if statement

im trying to call function inside if statement but it does not work. This is one of my first attempts in using Python. What am I doing wrong?

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

Would recommend that you pass savinginfile as a parameter:

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

You need to define option1 before calling. Python interprets from top to bottom.

You need to define your function before you try to call it. Just put def option1(): #and all that code below it above your if statements.

It's also bad practice to throw around too many global variables. You shouldn't use savinginfile the way you are -- instead, pass it to the function as a parameter and let the function operate in its own scope. You'll need to pass the function the name of the file to use before it's able to use savinginfile . Try instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM