Home > front end >  How do I keep adding 10% to each output number?
How do I keep adding 10% to each output number?

Time:03-02

This is all I have so far:

start = 100
end = x   (.10/x)
i = 0
for number in range(start, end, .10):
    i  = 1 
    print(f"{i}. {number}")

I want the output to look like for the first 50 numbers:

1. 100.0
2. 121.0
3. 133.1

CodePudding user response:

All you should need to do is multiply by 1.1 on each iteration.

start = 100

for number in range(50):
    print(f"{number 1}. {round(start,2)}")
    start = start * 1.10
1. 100
2. 110.0
...
49. 9701.72
50. 10671.9

CodePudding user response:

Some of these answers seem to be overkill (maybe you need that). But here is a simple option:

n = 100 #starting number
p = 0.1 #increment percentage (10% for your case)
for i in range(1, 51):
    print(f'{i}. {round(n,1)}') #print here
    n *= 1 p #add 10% here

Output:

1. 100
2. 110.0
3. 121.0
4. 133.1
5. 146.4
6. 161.1
7. 177.2
8. 194.9
...

CodePudding user response:

range only represents sequences of integers. You can use itertools.count in its place:

from itertools import count

start = 100
end = x   (.10/x)
i = 0
for number in count(start, .10):
    if number >= end:
        break
    i  = 1 
    print(f"{i}. {number}")

count is for infinite streams of numbers, so you need an explicit break condition inside the loop to exit.


Slightly less efficient, you can add itertools.takewhile to terminate the stream early.

from itertools import count, takewhile


start = 100
end = x   (.10/x)
i = 0
for number in takewhile(lambda x: x < end, count(start, .10)):
    i  = 1 
    print(f"{i}. {number}")

Unrelated, you can use enumerate instead of managing i yourself:

from itertools import count, takewhile


start = 100
end = x   (.10/x)
for i, number in enumerate(takewhile(lambda x: x < end, count(start, .10))):
    print(f"{i}. {number}")

or

from itertools import count

start = 100
end = x   (.10/x)
for i, number in enumerate(count(start, .10)):
    if number >= end:
        break
    print(f"{i}. {number}")

CodePudding user response:

This can also be achieved using generator_expression:

start = 100
print(*(f'{x 1}. {round(start*1.1**x, 1)}' for x in range(50)), sep='\n')
  • Related