Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 6 - Exception Handling
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
Control statements in Python help your program make decisions based on conditions using if
, elif
, and else
blocks.
Conditional operators allow you to compare values in Python:
Operator | Description | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal to | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
in | Returns True if value is present in sequence | x in sequence |
not in | Returns True if value is not present in sequence | x not in sequence |
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 (and
, or
, not
) allow you to combine multiple conditions:
Operator | Description | Example |
---|---|---|
and | Returns True if both operands are true | x and y |
or | Returns True if either operand is true | x or y |
not | Returns True if operand is false | not x |
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.