Python — Control Flow

Hi, this is my 4th post about the Python programming language. If you want to read the previous topic, you can click the link below 😁

Overview

In this post, we will learn about Control Flow in Python. Control Flow is ordered function calls, instructions, and statements are executed or evaluated. Every programming language has its own form of control flow which determines what section of code is run in a program at any time.

if Statement

For example, we want to print “Hi” when we type y and print “Hello” when we type anything other than y in our Python interpreter. The following code represents the above problem in Python:

the code above will print “Hi” when the value of the letter is “y”

How do we evaluate some conditions? We can use elif statement 🎉 🎉 🎉

the code above evaluate the value of z variable

Based on the code above, we are declaring a variable named z which takes input and converts it to an integer value. Then we evaluate the value of z with some conditions. If z has a value less than zero (line 5), the program print “Negative number”. The next condition is if z has a value equals to zero (line 7), the program prints “Zero”. Followed by the next conditions (lines 9 and 11).

We use comparison operators in the if statement as needed. More about operators will be explained in the next post.

for Statement

In certain cases, we need to call a function or execute any statement without having to write too long code. For example, I have a list named persons_name that contains 5 person’s names. I need to print the names without writing code over and over. What solution can be taken for this case? for Statement is the solution 🎉

iterate persons_name list values

If you want to execute any statement over a sequence of numbers, you can use a built-in function named range()

range() has three parameters named start, stop, and step. This function returns a sequence with zero as the first element (by default). We can customize with custom start, stop, and step values to generate a custom sequence of numbers.

break Statement

Python provides break statement like C language. It used to terminate from for and while loop. Loop statements may have an else clause. It is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. The following example is a program to find the prime number from 2 to 10.

break statement in line 5

continue Statement

Python also provides continue statement. This statement is used to continue the next iteration of the loop. For example, the following codes use for finding even and odd numbers.

continue statement in line 4

Next post:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store