English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python Reference Manual

Python program checks if the number is positive, negative, or 0

Python instance大全

In this example, you will learn to check if the user input number is positive, negative, or zero. The if...elif...else and nested if...else statements can solve this problem.

To understand this example, you should understand the followingPython programmingTopic:

Source code: Using if ... elif ... else

num = float(input("Enter a number: "))
if num > 0:
   print("Positive number")
elif num == 0:
   print("0")
else:
   print("Negative number")

Here, we use the if...elif...else statement. We can use nested if statements to perform the following operations.

Source code: Using nested if

num = float(input("Enter a number: "))
if num >= 0:
   if num == 0:
       print("0")
   else:
       print("Positive number")
else:
   print("Negative number")

The outputs of the two programs are the same.

Output1

Enter a number: 2
Positive number

Output2

Enter a number: 0
0

If the number is greater than zero, it is a positive number. We check this in the if expression. If it is False, the number will be zero or negative. This is also tested in subsequent expressions.

Python instance大全