Cha04F
Cha04F

Reputation: 35

While Loops - Increment a List

I'm stuck trying to figure out this while loop. It seemed simple at first but I keep running into errors. I think I just haven't used python in a while so it's hard to get back into the gist of things.

Write a while loop that will add 100 numbers to a list, starting from the number 100 and incrementing by 2 each time. For example, start from 100, then the next number added will be 102, then 104 and so on.

I have this so far;

count = 0
while count < 99:
    count += 1
    numbers.append(len(numbers)+2)

for x in numbers:
    print(x)

But that is simply giving me 0-100 printed out when I want it to be 2,4,6,8,10,...

Upvotes: 0

Views: 4417

Answers (4)

jhpratt
jhpratt

Reputation: 7130

Try numbers.extend(range(100, 300, 2)). It's a much shorter way to do exactly what you're looking for.

Edit: For the people downvoting, can you at least leave a comment? My initial response was prior to the question being clarified (that a while loop was required). I'm giving the pythonic way of doing it, as I was unaware of the requirement.

Upvotes: 0

Aidenhjj
Aidenhjj

Reputation: 1289

With a few modifications, and using a while loop as per your exercise:

numbers = []
count = 0
while count < 100:
    numbers.append(100 + (2*count))
    count += 1

for x in numbers:
    print(x)

Or with a for loop:

numbers = []
for i in range(100):
    numbers.append(100 + (2*i))

for x in numbers:
    print(x)

Or as a list comprehension:

numbers.extend([(100 + (2*el)) for el in range(100)])

Or as a recursion:

numbers = []
def rec(num):
    if num < 100:
        numbers.append(100 + (2*num))
        rec(num + 1)
rec(0)

Upvotes: 1

Fejs
Fejs

Reputation: 2888

Something like this:

numbers = []
while len(numbers) != 100:
    if len(numbers) > 0:
        numbers.append(numbers[-1] + 2)
    else:
        numbers.append(100)

Little explanation: You loop until your list has 100 elements. If list is empty (which will be at the beginning), add first number (100, in our case). After that, just add last number in list increased by 2.

Upvotes: 0

user7141836
user7141836

Reputation:

numbers = []

index = 0
number = 100
while index < 100:
    number += 2
    index += 1
    numbers.append(number)

for x in numbers:
        print(x)

Upvotes: 1

Related Questions