我希望能够计算出总时间的总和'循环返回的。关于如何做的任何想法?这是我目前的代码:
由于
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()
答案 0 :(得分: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 :(得分: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]。
答案 2 :(得分: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