Control Structures

Loops

The for loop is used to iterate over a sequence, such as an array or a range of numbers:

for i in range(5):
    print(i) # Prints 0, 1, 2, 3, 4

for item in my_array:
    print(item) # Prints each item in my_array

The while loop is used to repeatedly execute a block of code as long as a certain condition is true:

var i = 0
while i < 5:
    print(i) # Prints 0, 1, 2, 3, 4
    i += 1

The break statement is used to exit a loop prematurely:

for i in range(10):
    if i == 5:
        break
    print(i) # Prints 0, 1, 2, 3, 4

The continue statement is used to skip the rest of the current iteration and proceed to the next one:

for i in range(5):
    if i == 2:
        continue
    print(i) # Prints 0, 1, 3, 4

Conditional statements

The if statement is used to execute a block of code if a certain condition is true:

if x > 0:
    print("x is positive")

The else statement is used to execute a block of code if the condition in the if statement is false:

if x > 0:
    print("x is positive")
else:
    print("x is not positive")

The elif (short for "else if") statement is used to test multiple conditions in a single if statement:

if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")
Comments