use control statements in python

In Python, control statements are used to execute certain code blocks based on given conditions.

The if statement is used to execute a code block if a specified condition is true.

main.py
x = 5
if x > 0:
    print("x is positive")
43 chars
4 lines

The else statement is used to execute a code block if the same condition is false.

main.py
x = -5
if x > 0:
    print("x is positive")
else:
    print("x is negative")
77 chars
6 lines

The elif statement is used to specify additional conditions to check.

main.py
x = 0
if x > 0:
   print("x is positive")
elif x == 0:
   print("x is zero")
else:
   print("x is negative")
109 chars
8 lines

We can use logical operators like and, or, not to combine conditions.

main.py
x = 5
y = 10
if x > 0 and y > 0:
    print("Both x and y are positive")
elif x > 0 or y > 0:
    print("At least one of x and y is positive")
else:
    print("Both x and y are negative or zero")
195 chars
9 lines

Control statements like if, else, elif are essential for building complex logic in your Python programs.

gistlibby LogSnag