Python Control Flow

Greetings once more, budding Python mage! Last we spoke, we learned how to write some basic incantations in the Pythonic tongue, but that was just the beginning.

Now we venture deeper into the realm of Python, exploring the powerful spells that can control the flow of our code!

Conditional Statements

First, let's explore conditional statements. Think of them as magical barriers that only allow certain code to execute when the conditions are just right.

In Python, these barriers take the form of if, elif, and else.

if evaluates an expression. If the result is True, the code within this block is executed.

weather = "rainy"

if weather == "rainy":
    print("Better bring an umbrella!")

elif stands for "else if". It's used when you want to check for more conditions after the if.

weather = "sunny"

if weather == "rainy":
    print("Better bring an umbrella!")
elif weather == "sunny":
    print("Don't forget your sunglasses!")

else is used when you want some code to be executed if all the if and elif conditions are not met.

weather = "snowy"

if weather == "rainy":
    print("Better bring an umbrella!")
elif weather == "sunny":
    print("Don't forget your sunglasses!")
else:
    print("Looks like a good day to stay indoors and code!")

Looping Statements

Looping statements are our way of casting the same spell multiple times without needing to rewrite the code.

for is used for iterating over a sequence (like a list, tuple, or string) or an iterable object.

for i in range(5):
    print("Alohomora", i)

while is used to execute a block of code as long as the condition is true.

i = 0
while i < 5:
    print("Expelliarmus", i)
    i += 1

Control Statements

Control statements are our secret tricks to control the flow of loops. They're like magical shortcuts!

break is used to exit the loop prematurely when a certain condition is met.

for i in range(5):
    if i == 3:
        break
    print("Lumos", i)

continue is used to skip the current iteration and continue with the next.

for i in range(5):
    if i == 3:
        continue
    print("Nox", i)

pass is like a placeholder when the syntax requires a block of code, but you don't want to do anything yet.

for i in range(5):
    pass  # I'll do something with this later.

You've now learned some powerful spells to control your Python code. Practice these new tools at your disposal and soon you'll be casting complex incantations with ease. Happy coding, Python wizard!

Previous Next

Written © 2024 Written Developer Tutorials and Posts.

𝕏