Question

The program loops 1-10 but the user can choose whether they want to print only the even numbers, only the odd numbers, or all the numbers.

So, if the user choose to print only evens then the output should be: 2 4 6 8 10

If only odd: 1 3 5 7 9

All: 1 2 3 4 5 6 7 8 9 10

But when I run my code below, it works normally for print all but for print only even or print only odd then it won't run the program at all. So I was wondering what may be the mistakes here.

MODE = ["Only Even", "Only Odds", "All Numbers"]
for i,v in enumerate(MODE):
    print i+1, v
count = 0
s = int(input("Enter Mode Wanted: "))
if s == 3:
    while count < 10:
        print count+1
    count += 1
elif s == 2:
    while count <=10:
        if count%2 != 0:
            print count
    count += 1
elif s == 1:
    while count <= 10:
        if count%2 == 0:
            print count
    count += 1
Was it helpful?

Solution

Your count += 1 indentation is wrong.

CORRECTED:

MODE = ["Only Even", "Only Odds", "All Numbers"]
for i,v in enumerate(MODE):
    print i+1, v
count = 1                 #changed 0 to 1
s = int(raw_input("Enter Mode Wanted: "))
if s == 3:
    while count <= 10:    #changed < to <=
        print count       #changed count+1 to count
        count += 1
elif s == 2:
    while count <=10:
        if count%2 != 0:
            print count
        count += 1
elif s == 1:
    while count <= 10:
        if count%2 == 0:
            print count
        count += 1

OTHER TIPS

First, rather than use a while loop, you should use a for loop in cases like this, where you know what you are iterating over:

for count in range(1, 11):

thus saving you from the error of forgetting to manually increment count (or incrementing it in the wrong place, in this case).

Second, you should run this loop only once, and move your rules inside it:

for count in range(1, 11):    
    if (s == 3 or 
        (s == 2 and count % 2 != 0) or 
        (s == 1 and count % s == 0)):
        print count

Note how this significantly reduces duplication and, thus, potential for error.

Finally, you can use this question, str.format and the optional second argument to enumerate to improve your user input:

MODE = ["Only Even", "Only Odds", "All Numbers"]
for i, v in enumerate(MODE, 1):
    print "{0}: {1}".format(i, v)
while True:
    try:
        s = int(input("Enter mode wanted: "))
    except ValueError:
        print("Not an integer.")
    else:
        if s in range(1, len(MODE) + 1):
            break
        print("Not a valid mode.") 
for count in range(1, 11):
    ...        
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top