Python If Statement
An if statement is a statement that runs a block of code only when its condition is true. A false condition skips the block.
A simple if
The block runs, because the condition is true.
score = 75
if score >= 50:
print("You passed")When the condition is false
Now the block is skipped. The last line is not indented, so it always runs.
score = 30
if score >= 50:
print("You passed")
print("Program finished")A block can hold many lines
Every line with the same indent belongs to the block.
temperature = 30
if temperature > 25:
print("It is warm")
print("Drink some water")Values can act true or false
Truthy and falsy values come from the Data Types section. A non-empty string acts as true.
name = "Ana"
if name:
print("Name is set")Example
score = 68
print("Your score is", score)
if score >= 50:
print("You passed the test")
print("Result checked")Key points
- Condition: the test after the word if.
- It gives True or False.
- Use if to run a block only when its condition is true.
- Indent: the block lines up under the if line, with four spaces.
- A false condition skips the block.
- The rest of the program still runs.
- Truthy values act as true in a test, like a non-empty string.
- Falsy values act as false, like 0 or an empty string.
In this example, score is 68. The first line prints the score. The if tests 68 >= 50, which is true. So the indented line runs and prints the pass message. The last line is not indented. It runs no matter what the test said.
Note
Python needs no brackets around the condition.
End the if line with a colon instead.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does this code print? age = 16 if age >= 18: print("Adult") print("Done")