To create a conditional statement in Python, you simply use the keyword "if".
computers = ['hp', 'toshiba', 'dell', 'lenovo']
for computer in computers:
# Conditional statement checking for the string 'hp'.
if computer == 'hp'
print(computer.upper())
else
print(computer.title())
HP
Toshiba
Dell
Lenovo
True or False
# Use the assignment operator to store the string 'hp' in the variable 'computer'
computer = 'HP'
# Comparison between 'HP' and 'hp'
print(computer == 'hp')
# Comparison between 'hp' and 'hp'
print(computer.lower() == 'hp')
False
True
!True = False and
!False = True.!= to
denote "not equal to".
my_computer = 'dell'
# Check if the computer is not an HP
if my_computer != 'hp':
print("My computer is not an HP")
else:
print("You have an HP computer!")
My computer is not an HP
Numerical comparisons are pretty straightforward since we do not have to check the case on them
num = 45
# Check for equality
print(num == 45)
# Check for inequality
print(num != 45)
# Check if the number is less than 20
print( num < 20)
# Check if the number is greater than 40
print(num > 40)
True
False
False
True
Sometimes we would like to check if two or more conditions are simultaneously true with the and logical operator. Here is a truth table that demonstrates that.
In its most simplest form the AND logical operator is only true when BOTH conditions are true.
| P | Q | P AND Q |
|---|---|---|
| T | F | F |
| F | T | F |
| F | F | F |
| T | T | T |
Here is a small program that demonstrates how to use the
AND conditional statement in Python which conveniently has
the keyword and.
car_1 = 'mazda'
car_2 = 'honda'
# The AND operator evaluates to FALSE since one of the cars is a Mazda
if car_1 == 'honda' and car_2 == 'honda':
print('Both cars are Hondas!')
else:
print('One of the cars is not a Honda!')
One of the cars is not a Honda!
Another type of logical operator is the OR operator. In short, the OR logical operator is only false when both statements are false; otherwise it is true.
| P | Q | P OR Q |
|---|---|---|
| T | F | T |
| F | T | T |
| T | T | T |
| F | F | F |
computers = ['toshiba', 'thinkpad', 'lenovo', 'hp', 'alienware', 'dell']
for computer in computers:
if computer == 'thinkpad' or computer == 'alienware':
print(f'A {computer} is a very nice computer!')
else:
print(f'The {computer} is a great computer!')
print('We love computers!')
The toshiba is a great computer!
A thinkpad is a very nice computer!
The lenovo is a great computer!
The HP is a great computer!
A alienware is a very nice computer!
The dell is a great computer!
We love computers!