-
Book Overview & Buying
-
Table Of Contents
Python Illustrated
By :
An if statement lets your program decide whether to execute a block of code based on a condition. Imagine you’re deciding whether you want to chase a laser pointer or take a nap. You probably weigh factors such as how sleepy you are, whether the sun is shining on your favorite spot, or whether the laser pointer is even on. In programming, we use conditional statements to make such decisions. This is what an if statement looks like:
if condition:
# Code to execute if condition is True
The condition is a statement that evaluates to True or False. If it evaluates to True, it executes the block that comes after. How can we recognize the block? Well, this is where indentation comes in. The block can be recognized by being the same level of indentation. In Python, the code inside the if block must be indented. Usually, we use four or two spaces.

Let’s see an actual example. Let’s say we want to check whether it’s time for...