FAQ Part 4: Control Structures (if, for, while)

How do I write an if-else statement in Python?

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

How do for loops work in Python?

for loops iterate over items in a sequence:

for i in range(5):
    print(i)

How do while loops work?

while x < 10:
    print(x)
    x += 1

Can I write an if statement in one line?

Yes, using a conditional expression:

x = 5
print("Positive") if x > 0 else print("Non-positive")

How do I loop through a list with indices?

for index, value in enumerate(my_list):
    print(index, value)

How do I iterate over a dictionary?

for key, value in my_dict.items():
    print(key, value)

Can I use else with a for loop?

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")

When should I use a while loop instead of a for loop?

Use while when you don’t know how many iterations you need—only the stopping condition.

How do I create an infinite loop?

while True:
    print("Looping forever")
    break  # Use break to exit