If statements
Python hosting: PythonAnywhere: host, run and code Python in the cloud. Free tier available.
In Python you can define conditional statements, known as if-statements. A block of code is executed if certain conditions are met.
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")
Want more practice on this without setting anything up? PyChallenge has graded loop and condition exercises that run in the browser, and the error message tells you what went wrong.
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| Operator | Description |
| != | not equal |
| == | equals |
| > | greater than |
| < | smaller than |