循环1-10 PRINT只有偶数,只有ODDS或ALL

时间:2014-05-05 13:19:52

标签: python loops python-2.7 while-loop

程序循环1-10,但用户可以选择是否需要 仅打印偶数,只打印奇数或所有数字。

因此,如果用户选择仅打印均匀,则输出应为:   2 4 6 8 10

如果只是奇数:1 3 5 7 9

全部:1 2 3 4 5 6 7 8 9 10

但是当我在下面运行我的代码时,它可以正常打印,但仅限打印 偶数或只打印奇数然后根本不会运行程序。所以我很想知道 这可能是什么错误。

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

2 个答案:

答案 0 :(得分:2)

您的count += 1缩进错误。

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

答案 1 :(得分:0)

首先,不要使用while循环,你应该在这种情况下使用for循环,在那里你知道你在迭代什么:

for count in range(1, 11):

因此可以避免忘记手动增加count(或在这种情况下将其递增到错误位置)的错误。

其次,你应该只运行一次这个循环,并将规则移到其中:

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

请注意,这会显着减少重复,从而可能导致错误。

最后,您可以使用this questionstr.formatenumerate的可选第二个参数来改善您的用户输入:

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):
    ...