Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 3 - Control Flow

3.1 Conditional Statements

Control statements in Python help your program make decisions based on conditions using if, elif, and else blocks.

Conditional Operators:

Conditional operators allow you to compare values in Python:

OperatorDescriptionExample
==Equal tox == y
!=Not equal tox != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y
inReturns True if value is present in sequencex in sequence
not inReturns True if value is not present in sequencex not in sequence

Example using if, elif, and else:

x = 10
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

In this example:

  • x > 0 checks if x is greater than 0.
  • x == 0 checks if x is exactly equal to 0.
  • else covers any other case where x is negative.

Logical Operators:

Logical operators (and, or, not) allow you to combine multiple conditions:

OperatorDescriptionExample
andReturns True if both operands are truex and y
orReturns True if either operand is truex or y
notReturns True if operand is falsenot x

Example using Logical Operators:

x = 10
y = 10
if x == 10 and y == 10:
    print("Both x and y are equal to 10.")
elif x == 10 or y == 10:
    print("Either x or y equals 10.")
else:
    print("None of them equals 10.")

In this example:

  • x == 10 and y == 10 checks if both x and y are equal to 10.
  • x == 10 or y == 10 checks if either x or y (or both) equals 10.
  • else covers any other cases where neither x nor y equals 10.

Try modifying the values of x and y in the examples above to see how the conditions and logical operators behave.