Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use variable > 0 to check whether a Python value is greater than zero. The comparison is strict: it returns True for a positive value and False for zero or a negative value.

Use an explicit comparison

Put the comparison in an if statement when you want to run code only for a positive value:

if variable > 0:
    print("The value is greater than zero")

Python’s comparison operators are described in the Python Language Reference. A comparison such as variable > 0 evaluates to the Boolean value True or False. If you need to keep the result, assign it to a variable:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
is_positive = variable > 0

Why if variable: is different

A bare condition checks truthiness, not whether a value is above a threshold. In Python, numeric zero is false in a Boolean context, but a nonzero negative number is true. As a result, if variable: can accept negative numbers, while if variable > 0: rejects them. Python documents these rules under truth value testing and comparisons.

for variable in (5, 0, -3):
    print(variable, variable > 0)

This prints:

5 True
0 False
-3 False

Check that the value can be compared with zero

The value must support an ordering comparison with the integer 0. For example, Python does not order complex numbers with >; attempting that comparison raises TypeError, as specified in the comparison rules. Other types may define their own comparison behavior, so use a value whose comparison semantics fit your purpose.

When the value comes from input

input() returns text. Convert and validate that text before comparing it numerically; do not compare a string such as "5" directly with integer zero in Python 3. The appropriate conversion depends on the kind of number your program expects.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi