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 Courses:

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

OperatorDescription
!=not equal
==equals
>greater than
<smaller than

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

Nesting

The most straightforward way to do multiple conditions is nesting:

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.

21 thoughts on “If statements

  1. Erica - November 21, 2015

    I am new to python and just learning the syntax. (I am experienced in other languages).
    What is the syntax if I want more than one line of code between if: and else:, and more than one line after else: ?

    1. Frank - November 23, 2015

      Hi Erica, simply add the lines between if and lines. Python uses indention to define the code blocks. All lines should have the same indention. By default Python imposes four spaces.

  2. Eric - September 16, 2015

    hello, I’m using a version 3.5 of Python which may be a little different from the tutorial. when I type “else” after “if”, it always says invalid syntax. I’m totally confused of that.

    1. Frank - September 16, 2015

      Hi Eric,
      Could you post the code you use? Make sure your indention is right. Python expects four spaces for every code block.