find specific numbers in a sequence


Hi I’d like to understand how in the following python program to proceed to add "the latest added number" and the "count of numbers that were added". the output should be like [121 21 11], the code gives 121 but how do I get the other two?

sum = 0
k = 1
while sum <= 100:
  sum = sum + k
  k = k + 2

I don’t know what commands to use to find out the answer, sum is 121, how do I add 21 which is the last number added before sum <= 100 and 11 which is the count of numbers (1,3,5,7,9,11,13,15,17,19,21)

Asked By: ruff



First off, "sum" is a built-in function, so you should not use it as a variable name.

Next, you can easily build a list of your nums making it easy to get sum, count, last, etc.

nums = [1]
while sum(nums) <= 100:

print(sum(nums), nums[-1], len(nums))
121 21 11
Answered By: Kurt

you should just store your ks in a list so you can access them later:

sum = 0
k = 1
k_list = [1]

while sum <= 100:
    sum += k
    k += 2

print(sum, k_list[-1], len(k_list))
Answered By: maxxel_
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.