2014-11-25 3 views
-2
def perd(): 

    Personaldetails_file = open("Personaldetails_file.txt", "w") 
    Personaldetails_file = open("Personaldetails_file.txt", "a") 

    pd = input("Are you a new user?") 

    if pd == "yes": 
     print ("Add your details") 
    ####################################  
    age = int(input("how old are you?")) 
    DOB = input("Date of birth:") 
    gender = input("Gender:") 
    weight = int(input("weight in kg:")) 
    height = int(input("height in cm:")) 

    Personaldetails = (age, DOB, gender, weight, height) 

    Personaldetails_file.write(str(Personaldetails)) 
    Personaldetails_file.close() 

    ####################################### 


def td(): 

    choice = input("which trainning event would you like to access?\n1.swimming\n2.cycling\n3.running\nplease type in the number before the event of which you want to choose\n") 
    if choice == "1": 
     Swimming_file= open("Swimming_file.txt", "w") 

     totaldistance = input("what was the total distance you swam in meters?") 
     totaltime = input("how long did you swim for in minutes?") 
     speed = totaldistance/totaltime 
     print ("on average you where running at a speed of", speed, "mps\nyou can look at the tables to see how many calouries you have burnt") 

     total = (totaldistance, totaltime, speed) 
     Swimming_file.write(str(total)) 
     Swimming_file.close() 

    elif choice == "3": 
     Running_file= open("Running_file.txt", "w") 


     totaldistanceR = int(input("what was the total distance you ran in KM?")) 
     totaltimeR = int(input("how long did you run for in minutes?")) 
     totaltimeR1 = 60/totaltimeR 
     speedR1 = totaldistanceR/totaltimeR1 
     calburn = (speedR1 * 95)/(60/totaltimeR1) 

     print ("\nThe records have been saved") 
     print ("\non average you where running at a speed of", speedR1, "KMph\nyou burnt",calburn," calouries\n") 

     totalR = (totaldistanceR, totaltimeR, speedR1, calburn) 
     Running_file.write(str(totalR)) 
     Running_file.close() 
    ############################################################## 
    elif choice == "2": 
     Cycling_file= open("Cycling_file.txt", "w") 
     with open("Personaldetails_file.txt", "r") as f: 
     content = [x.strip('\n') for x in f.readlines()] 
     lines = f.readlines() 
     for line in lines: 
      words = line.split(",") 
      age = (line.split)(0) 
      weight = (line.split)(3) 
      height = (line.split)(4) 
################################################################    
     totaldistancec = int(input("what was the total distance you cycled in KM?")) 
     totaltimec = int(input("how long did you cycle for in minutes?")) 
     calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)     
     speedc = totaldistancec/totaltimec 
     print ("on average you where running at a speed of", speedc, "KMph\nyou burnt", calburn1, " calouries") 

     totalc = (totaldistancec, totaltimec, speedc) 
     Cycling_file.write(str(totalc)) 
     Cycling_file.close() 
     Personaldetails_file.close() 

오류 메시지가 나타나면 오류가 나타납니다. TD calburn1 = (13.75 * 무게) + (5 * 높이)의 라인 (84) - (6.67 * 세) UnboundLocalError : 할당 전에 참조 된 지역 변수 '무게'사람이 내가이 오류를 해결할 수있는 방법을 알고 있나요? '#의'에 둘러싸여 질문에 관련이 코드언 바운드 로컬 오류 수정 방법을 모르겠다.

+1

파이썬 들여 쓰기는 구문의 일부입니다. 코드를 들여 씁니다. –

+0

어떻게 함수를 td 또는 perd라고 부릅니까? –

+0

'weight' 변수가 처음에'int (input ("weight in kg :"))'로 설정되기를 원한다면 함수 몸체의 첫 번째 줄에'global weight'가 있어야합니다. 그렇지 않으면 python 전역 변수를 원하는지 알 수 없습니다. – Alec

답변

1

현재 체중

def perd(): 

... 
    gender = input("Gender:") 
    weight = int(input("weight in kg:")) 
    height = int(input("height in cm:")) 

... 

선언하지만 당신이 다른 기능에 여기를 사용하려고 :

def tr(): 
    .... 
    calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age) 
    .... 

이있다 perd() 함수 내의 변수에 대해 알지 못하는 별도의 함수와 그 이유는 무엇입니까? 코드 조각을 분리하여 스스로 사용할 수 있어야하므로 함수를 조작 할 필요가 없습니다. 즉, perd()이 실행되면 로컬 변수가 범위를 벗어납니다. 이 질문을보십시오, Short Description of the Scoping Rules?. 이 문제를 해결하려면 perd()에서 입력을 받아 들일 필요가 있습니다. 매우 pythonic이 아니기 때문에 바람직하지 않습니다. 또는 다음과 같이 함수 매개 변수로 값을 전달할 수 있습니다.

td(weight, height, age): 
    #code here 

이제 td 함수 내에서 전달 된 값에 액세스 할 수 있습니다. 그러나 당신은 이것이 동일한 변수가 아니라는 것을 깨달을 필요가 있습니다. 그들은 같은 이름을 공유 할 수도 있지만 같은 것이 아닙니다. 퍼드 기능에서 사용하고자하는 모든 값을 전달해야합니다. 이것은 모듈성을 사용할 수있는 방식으로 함수를 설계하므로 다른 사용자가 이미 알고있는 데이터에 대해 계산을 수행 할 수 있기 때문에 사용자가 입력을 처리 할 수 ​​있으므로 코드를 더 쉽게 읽을 수 있으므로 바람직합니다. 파이썬은 무엇에 관한 것입니까

관련 문제