2017-10-09 99 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)) 

順便說,我也發subjectsNum的參數subject(),和所使用的新型format功能,和環i在[0,N-1]代替[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