简体   繁体   中英

How can I sum the result of number values?

Hi im a beginner in Python. and I've just a simple question for you but I can't figure it out anyway.

for i in range(7,10):
    function= (1/i)
    i+=1
    print(function)

then it prints

0.14285714285714285
0.125
0.1111111111111111

but firstly I want to sum these values and after that print. How can i?

Python几乎就像自然语言一样:

print(sum(1 / i for i in range(7, 10)))

What about something like this:

total = 0

for i in range(7,10):
    function = 1/i
    total = total + function

print(total)

The idea is that every time the iteration is ran i increases by one, also since the range is a list ( [7,8,9,10] ), the first time i will be 7, then 8 and so on. The only printed value will be the total sumation at the end. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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