2015-02-03 4 views
0

나는 학생들이 완료해야하는 과업 과제에 대한 솔루션을 개발하려고 노력 중이며, 함수간에 변수를 전달하는 데 주저합니다. 나는 다음과 같은 데이터를 생성하는 함수 내에서 퀴즈를 만들었습니다 : 나는 두 번째 함수로이 데이터를 전달해야 하나의 함수에서 다른 함수로 변수에 데이터 전달하기

점수

    • 이름을 그 다음 것 이 데이터를 파일에 추가하십시오 (학생이 속한 그룹에 따라 다름). 내가 매개 변수로 두 번째 함수에 문자열/목록으로 데이터를 전달하기 위해 시도로

      내 코드는 다음과 같습니다

      def Quiz(): 
           #Code to collect user details and generate scoe (10 random questions)  
           strSave=input("Do you want to save your score? y/n") 
           if strSave.lower()=="y": 
            result=(strFirstName+","+strLastName+","+str(score)) 
            #Stores the required data as a csv string 
            return result 
            #?passes the data back? 
            funcSave() 
           elif strSave.lower()=="n": 
            funcQuiz() 
            #restarts the quiz function 
      
      def funcSave(result): 
          #The function to save the score(s) to file 
          group=input("Which group are you A1, A2 or A3?\n") 
          if group=="A1": 
           file=open("A1.txt","a") 
           file.write(result) 
           #error is that result is not defined 
           file.close() 
          elif group=="A2": 
           file=open("A2.txt","a") 
           file.write(strFirstName+","+strLastName+","+str(score)) 
           file.close() 
          elif group=="A3": 
           file=open("A3.txt","a") 
           file.write(strFirstName+","+strLastName+","+str(score)) 
           file.close() 
          else: 
           print("unknown") 
      
  • 답변

    2

    귀하의 문제가 여기에 있습니다 :

    당신은 return 호출을 제거해야
    return result #immediately ends the method, returning result to the caller 
    
    funcSave() # Is never executed because you've return'd. Would throw TypeError if it did because funcSave() needs one argument 
    

    , 그럼 실제로 그렇게처럼 Quiz 방법에서 results 변수를 전달 :

    funcSave(results) 
    

    에도 오타가 있습니다., Quiz() 대신 funcQuiz()이 호출되어 다시 시작됩니다. 대신이의 여담으로

    :

    result=(strFirstName+","+strLastName+","+str(score)) 
    

    당신은 단지이 작업을 수행 할 수 있습니다 파이썬의 join 방법은 . 이전과 함께 문자열을 사용하여 값 목록을 연결

    result = ','.join((strFirstName,strLastName,str(score))) 
    

    구분 기호. 파이썬이 중간 문자열을 생성 할 필요가 없으므로 +을 사용하는 것보다 효율적입니다. join은 모든 값이 문자열이기를 기대하므로 score에 캐스트가 필요합니다.

    +0

    고마워요. 정말로 도움이되고 문제를 설명 할뿐만 아니라 해결 방법을 설명해주었습니다. –

    0

    대신

    return result 
    #?passes the data back? 
    funcSave() 
    

    funcSave(result) 
    

    또한 Quiz 함수의 이름을 funcQuiz으로 바꾸면 다시 시작됩니다.

    0

    funcSave 함수에 전달하기 전에 데이터를 반환한다고 생각합니다. 다른 함수 내의 함수에 데이터를 전달하려는 경우 데이터를 반환하지 않으려 고합니다. 데이터를 반환하면 함수에서 데이터를 가져올 수 있지만 함수의 실행도 종료됩니다.

    이 시도 :

    def Quiz(): 
         #Code to collect user details and generate scoe (10 random questions)  
         strSave=input("Do you want to save your score? y/n") 
         if strSave.lower()=="y": 
          result=(strFirstName+","+strLastName+","+str(score)) 
          # Pass the result to the funcSave function instead of returning it. 
          funcSave(result) 
         elif strSave.lower()=="n": 
          # rename the funcQuiz() function to Quiz() so it is called correctly 
          Quiz() 
          #restarts the quiz function 
    
    def funcSave(result): 
        #The function to save the score(s) to file 
        group=input("Which group are you A1, A2 or A3?\n") 
        if group=="A1": 
         file=open("A1.txt","a") 
         file.write(result) 
         #error is that result is not defined 
         file.close() 
        elif group=="A2": 
         file=open("A2.txt","a") 
         file.write(strFirstName+","+strLastName+","+str(score)) 
         file.close() 
        elif group=="A3": 
         file=open("A3.txt","a") 
         file.write(strFirstName+","+strLastName+","+str(score)) 
         file.close() 
        else: 
         print("unknown") 
    
    +0

    감사합니다. 결과 변수를 함수의 매개 변수로 추가하는 것과 함수를 호출 할 때 위의 솔루션에 약간의 명확성을 추가했습니다. 이제 내가해야 할 일은 과제 3을 해결하는 것뿐입니다! –

    관련 문제