2013-12-11 4 views
2

if 함수 내부에서 함수를 호출하려하지만 작동하지 않습니다. 이것은 파이썬 사용에 대한 나의 첫 번째 시도 중 하나입니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?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를 정의 할 필요가있다. 파이썬은 위에서 아래로 해석합니다.

+1

JD의 코드에서 전역 변수로서의 savinginfile이 option1의 범위를 벗어나지 않았습니다. option1()은 전역 네임 스페이스를 자동으로 검색합니다. 유일한 문제는 option1이 호출 전에 정의되지 않는다는 것입니다. 당신이 제안한대로, saveinfile을 매개 변수로 전달하고 호출하기 전에 option1을 정의하는 것이 올바른 방법입니다. –

+0

@TwistedMeadow 맞습니다! 여전히 나쁜 습관이지만, 나는 그것을 반영하기 위해 나의 대답 (위)을 업데이트 할 것이다. –

+0

좋은 catch @TwistedMeadow는 'if else'가 최상위 레벨에 있다는 것을 알지 못했습니다. 답변이 변경되었습니다. – qwwqwwq