Question

Hi all I'm new to programming, and trying to understand while loop in Python.

I want to print the following

print 2
print 4
print 6
print 8
print 10
print "Goodbye!" 

Here's what I wrote

x = 0
sum = x

while (sum != 10):
    x = x + 2
    print x
    sum = x + 2
    Print ('Good bye!') 

Can any one please let me know where am I going wrong..

Was it helpful?

Solution

The most direct fix:

x = 0
sum = x

while (sum <= 10):
    x = x + 2
    print x
    sum = x + 2
print ('Good bye!')  # <-- lower case, unindented

A shorter solution:

for x in range(2, 12, 2): # start at 2, increment by 2, up to but not including 12
    print x
print 'Good bye!'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top