简体   繁体   中英

Python 3.x while loop

so here is the idea of the exercise:

I have to make this code:

count = int(input())
while count>0:
    print (count)
    count = count - 1

Sum up the numbers from count, meaning:

5 5
4 9
3 12
2 14
1 15

I've done that part, but I have a problem with the next one.

3 3
2 7
1 8

My code is the following:

count = int(input())
sum = count
while count>0:
    print("%d %d"%(count, sum))
    count = count - 1
    sum = sum + count 

I don't understand how to go from 2 to 7 and from 1 to 8.

Thank you in advance, and I am really sorry for the stupid topic name but I don't really know how to phrase the problem.

Your code will not work as is.

You need to read in each number, not just one, you need sum each number (and not sum the value twice, and not decrement the count, which was being used originally just to loop a number of times.

Assuming that an input of 0 means to stop, and without any error checking:

count = int(input())
sum = 0
while count>0:
  sum = sum + count
  print (count, sum)

  # next input
  count = int(input())

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