Python If ... Else
January 17th 2020 529

Control Statements
Decision-making
Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions.
Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the outcome. You need to determine which action to take and which statements to execute if the outcome is TRUE or FALSE otherwise.
Python programming language provides the following types of decision-making statements.
if
if...else
elif
nested if
If statement
An if statement consists of a boolean expression followed by one or more statements.
Syntax:
if expression:
# statements
Example:
# if statement
x = 10
if x<100:
print("x is less than 100")
print("Good bye!")
#output
x is less than 100
Good bye!
If...Else
An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.
Syntax:
if expression:
# statements
else:
# statements
Example:
# if...else statements
x = 1011
if x<100:
print("x is less than 100")
else:
print("x is not less than 100")
print("Good bye!")
#Ouput
x is not less than 100
Good bye!
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". It is short form of "else if"
Syntax:
if expression:
# statements
elif expression:
# statements
else:
# statements
Example:
# elif statement
x = 100
if x<100:
print("x is less than 100")
elif x==100:
print("x is equal to 100")
else:
print("x is not less than 100")
print("Good bye!")
#Output
x is equal to 100
Good bye!
Nested if
if or else if statement can be used inside another if or else if statement(s).
Example:
# nested if statements
x = 10
if x<100:
if x<50:
print("x is less than 100 and less than 50")
elif x==100:
print("x is equal to 100")
else:
print("x is not less than 100")
print("Good bye!")
#Output
x is less than 100 and less than 50
Good bye!
Ternary Operators
Ternary operators evaluate something based on a condition being true or not. It is short Hand If
Syntax:
return_when_true if condition else return_when_false
#short hand if
height = 5.9
state = "tall" if height >= 6 else "short"
print(state)
result = 1 > 2
print("Greater Than" if result else "Less Than")
#Output
short
Less Than
The pass Statement
if
statements cannot be empty, but if you for some reason have an if
statement with no content, put in the pass
statement to avoid getting an error.
#pass example
a = 33
b = 20
if b > a:
pass
#Output
#you will get no output and no errors