If Statements - Conditional Flow


If statements allow the flow of a program to be control depending on predetermined conditions. If statements are common in most software languages and are essential for most programs.
If statement are created with an "if" followed by an expression that will return True or False. This is terminated with a colon (:). Care should be taken with the whitespace for an if statement as the subsections of code need to be indented.

Example 1

Here we have create a situation where a score is to be used tyo determine the correct output. Here we have created an if statement to check if the score is above or equal to 40. If this is correct then the following code that is indented will run. If not the else statement will run.
score = 55

if score >= 40:
    print ("student passed the test")
    print ("Student failed the test")
student passed the test

Example 2

Here we will build on the example above to include a range of grades to be returned.
score = 55

if score >= 90:
    print ("student passed the test, A")
elif score >= 80:
    print ("student passed the test, B")
elif score >= 70:
    print ("student passed the test, C")
elif score >= 60:
    print ("student passed the test, D")
elif score >= 50:
    print ("student passed the test, E")
elif score >= 40:
    print ("student passed the test, F")
    print ("Student failed the test")
student passed the test, E
Here we have used the elif, this is used to allow further logic tests to be performed.

Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.

Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines