Tech With Tim Logo
Go back

IF/ELIF/ELSE

The If Statement

The if statement is the most basic form of logic within python. It simply checks if something is the case, and if it is, it executes what is within the proceeding block of code. The basic syntax for an if statement can be seen below.

if 4 < 5:
    print("true")

Breaking down the syntax: we start with the keyword "if", then a condition followed by a colon (:). The following lines that are indented are what will run if the condition evaluates to True.

The Importance of Indentation

Unlike many other languages python does not use braces or brackets to enclose blocks of code, it uses indentation. That is why it is extremely important to be mindful of your codes spacing and indentation. The example below illustrates this.

number = int(input("Please type a number: "))
if number < 5:
    print("the number is less than 5")
print("I always run")

# If the number is less than 5 both print statements will execute. 
# Otherwise just "I always run" will be printed to the screen

The Else Statement

The else statement is something that can be added after an if statement. It will only run if the if statement above it did not execute. In other words, if the condition is not met (it is False) what is inside the else statement will run.

number = int(input("Please type a number: "))
if number < 5:
    print("the number is less than 5")
else:
    print("the number is NOT less than 5")

Note: The indentation is still important. Notice that the else is in-line with the if statement above it.

The Elif Statement

The elif statement allows us to check multiple conditions. It must come after an if statement and before a possible else (see examples). Is it valid to have multiple elif statements proceeding one another. When using an elif it is not necessary to have an else afterwards, it is simply optional.

number = int(input("Please type a number: "))

if number < 5:
    print("the number is less than 5")
elif number < 10:
    print("the number is greater than or 5 and less than 10")
elif number < 15:
    print("the number is greater than or 10 and less than 15")
else:
    print("the number is NOT less than 15")


if number == 10:
    print("The number is 10")
elif number == 15:
    print("The number is 15")

# Notice it is not necessary to include an else

The conditions checked in the elif will only be checked if the ones before them were False. This means that if for this example the number was less than 5 the program will only print "the number is less than 5". It will not check the elif conditions even though they may evaluate to True. If you are having trouble understanding please watch the video above.

Design & Development by Ibezio Logo