【问题标题】:If Statement - Nested Conditional Using Modulus Operator in PythonIf 语句 - Python 中使用模运算符的嵌套条件
【发布时间】:2017-02-22 00:04:14
【问题描述】:

我需要用 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 值,因此应该打印“这个数字是偶数!”但是相反,我收到了此错误消息-为什么?谢谢!

【问题讨论】:

    标签: python if-statement int modulus


    【解决方案1】:

    每个 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!")
    

    【讨论】:

    • Brilliant - 不知道 Python 要求每个块的开头都以冒号结尾。与您对缩进的更正相同 - 谢谢。
    猜你喜欢
    • 2014-10-17
    • 2019-11-14
    • 2021-03-04
    • 2011-02-18
    • 1970-01-01
    • 2017-01-03
    • 2012-02-17
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多