2. If
An if statement runs a block of code only when its condition is True:
- The condition goes after
ifand before a colon:. - The block is the code indented below the
if. By convention, use four spaces. - When the condition is
False, the block is skipped and the program continues. ifis a statement, not a function: it does not need parentheses and it does not produce a value.
The condition is usually a comparison, so it produces True or False.
Coming from JavaScript? Blocks are defined by indentation, not { }, and the condition needs a colon. Parentheses around the condition are optional.
Run a block when the condition is true
Create a variable age with the value 18. Use an if statement to check age >= 18 and, inside its block, print Adult.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Skip the block when the condition is false
Create a variable age with the value 15. Use an if statement to check age >= 18 and print Adult inside its block.
Because 15 >= 18 is False, the block is skipped. The program must print nothing at all:
Create a free account to save your progress and unlock chapter 2.
Read an age and check it
Read an age with input("Age: "). input() returns text, so wrap it in int() before comparing it with 18. If the age is 18 or more, print Adult.
The simulated user types 20, so the console shows the prompt, the typed line and the result.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Compare text
Create a variable password with the value "python". Use an if statement to check whether it is equal to "python" and, if it is, print Access granted.
Print exactly:
Create a free account to save your progress and unlock chapter 2.