python logo

Tag: if

If statements

In Python you can define conditional statements, known as if-statements.
A block of code is executed if certain conditions are met.

Related Course:
Python Programming Bootcamp: Go from zero to hero

If statements

Consider this application, it executes either the first or second code depending on the value of x.


x = 3
if x > 10:
print("x smaller than 10")
print("x is bigger than 10 or equal")

If you set x to be larger than 10, it will execute the second code block.   We use indentation (4 spaces) to define the blocks.

A little game:
A variable may not always be defined by the user, consider this little game:

age = 24

print "Guess my age, you have 1 chances!"
guess = int(raw_input("Guess: "))

if guess != age:

Conditional operators

A word on conditional operators

Do not confuse the assignment operator (=) with the equals operator (==).


The most straightforward way to do multiple conditions is nesting:

Operator Description
!= not equal
== equals
> greater than
< smaller than
a = 12
b = 33

if a > 10:
if b > 20:

This can quickly become difficult to read, consider combining 4 or 6 conditions.  Luckily Python has a solution for this, we can combine conditions using the and keyword.

guess = 24
if guess > 10 and guess < 20:
print("In range")
print("Out of range")

Sometimes you may want to use the or operator.

If you are new to Python programming, I highly recommend this book.

Download Python Exercises