2017-10-09 2 views
0

나는 루프에 의해 반환되는 'totalTimes'의 합계를 계산할 수 있기를 원합니다. 그것을하는 방법에 대한 아이디어? 여기에 내가 현재 가지고있는 코드 :루프의 결과 요약

감사

subjectsNum = int(input ("How many subjects do you have to study?")) 

def subject(): 
    for i in range (1, subjectsNum+1): 

     subjectName = input ("What is the subject name?") 
     pagesQuantity = float(input ("How many pages do you have to study?")) 
     pagesTime = float (input ("How long do you reckon it will take to study one page (in minutes)?")) 
     totalTime = (pagesQuantity) * (pagesTime)/60 
     print("The estimated time to study %s is %s hours" %(subjectName, totalTime)) 


subject() 

답변

1

물론, 그냥 루프 외부의 누적 목록이 있습니다.

def subject(): 
    times = [] # this is our accumulator 
    for i in range(1, subjectsNum+1): 
     ... 
     times.append(totalTime) 

    return times # return it to the outer scope 

times = subject() # assign the return value to a variable 
grand_total = sum(times) # then add it up. 
1

이전에 0으로 설정 한 추가 변수를 루프에 추가하십시오. 그런데

def subject(subjectsNum): 
    totalSum = 0 
    for i in range (subjectsNum): 

     subjectName = input ("What is the subject name?") 
     pagesQuantity = float(input ("How many pages do you have to study?")) 
     pagesTime = float (input ("How long do you reckon it will take to study one page (in minutes)?")) 
     totalTime = (pagesQuantity) * (pagesTime)/60 
     print("The estimated time to study {} is {} hours".format(subjectName, totalTime)) 
     totalSum += totalTime 
    return totalSum 


subjectsNum = int(input ("How many subjects do you have to study?")) 
totalSum = subject(subjectsNum) 
print("Sum is {}".format(totalSum)) 

는, I는 subject()subjectsNum 파라미터를 만들어, 상기 새로운 스타일을 format 함수를 사용하고, 위에 i을 반복 [0, N-1] 대신 [N (1)]의.

0

for 루프의 반환 값을 사용하려면 결과를 어딘가에 저장하고 마지막으로 모든 결과를 합산해야합니다.

subjectsNum = int(input ("How many subjects do you have to study?")) 

Final_total_time=[] 

def subject(): 
    for i in range (1, subjectsNum+1): 

     subjectName = input ("What is the subject name?") 
     pagesQuantity = float(input ("How many pages do you have to study?")) 
     pagesTime = float (input ("How long do you reckon it will take to study one page (in minutes)?")) 
     totalTime = (pagesQuantity) * (pagesTime)/60 
     print("The estimated time to study %s is %s hours" %(subjectName, totalTime)) 
     Final_total_time.append(totalTime) 


subject() 

print(sum(Final_total_time)) 

출력 :

How many subjects do you have to study?2 
What is the subject name?Physics 
How many pages do you have to study?10 
How long do you reckon it will take to study one page (in minutes)?2 
The estimated time to study Physics is 0.3333333333333333 hours 
What is the subject name?Python 
How many pages do you have to study?5 
How long do you reckon it will take to study one page (in minutes)?1 
The estimated time to study Python is 0.08333333333333333 hours 
0.41666666666666663