如果语句 - 在Python中使用模数运算符嵌套条件

时间:2016-10-13 02:21:57

标签: python if-statement int modulus

我需要在Python中创建一个程序,要求用户输入一个数字,然后告诉用户该数字是偶数还是可以被5整除。如果两者都不是,则不要打印任何内容。例如:

Please enter a number: 5

    This number is divisible by 5!

Please enter a number: 7

Please enter a number: 20

    This number is even!

    This number is divisible by 5!

我尝试复制this answer中使用的方法,但我在第8行收到错误消息:

SyntaxError: invalid syntax (<string>, line 8) (if Num_1 % 2 == 0)

这是我的代码:

#TODO 1: Ask for user input
Num1 = input("Please enter a number")
#TODO 2: Turn input into integer
Num_1 = int(Num1)
#TODO 2: Use conditionals to tell the user whether or not their
#number is even and/or divisible by 5

if Num_1 % 2 == 0
    print ("This number is even!")
        if Num_1 % 5 == 0 
            print ("This number is divisible by 5!")

由于我使用模数运算符来确定Num_1是否是2的精确倍数,我应该返回一个值True,因此应该打印“这个数字是偶数!”但相反,我收到此错误消息 - 为什么?谢谢!

1 个答案:

答案 0 :(得分:2)

每个Python块的开头应以冒号:结束。另请注意缩进。

Num1 = input("Please enter a number")
Num_1 = int(Num1)

if Num_1 % 2 == 0:
    print ("This number is even!")
    if Num_1 % 5 == 0:
        print ("This number is divisible by 5!")