Rey
Rey

Reputation: 11

Add value repeatedly in Python

This might be very simple, but I'm having trouble finding the answer (possibly because it is difficult to figure out how to format the question).

I would like to do in Python what I can do in Excel, wherein there is a set value (set with the $) that can be repeatedly added to the previous value in order to generate a list.

For example:

1 + 4 = 5,
5 + 4 = 9,
9 + 4 = 13, et cetera.

I feel like the answer is obvious, but I am struggling to figure out what it is.

Any help would be appreciated.

Upvotes: 0

Views: 309

Answers (3)

user7589150
user7589150

Reputation:

The above works really well, but if you want to display the calculation in your list, as you state above, then try this.

num = input("Number here:")
num_list = []
while True:
    addNum = input("Add number :")
    try:
        sumNum = int(num)+int(addNum)
        num_list.append(num+" + "+addNum+" = "+str(sumNum))
        print(num_list)
        num = str(sumNum)
    except TypeError:
        print("Pease insert a valid whole number")

Your list will look like this: [1+2=3,3+4=5,5+9=14]....

Correct me if I misunderstood the question.

Upvotes: 0

Oyster773
Oyster773

Reputation: 375

You can use a loop and your set value in a variable. Not exactly sure what you meant by generating a list. Consider the following:

def addManyTimes(self, howManyTimes, initialValue, constantValue):
    your_list = []
    for x in range(howManyTimes):
        initialValue += constantValue
        your_list.append(initialValue)
    return your_list

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54223

You could simply use a range with a specific step:

>>> range(1, 100, 4)
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97]

and in Python3:

>>> list(range(1, 100, 4))
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97]

Upvotes: 2

Related Questions