Python — Control Flow
Introduction to Python — Lists and Dictionaries
Congratulation 🎉 🎉 🎉 Today we will discuss about Lists and Dictionaries in Python. If you haven’t read variables…
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 😁
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.
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:
How do we evaluate some conditions? We can use elif statement 🎉 🎉 🎉
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).
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 🎉
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.
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.
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.