Python 3 — Making Decisions with Conditionals
Conditionals allow your code to make decisions. Without them, your code is just a simple recipe. By checking conditions, your program can choose to run specific code blocks while completely skipping others.
Before making a decision, you must compare values. Python returns a Boolean value (True or False) after evaluations:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 (True) |
!= | Not equal to | 5 != 3 (True) |
> / < | Greater/Less than | 10 > 12 (False) |
>= / <= | Greater/Less or equal | 10 >= 10 (True) |
Python checks the conditions sequentially. The moment it finds a condition that evaluates to True, it runs that block of code and skips the rest:
temperature = 28
if temperature > 30:
print("It is extremely hot outside!")
elif temperature >= 20:
print("The weather is warm and nice.")
else:
print("It is cold outside.")
Notice the colons (:) at the end of each condition, and the indentation before the print functions. In Python, **indentation is mandatory** and defines which code belongs to which block.
You can check multiple conditions at the same time using logical operators:
and: ReturnsTrueonly if **both** conditions are true.or: ReturnsTrueif **at least one** condition is true.not: Inverts the condition (turns true to false, and vice-versa).
has_licence = True
age = 19
if age >= 18 and has_licence:
print("You are cleared to drive!")
else:
print("You cannot drive.")
In Python, failing to indent or mixing tabs with spaces causes an IndentationError. Always use 4 spaces for your indents. Our Compiler handles this formatting for you automatically when you press tab!
Write a grading program: declare a variable called 'score'. If the score is 90 or more, print "Grade A". If it is 80 or more, print "Grade B". If 70 or more, print "Grade C". Otherwise, print "Grade F".