Reputation: 29
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?
Upvotes: 2
Views: 949
Reputation: 1856
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)
Upvotes: 0
Reputation: 161
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)
Upvotes: 0
Reputation: 37299
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))
.
Upvotes: 4