If Statements
If Statements, or in SQA language, selections, allow decisions to be made inside of the code.
Conditions always end up being one of three formats.
Simple If Statements
Simple if statements check if something is true, and performs an action if it is true.
In the scenario below, a number is entered by the user, and if that number is greater than 5, the program displays “The number is larger than 5”.
number = int(input("Enter a number: "))
if number > 5:
print("The number is larger than 5")
If Else Statements
If Else Statements allow decisions to made if something is true or false.
In the scenario below, a number is entered by the user. If the number is greater than 5 the program prints out “The number is larger than 5”. If the number is not larger than 5, the program displays “The number is not larger than 5”.
number = int(input("Enter a number: "))
if number > 5:
print("The number is larger than 5")
else:
print("The number is not larger than 5")
Complex If Statements
Complex If Statements allow code to make multiple decisions. It can check for the first condition and if that is not true, it can check a second condition.
In the scenario below, a number is entered by the user. If the number is greater than 5 the program prints out “The number is larger than 5”. The program then checks if the number is less than 5. If it is, it prints out “The number is less than 5”. Finally, if we know its not greater than 5 or less than 5, we can display “The number IS 5.”
number = int(input("Enter a number: "))
if number > 5:
print("The number is larger than 5")
elif number < 5:
print("The number is not larger than 5")
else:
print("The number IS 5")