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:
Complete Python Bootcamp: Go from zero to hero in Python 3

If statements


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



#!/usr/bin/python

x = 3
if x > 10:
print("x smaller than 10")
else:
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:
print("Wrong!")
else:
print("Correct")

Conditional operators


A word on conditional operators

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

Nesting


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:
print("Good")

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")
else:
print("Out of range")

Sometimes you may want to use the or operator.