Python Wiki
Advertisement

An if statement is a type of statement in Python.

Usage[]

An if statement can be used to input a certain block of code that will only be executed if, and only if a certain condition is met or evaluates to True.

Structure[]

if some_condition:
   some_expression

Elif Statements[]

Elif statements, determined by the keyword "elif", work exactly the same way as if statements. Elif statements are used in the case of there being multiple possible conditions, and different results that can be obtained from each condition, or if the specified condition before the elif statement isn't met.

Structure[]

The structure for creating elif statements is practically the same as that with if statements. However, elif statements start with the "elif" keyword, and there also must be an if statement preceding the elif statement (as that was the whole reason for assigning elif statements in the first place), or the program will raise an error.

if some_condition:
   some_expression 
 
elif another_condition:
   different_expression

Syntax[]

if foo == 5: #Sees if foo is equal to five
    print("Foo is equal to five!") #If foo is equal to five it prints this
elif foo < 5: #If foo is not equal to five it checks to see if it is less than five
    print("Foo is less than five!") #If foo is less than five it prints
else: #If foo is not equal to five or less than five it automatically prints
    print("Foo is greater than five")
Advertisement