Loading lesson path
Python supports the usual logical conditions from mathematics:
a == b
a != b
Formula
a < ba <= b
Formula
a > ba >= b These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword.
Formula
a = 33 b = 200 if b > a:print("b is greater than a")In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a.
is 33, and b is
200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".The if statement evaluates a condition (an expression that results in
). If the condition is true, the code block inside the if statement is executed. If the condition is false, the code block is skipped.
Checking if a number is positive:
Formula
number = 15 if number > 0:print("The number is positive")Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.
If statement, without indentation (will raise an error):
Formula
a = 33 b = 200 if b > a:print("b is greater than a")# you will get an error
You can use spaces or tabs for indentation, but you must use the same amount of indentation for all statements within the same code block.
You can have multiple statements inside an if block. All statements must be indented at the same level.
Multiple statements in an if block:
Formula
age = 20 if age >= 18:print("You are an adult")
print("You can vote")
print("You have full legal rights")Boolean variables can be used directly in if statements without comparison operators.
Formula
is_logged_in = True if is_logged_in:print("Welcome back!")Python can evaluate many types of values as
False in an if statement. Zero (
), empty strings ( "" ), None, and empty collections are treated as
False. Everything else is treated asTrue. This includes positive numbers (
), negative numbers ( -3
Formula
), and any non - empty string (even"False" is treated as
Formula
True because it's a non - empty string).