In Python, you can use If Else statements to control logics, for example if you have a variable x (10):
x = 10
and you wanted to print out something depending if x is equals to 10 or not you can use
Code: Select all
if (x==10):
print ("x is ten!")
else:
print ("x is NOT ten!")
You don't have to have the else statement and its block of code at all. It's just there to show you the syntax if you need to use the else.
Notice to compare if value is equal to some other value we use double equal sign (==). This is so because the single equal sign (=) indicates variable assignment and so we don't confuse it between trying to compare x to value and setting x to hold a value.
You can have an
elif
(elseif statement) statement between the if and else statements if you want to check for additional conditions before running the else statement.For example you can do this
Code: Select all
x = 8
if (x==10):
print ("x is ten!")
elif (x==8):
print ("x is eight!")
elif (x==6):
print ("x is six!")
else:
print ("x is NEITHER ten, eight NOR six!")
Next lesson: Functions/Methods in Python Previous lesson: Ranges and For Loops in Python