if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for
loops iterate over items in a sequence:
for i in range(5):
print(i)
while x < 10:
print(x)
x += 1
Yes, using a conditional expression:
x = 5
print("Positive") if x > 0 else print("Non-positive")
for index, value in enumerate(my_list):
print(index, value)
for key, value in my_dict.items():
print(key, value)
Yes, the else
block executes if the loop completes without hitting break
:
for x in range(5):
if x == 10:
break
else:
print("Completed without break")
Use while
when you don’t know how many iterations you need—only the stopping condition.
while True:
print("Looping forever")
break # Use break to exit