Control Flow
If/Else
If/else statements in python are pretty straightforward and similar to other languages. elif
is used instead of else if, and there are no parenthesis when stating the conditions.
python
num = 3
if num == 1:
print("1")
elif num == 2:
print("2")
else:
print("Other")
For loops
For loops can iterate over lots of data structures. Range is exclusive of the end, and inclusive of the beginning.
python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
for x in range(6):
print(x) # Prints 0-5
for x in range(2,6):
print(x) # Prints 2-5
You can also use an else block after the for loop to run some code after the loop has finished. However, if the for loop is escaped with break
, it won't run.
python
for x in range(6):
print(x)
else:
print("I will be shown!")
for x in range(6):
if x == 3: break
print(x)
else:
print("I will not be shown :(")
While loops
Very similar to for loops in syntax and behavior. Can also include else statements to run after the loop concludes.
python
i = 1
while i < 6:
print(i)
i += 1
else:
print("Finished")
Match
New in Python 3.10, you can now perform match statements in python.
python
num = 1
match num:
case 1:
print("1")
case 2:
print("2")
case _:
print("other")