Python – Syntax of If, For, While, Break, Continue

1. If Statement

if condition:
    # Code to execute if the condition is True
if 5 > 3:
    print("5 is greater than 3")

2. if-else Statement

if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the condition is False
if 3 > 5:
    print("3 is greater than 5")
else:
    print("3 is not greater than 5")

3. if-elif-else Statement

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if both conditions are False
x = 10
if x > 10:
    print("x is greater than 10")
elif x == 10:
    print("x is equal to 10")
else:
    print("x is less than 10")

4.for Loop

for variable in sequence:
    # Code to execute in each iteration
for i in range(5):
    print(i)

5.while Loop

while condition:
# Code to execute as long as the condition is True
i = 0
while i < 5:
    print(i)
    i += 1

6.break Statement

for/while variable in sequence/condition:
    if condition:
        break  # Exit the loop
for i in range(10):
    if i == 5:
        break
    print(i)

7. continue Statement

for/while variable in sequence/condition:
    if condition:
        continue  # Skip the rest of the code in this iteration
    # Code to execute if the condition is not met
for i in range(5):
    if i == 2:
        continue
    print(i)

8. else with Loops

for/while variable in sequence/condition:
    # Code to execute in each iteration
else:
    # Code to execute after the loop finishes
for i in range(3):
    print(i)
else:
    print("Loop finished!")

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *