Python Conditions and If statements
Conditions in Python work like the comparisons you know from math class:
a == b: equala != b: not equala < b: smaller thana <= b: smaller than or equala > b: larger thana >= b: larger than or equal
You will meet these comparisons in many places, above all in loops and in "if statements".
To write an "if statement", begin with the if keyword.
Example
a and 200 to b, then uses an if statement to check if b is greater than a and prints a message.
Output: complete Python program
a = 33
b = 200
if b > a:
print("b is greater than a")
How If Statements Work
An if statement looks at a condition, meaning an expression whose value is either True or False. When the answer is True, Python runs the statement's code block. When it is False, Python skips that block.
Example
if statement and prints a message.
Output: complete Python program
number = 15
if number > 0:
print("The number is positive")
Indentation
Many languages mark a block of code with curly brackets. Python uses indentation instead: the whitespace at the start of a line is what defines scope in your code.
Note: Spaces and tabs both work, but every statement in one code block has to be indented by the same amount.
Example
if statement without proper indentation to demonstrate that Python will raise an error.
Output: complete Python program
a = 33
b = 200
if b > a:
print("b is greater than a")
Multiple Statements in If Block
An if block is not limited to one line. Put as many statements in it as you need, and indent each of them to the same level.
Example
age is 18 or older and prints multiple statements inside the if block.
Output: complete Python program
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("You have full legal rights")
Using Variables in Conditions
A boolean variable needs no comparison operator: you can place it straight after if.
In fact, an if statement can judge many kinds of values as True or False.
The values that count as False are zero (0), empty strings (""), None and empty collections. All other values count as True.
So positive numbers like 5, negative numbers like -3 and every string with at least one character count as True. That even covers "False", because the string is not empty.
Example
if statement to print a welcome message.
Output: complete Python program
is_logged_in = True
if is_logged_in:
print("Welcome back!")