Python Tutorial‎ > ‎

Tutorial Five

This tutorial is for the Python IDLE (GUI) - Graphical User Interface
Click the images to enlarge them

Conditionals are used to do something if somethings condition is correct. In simple IF something = something THEN do something. In python, and most other programming languages, IF statements are used as the main conditionals. An example of this would be:
Output a message saying "How many legs to humans have?" 
Store the input as number
if number = 2 then output a message saying "Correct answer". 
Please note this is pseudo code (not actual python language).

Here is the python equivalent: 


number = 0
number = input("How many legs do humans have?")
if number == "2":
    print ("Correct")

Notice how it is structured-  if [variable name] == [value or variable name]: 
-The if must be lower case.
-If checking a variable has a static value use two equal symbols "==".
-After the end of the value or second variable name a colon is required.
Try inserting a colon into the Python IDLE then press enter, notice how the next line is indented.
Anything you want to happen when the if statement returns true MUST BE INDENTED.
As soon as you remove the indent that part of the program will be run regardless of the return of the if statement.

Instead of using two equal symbols "==", using a greater than symbol (>) will return true for any value over 2, using a less than symbol (<) will return true for any value less than 2.
< Less than,     <= Less than or equal to,     > Greater than,     >= Greater than or equal to,     != OR <> Not equal to,     == Equal to. 
Any of the above can be used in conditionals to check for values.

We can extend our program above by adding an else. else's are used to check other values in the if statement. Think of it like a otherwise:
 If something = something Then output "correct" otherwise(else) output "incorrect".
"Elseif" statements in python are written as elif and work the same as if statements and will only be checked of the if statement before it was false.
"Else" statements in python are written as else and true if the if statement was false.

So lets modify our program to output a message saying "incorrect" if the user doesn't enter 2.

Conditionals Program

number = 0
number = input("How many legs do humans have?")
if number == "2":
    print ("Correct")
    print ("Incorrect")

Now if the user enters any number that is not 2 then it will output "Incorrect" if they enter  2 it will output "Correct".
Now try and see if you can change the program to output "Too high" if you enter a number greater than 2 and "Too low" if you enter a number less than 2.

Notice how the program has to be re-run every time you want to try a new value, in the next tutorial we will fix this by using a loop.