Conditional Statements¶
We can use conditional statements to control how or if portions of our code will execute, based on logical criteria that we provide. The most basic type of conditional statement is an if statement. The syntax for an if statement is as follows:
if condition: code to be executed if condition is true
grade = 34
if grade >= 60:
print('You passed the exam.')
print('Congratulations!')
If-Else Statements¶
We can use an if statemnt to determine whether or not a particular set of actions will be satisfied. But we will occasionally want to use a condition to determine which of two sets of actions will be completed. This functionality is provided to us by an if-else statement. The syntax for an if-else statement is as follows:
if condition: code to be executed if condition is true else: code to be executed if condition is false
grade = 34
if grade >= 60:
print("You passed the exam.")
print("Congratulations!")
else:
print("You failed the exam.")
print("Better luck next time.")
You failed the exam.
Better luck next time.
If-Elif-Else Statements¶
If statements allow us to determine whether or not a single set of actions will be taken, and if-else statments allow us to determine which of two sets of actions will be taken. If we require our program to select from more than two options when making a decision, we can use an if-elif-else statment. The syntax for this sort of statement is as follows:
if condition1: code to be executed if condition is true elif condition2: code to be executed if condition1 is false, but condition2 is true elif condition3: code to be executed if all above conditions are false, but condition3 is true elif condition4: code to be executed if all above conditions are false, but condition4 is true ... else: code to be executed if all above conditions are false.
We can include as many conditions as we would like in an if-elif-else statement. However, It is important to note that only one portion of the code will be allowed to execute. It is possible that multiple conditions might potentially evaluate to True
, but as soon as the if-elif-else statement encounters its first True
condition, it will execute the code for that condition, and will then skip the rest of the statment.
The example below provides an example with a single elif
clause.
grade = 85
if grade >= 90:
print("You got an 'A' on the exam.")
elif grade >= 80:
print("You got a 'B' on the exam.")
elif grade >= 70:
print("You got a 'C' on the exam.")
elif grade >= 60:
print("You got a 'D' on the exam.")
else:
print("You got an 'F' on the exam.")
You got a 'B' on the exam.