Conditionals provide the ability to execute specific code blocks based on whether a given condition is true or false. In this article, I will explain the various types of conditionals in Python and how to use them effectively to write clean, efficient, and flexible code.
In Python conditionals, indentation defines the blocks of code that belong to the
The
The syntax for an
For example, to check if a number is positive:
The
if condition:
# code to execute if the condition is true
else:
# code to execute if the condition is false
For example, to check if a number is even or odd:
number = 6
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
The
The syntax is as follows:
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if none of the conditions are true
For example, to categorize a numeric grade:
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("F")
You can also create nested conditionals by placing one
For example, to determine the quadrant of a point in a Cartesian coordinate system:
x, y = 5, -2
if x > 0:
if y > 0:
print("Quadrant I")
else:
print("Quadrant IV")
else:
if y > 0:
print("Quadrant II")
else:
print("Quadrant III")
A conditional expression, also known as a ternary operator, is a concise way of writing a simple
The syntax is as follows:
For example, to assign the absolute value of a number:
Here are some sample problems solved with Python conditionals.
a = 15
b = 8
c = 12
if a > b:
if a > c:
largest = a
else:
largest = c
else:
if b > c:
largest = b
else:
largest = c
print(f"The largest number is : {largest}")
numbers = [1, 3, 5, 10, 12, 15, 19, 22, 20, 24]
for number in numbers:
result = ""
if number % 3 == 0:
result = "fizz"
if number % 5 == 0:
result += "buzz"
if result == "":
result = number
print(result)
Determine if a given year is a leap year or not. A leap year is divisible by 4, but if it is divisible by 100, it must also be divisible by 400.
year = 2000
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
else:
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
Determine the winner of a game of Rock, Paper, Scissors, given the choices of two players.
player1 = "scissors"
player2 = "paper"
if player1 == player2:
print("Its a tie")
else:
if player1 == "rock":
if player2 == "scissors":
print("Player 1 wins")
else:
print("Plater 2 wins")
elif player1 == "paper":
if player2 == "rock":
print("Player 1 wins")
else:
print("Player 2 wins")
elif player1 == "scissors":
if player2 == "paper":
print("Player 1 wins")
else:
print("Player 2 wins")
Classify a triangle as equilateral, isosceles, or scalene, given the lengths of its sides.