But don’t freak out, because with this tutorial, you’ll be able to navigate through those tangled lines of code and come out victorious!
To begin with: what are compound statements? Well, they’re basically multiple statements grouped together under one umbrella like a big ol’ family reunion for your code. And just like at a family gathering, you might need to bring some snacks or drinks to keep everyone happy and fed. In this case, those snacks are the individual statements that make up our compound statement.
So let’s say we want to print out “Hello world!” if it’s raining outside, but only if it’s also after 5pm. Here’s what our code might look like:
# This script checks if it's raining outside and if it's after 5pm, and prints a corresponding message.
# First, we define the variables rain and time.
rain = True # This variable represents whether it's raining or not.
time = 18 # This variable represents the current time in 24-hour format.
# Next, we use an if statement to check if both conditions are met.
if rain and time > 17: # The 'and' operator ensures that both conditions must be true for the code to execute.
print("It's raining and past 5pm!") # If both conditions are met, this message will be printed.
else:
print("Sorry, no rain for you.") # If either condition is not met, this message will be printed.
Now that looks pretty straightforward. But what if we want to do something more complex? Let’s say we have a list of numbers and we only want to add them up if they’re greater than 10. Here’s where our compound statement comes in:
# This script calculates the sum of numbers in a list that are greater than 10.
# Initialize a variable to store the total sum
total = 0
# Loop through each number in the list
for num in my_list:
# Check if the number is greater than 10
if num > 10:
# If it is, add it to the total sum
total += num
# Print the final result
print(f"The sum of numbers over 10 is {total}.")
Notice how we’ve nested an “if” statement inside a “for” loop. This allows us to perform multiple operations within our compound statement, making it more powerful and versatile than just using simple statements on their own.
But be careful! Compound statements can get pretty messy if you’re not careful with your indentation. Remember that each line within the basic block must be indented by the same amount otherwise Python won’t know which statement belongs to which compound statement. And always make sure to include a blank line at the end of your code to indicate completion!
Just remember to keep those snacks coming and don’t forget to clean up after yourself when you’re done!