for循环,尝试排除if和else语句中的数字

时间:2016-10-11 19:48:17

标签: python

我是python的新手,因为你可以看到' n'可以被5,6和5& 6整除但是对于那些数字它仍然显示(例如100O)当它被5或6分割时我不想要' n'要打印的号码。任何建议都会有所帮助,但请保持新手级别,以便我学习。

def main():
    numHigh = 101
    for n in range(numHigh, 0, -1):
        print(n)
        if (n % 5 == 0):
            print("Where do you see yourself in five years?")
        elif (n % 6 == 0):
            print("I'll believe six impossible things before breakfast.")
        elif (n % 5 == 0) & (numHigh % 6 == 0):
            print("Thirty days in hath September.")
main()


Sample Output: 
101
100
Where do you see yourself in five years?
99
98
97
96
I'll believe six impossible things before breakfast.
95
Where do you see yourself in five years?
94
93


I want this output:
101
Where do you see yourself in five years?
99
98
97
96
I'll believe six impossible things before breakfast.
Where do you see yourself in five years?
94
93

2 个答案:

答案 0 :(得分:1)

def main():
numHigh = 101
for n in range(numHigh, 0, -1):
    if (n % 5 == 0):
        print("Where do you see yourself in five years?")
    elif (n % 6 == 0):
        print("I'll believe six impossible things before breakfast.")
    elif (n % 5 == 0) & (numHigh % 6 == 0):
        print("Thirty days in hath September.")
    else:
        print(n)
main()

答案 1 :(得分:1)

print(n)位于for循环的开头,因此每次循环运行时都会打印n。相反,你应该在ifs和elif之后创建一个else语句。这样,如果所有ifs / elifs都不正确,它将打印n。

喜欢这个

if …
elif …
elif …
else:
    print(n)