简体   繁体   English

循环的新手问题

[英]Newbie issue with loops

I am brain dead on trying to do the following task in Python(3.) Please help. 我为尝试在Python(3。)中执行以下任务而死了。

Write a loop that calculates the total of the following series of numbers: 1/30 + 2/29 + 3/27 +⋯+ 29/2 + 30/1. 编写一个循环,计算以下一系列数字的总和:1/30 + 2/29 + 3/27 +⋯+ 29/2 + 30/1。

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)

I can produce the quotient of each but am lost on how to efficiently find the sum. 我可以产生每个的商,但是却迷失了如何有效地求和。

For efficiency: 为了提高效率:

In [794]: sum(i*1.0/(31-i) for i in range(1, 31)) # i*1.0 is for backward compatibility with python2
Out[794]: 93.84460105853213

If you have to do that in a loop explicitly, see @Bill's hints ;) 如果必须显式地在循环中执行此操作,请参阅@Bill的提示;)

You're almost there, so I'll give you a few hints. 您快到了,所以我给您一些提示。

# initialize a total variable to 0 before the loop

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)
    # update the total inside the loop (add the quotient to the total)

# print the total when the loop is complete

If you want to see a more Pythonic (idomatic) solution, see zhangxaochen's answer. 如果要查看更多的Pythonic(idomatic)解决方案,请参见zhangxaochen的答案。 ;) ;)

total = 0
for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    print(quotient)
    total += quotient
print/return(total)

Be aware you are going to have some rounding going on and may get an answer you aren't expecting. 请注意,您将要进行一些四舍五入,并且可能会得到您所期望的答案。

Do this to keep track of summation. 这样做可以跟踪求和。

total = 0

for numerator in range(1, 31, 1):
    denominator = (31 - numerator)
    quotient = numerator / denominator
    total = total + quotient

print(total)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM