Flow Control in Python – Explore Conditional Programming, Python Loops and Statements
By Varun Dwarki
Python programming language normally executes the instructions one after the another, until you say otherwise. However, the real strength of programming isn’t just for the programs to start from the first line of code and simply execute every line, straight till the end. A program should be able to skip over a few instructions, return to them at some other point in time, repeat them, or simply choose one of several instructions to run. We call this flow control in Python (or alternatively, control flow), Python’s path through a program.
In order to control the flow of a program, Python provides various flow control statements, which we are going to learn in this article. The topics covered in this article are:
- Conditional Programming
- if Statement
- if…else and if…elif…else Statements
- Python Loops
- while Loop
- for Loop
- The break and continue Statements
- The pass Statement
- Conclusion
The control flow statements in Python can mainly be divided into two categories: conditional programming (often referred to as branching), and looping.
Conditional Programming
Conditional programming is something that you do every day, every moment of your life. It’s basically decision-making and evaluating conditions: If I going to be late for work today, then I will inform my manager, and if it is raining today, then I should take my umbrella.
Similarly, Python has several built-in keywords that provide programs with the ability to execute different instructions under different conditions. Flow control statements often start with a condition, which evaluates to a Boolean value True or False, by blocks of code. Now let’s explore the most important part, the flow control statements themselves.
if Statement
if statement is one the most basic and well-known control flow statement types. It checks the condition, evaluates the block of code that flows if the condition is True, or skips the action if the condition is False.
#Example 1
climate_nice = True if climate_nice: print("I will go for a stroll")
Here, the variable climate_nice is fed as a conditional expression to the if statement. Since the result of the evaluation is True, the control enters the block of code immediately after the if statement. Also, note that the print instruction is indented, which means that it belongs within the scope of the if statement.
if…else and if…elif…else Statements
Now, what if you want to specify a particular action when the condition evaluates to False, instead of doing nothing? Or may be specify more conditions? Simple, for that purpose we have if…else and if…elif…else statements.
Example 2: Given a word, determine if you have to article ‘a’ or ‘an’ before the word.
#Example 2
word = 'evening stroll' if (word[0].lower() in 'aeiou'): print("an", word) else: print('a', word)
You can also rewrite the above program using conditional expression as shown below:
#Example 3
word = 'evening stroll' result = ("an " + word if (word[0].lower() in 'aeiou') else 'a '+ word) result
In the above expression parenthesis are optional, they are just used for better comprehension of the code. Similarly, you can test for many case using if..elif..else statement as shown below:
#Example 4
x = 10; y = 15; z = int(input("Please enter an integer: ")) if z < 0: print(z, "is a negative number") elif z > 10 and z < y: print(z, "is positive integer and lies bewteen x and y") elif z == x: print(z, "is euqal to x") elif z == y: print(z, "is euqal to y") else: print(z, "is greater than both x and y")
Note that the else statement is optional and there can be zero or more elif statements. As you can in the above example, if you want to make multiple comparisons at the same time, you can use Boolean expressions along with and, not, also or to determine the final Boolean result.
Let us now move on to loop statements.
Best-suited Python for data science courses for you
Learn Python for data science with these high-rated online courses
Loops
Loops are important and one of the most basic concepts in any programming language. Looping basically means being able to repeat the execution of a certain portion of code more than once (known as iterations), based on loop parameters. Python offers two main looping constructs that serve different purposes: for and while statements.
Popular Python Course Providers:
Top Python Courses by Udemy | Popular Python Courses by Coursera |
Top Python Courses by Udacity | Popular Python Courses by PluralSight |
while Loops
Python’s while statement is the simplest and the most basic iteration mechanism. It repeatedly executes a block of statements (usually indented) as long as the condition evaluates to True. When the test condition becomes False, the control moves to the statement that follows the while block. In case the test condition evaluates to False, to begin with, the body of the loop never runs and the while statement will be entirely skipped. Here’s a simple example:
Example 5: Let’s use a while statement to create a program that will demonstrate the countdown. So, the moment the count is 0, you should print a message “Happy New Year”.
# Example 5
def countdown(m): while m > 0: print(m) m = m - 1 print("Happy New Year!!") countdown(5)
As you can see the code is as simple as plain English. Given a number m, while the number m is greater than 0, display the number m, and then reduce the number by 1. Do the same until m is greater than 0. When you get to 0, display the message “Happy New Year”. Let’ us consider another simple example.
Example 6: Write a program that will calculate the binary representation of a given number. Use a while statement.
# Example 6
z = int(input("Please enter an integer: ")) binary = [ ] #this will store the binary representation of the number while z > 0: remainder = z % 2 #reminder after division by 2 binary.append(remainder) #keeps track of the reminders z //= 2 #dividing by two print("The wroge order", binary) binary = binary[::-1] #reversing the order of remainders print("The binary representation of", z ,"is", binary)
I will leave it to you to analyze the example. Meanwhile, let us now move to the next looping construct for the statement.
for Loops
The for the statement in Python is slightly different from what you are used to from other languages such as C, and others. Unlike in C language, where you mention both the iteration step and the halting condition, Python’s for statement can step through the items of any sequence (or other built-in iterables), in the order, they appear in the sequence. Here’s a simple example:
#Example 7
pet = "hamster" for char in pet: print(char)
Here, the sequence we have provides an id string. When Python runs the for loop, it assigns each item (or character) of the string to the target char one by one and then executes the loop body for each, until no characters are left. Let us consider another simple example:
Example 8: Write a program that will iterate through two given sequences of the same length and print respective elements from two sequences in pairs.
# Example 8
pets = ['cats', 'dogs', 'fishes', 'rabbits', 'hamsters', 'parrots', 'ferrets'] priority = [1, 3, 2, 4, 6, 7, 5] for position, fav_pet in enumerate(pets): priority_value = priority[position] print(fav_pet, priority_value)
While this is all great, at times you would want to change the regular flow of a loop. For example, skip an iteration (as many times as you want) or break out of the loop, when you have acquired the results that satisfy your requirement. To handle such situations, Python offers a break and continue statements.
The break and continue Statements
The break and continue statements alter the control flow of the loop. The break statement simply allows you to exit the loop. Remember that break and continue only operate on a single level of the loop. In the case of nested loops, the break keyword-only terminates the loop where it is located. If the break is present in the innermost loop, it will only terminate the innermost for loop; any outer loop will continue to run.
Example 9: Write a program that computes an average. The program should keep asking the user to enter a number until the user types “done”. When the input is “done”, the program should then display the average of all the given numbers. Make use of control flow statements and break.
#Example 9
sum = 0 counter = 0 while (True): input_value = input('Enter a number: ') if input_value == 'done': break value = float(input_value) sum = sum + value #keeps track of the total sum counter = counter + 1 #keeps the count of number of inputs entered average = sum / counter print('Average:', average)
The above example clearly illustrates the functionality of the break statement. When the input provided by the user is ‘done’, the control breaks out of the while loop and the statement after the while loop is executed. Sometimes, instead of jumping out of the loop, you might just want to skip the current iteration and move on to the next iteration. In such cases, the continue statement comes into the picture. Here’s a simple example:
Example 10: Write a program that will accept an integer input from the user, and prints the square of the number if the number is even, and if the number is odd, prints the message “num is odd. Enter even number”. Also, when the program should stop prompting for input if the user inputs the letter ‘q’ or ‘Q’.
#Example 10
while True: input_value = input("Integer, please [q (or Q) to quit]: ") if input_value == 'q' or input_value == 'Q': # quit break number = int(input_value) if number % 2 == 0: # an even number print(number, "squared is", number*number) continue print(number, "is odd. Enter even number")
Now, let us explore a few other interesting Python control flow relates statements.
The pass Statement
The pass Statement basically does nothing. It is a no-operation placeholder that can be used when you need a statement syntactically but no action needs to be taken, or if you need a placeholder for code that’s not yet implemented. For example,
#Example 11
a = 0 if a < 0: print('negative!') elif a == 0: # TODO: put something here pass else: print('positive!')
Conclusion
That’s it! With this, we have reached the end of the article. Flow control statements in Python are very important code structures that weave data into meaningful programs. You should have a strong grip on them and more importantly, you should be able to figure which control flow statements will give the best results based on your requirement.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio