Home > Back-end >  Create an odd number list
Create an odd number list

Time:09-21

i want to make an odd number list by using 'while' and 'for'

a = []
x = 1
while x < 101:
    if x % 2 != 0:
        a.append(x)
        x = x   1
print(a)

but nothing happened... and other unrelated codes which is in another sentence are also not executed. what is my problem?

CodePudding user response:

You should increase the value of x in each iteration and not only if the value is an odd number:

a = []
x = 1
while x < 101:
    if x % 2 != 0:
        a.append(x)
    x  = 1
print(a)

Though this is probably for learning purposes note that you could achieve this using the range function as follows: list(range(1,101, 2)).

CodePudding user response:

When you increment x, it should be out of 'if' condition. increment should happen under while

a = list()
x = 1
while x <101:
    if x%2 != 0:
        a.append(x)
    x  = 1
print(a)

CodePudding user response:

You can use the range function as well (for for loop) which handles the increment part in the loop as below:
FOR LOOP:

odd=[]
for i in range(101):
    if (i%2!=0):
        odd.append(i)
print (odd)

WHILE LOOP:

odd=[]
i = 1
while i<101:
    if i%2 != 0:
        odd.append(i)
    i =1
print (odd)
  • Related