Introduction
"Imagine having the power to direct the flow of a program. Control statements in Python grant you that authority, enabling you to orchestrate actions, decisions, and iterations within your code."๐ช
"Get ready to unravel the mystery of Python's control statements! By the end of this article, you'll master these terms and gain a comprehensive understanding of control structures, not just in Python but across programming languages. Stick around for an insightful journey into the heart of programming control."๐
What are control structures?
control structures are blocks of code that dictate the flow of a program and how a program executes. For example, From choosing what to wear based on the weather, Control structures mirror these choices, allowing your code to adapt and respond intelligently to different situations. In programming, we must make decisions and execute the blocks of code according to that decision.
Understanding control structures is fundamental in programming, a vital skill that every programmer needs to master. These structures dictate the logic and flow of code, enabling developers to make decisions, iterate through tasks, and create dynamic programs that respond differently to situations. Proficiency in control structures lays the groundwork for crafting efficient, functional code across various programming languages.
There are 3 types of control structures in python
Sequential structure
Selection/Decision structure
Repetition structure (iteration)
And we will be going over all these terms so you can have a better understanding of what they mean and how we can apply them to our code
Sequential structure
The sequential structure in Python represents the default flow of instructions, where commands are executed one after another in the order they appear within the code. It's the simplest form of control structures, The execution of these code structures follows a linear path from the first line of the code down to the last line of the code.
#This is a sequential structure
#Sequential execution for mathematical operation
a = 3
b = 5
c = a + b
print(c)
#Result is the addition of the variable a and b which equal 8
This example demonstrates how Python executes code line by line, following a sequential structure where print(c)
execution relies on the results of the previous variables defined above.
Because of the linear nature of the sequential structure, it offers clarity in the execution of the code and easy comprehension of such blocks of code. Unlike other control structures, it does not involve decision-making from different conditions or iterations of code but it forms the foundation on which these complex programming structures are built.
Selection structure
The selection structure models the example I gave at the beginning of this article on how people decide on what to wear based on the given weather, where if the weather is sunny, you put on sunscreen and a hat, If it's rainy, you put on an umbrella and coat. That is a brief overview of how the selection structure works in a real-life scenario. Now let's bring this back to programming
In Python, The selection statement is also referred to as a decision control statement or branching statement and we have 4 types of selection structure
if statements
if-else statement
nested if statements
if-elif-else statement
if statements- The if statement is a fundamental control structure used to perform conditional execution based on a specified condition. An if statement only has one condition to check. If the condition is True, the code block immediately following the if statement is executed. It runs the code only if that condition is met.
In the following code, the name variable would only be printed if you pass the value 'David' to it
#if statements only check for one condition
name = input("what is your name? ")
if name == 'David':
print(name)
If-else: The if-else statement evaluates the condition to either True or False and executes according to the condition. This introduces dynamism to our programs by adding flexibility and decision-making capabilities based on different scenarios
The following block of code will execute as True if you input the name to be David and False if you input any other name
#if-else statement performs evaluation for either True or False
name = input("what is your name? ")
if name == 'David':
print("Welcome" +" "+name)
else:
print("Wrong name")
nested-if: Nested if statements are an if statement inside another if-statement
In the following code, we check if the length of the name is greater than 0 and also check again if it is between a range of less than or equal to 10. With this, we can set multiple branch points in our code to handle different conditions.
# Nested if statement to check name
name = input("Enter your name: ")
# Checking length of the name
if len(name) > 0:
# If the username is not empty, check its length
if len(name) <= 10:
print("username accepted")
else :
print("username is too long")
else:
print("username cannot be empty")
if-elif-else statements: The if-elif-else statement is used to conditionally execute a statement or block of statements. You can include multiple elif blocks to check for additional conditions. The else block, if used, is executed only if none of the preceding conditions are met
The following code will evaluate the elif block as True because it checks the if condition, doesn't match and it goes on to check the elif condition and it matches and then, the program will print "I'll need a hat"
weather = 'hot'
if weather == 'cold':
print("I'll need an umbrella and a raincoat")
elif weather == 'hot':
print("I'll need a hat")
else:
print("I am not sure about the weather")
Repetition Structure(iteration)
In Python, A repetition structure is used to repeat a block of code until some conditions listed within the loop evaluate to true or have been satisfied.
In some cases, we have loops that would run forever without any of its terminating evaluating to true. These are known as infinite loops
There are two types of loop
For loop
While loop
For loops :
For loops are mostly used to iterate through objects like lists, tuples and dictionaries. For example, If we want to iterate through each value in a list and print a simple message along with that value, For loops can help us achieve that with just a few lines of code
users= ['Dave','Robert','Sandra','Mary']
for user in users:
print("How are you feeling today "+ user)
You can see how for loops make it so much easier with just three lines of code to loop through and print the attached message to all the names
While loops :
While loops are used to iterate repeatedly for as long as a condition is true. They are mostly useful when you want a program to run until a certain condition is no longer met.
we can also use while loops to set a condition to print a certain range of numbers, but in this case, we would set a starting point, counter and then the condition to achieve it
#This would print the word candy 5 times
i = 1
while i <= 5:
print("Hello")
i+=1
It is also worth knowing that improper use of the while loops can lead to infinite loops so we should check thoroughly for our conditions and counters
Conclusions:
So we have discussed extensively on control structures and their usage in Python. Combining all these in our program would give us the power to handle the flow of our program generally.
if you like this article, pls do well to leave a like, I also appreciate any feedback as it would help me grow๐น and refine the content I share๐