Python 程序:检查数字是正数,负数还是 0
在此示例中,您将学习检查用户输入的数字是正数,负数还是零。 使用if...elif...else和嵌套if...else语句可以解决此问题。
要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:
源代码:使用if...elif...else
num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
在这里,我们使用了if...elif...else语句。 我们可以使用嵌套的if语句执行以下操作。
源代码:使用嵌套if
num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number") else: print("Negative number")
两个程序的输出将相同。
输出 1
Enter a number: 2 Positive number
输出 2
Enter a number: 0 Zero
如果数字大于零,则为正数。 我们在if的表达式中对此进行检查。 如果为False,则数字将为零或负。 在后续表达式中也对此进行了测试。