2017-10-09 12 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

以前にゼロに設定した余分な変数をループ内に追加しました。ところで

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)) 

、私はまた、subject()subjectsNumパラメータを行い、新たなスタイルformat機能を使用し、[N-1、0]上iをループの代わりに、[1、N]。

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 
関連する問題