Python

Understanding the conditional Statement and Loop of python

From my last tutorial, we have a good basic understanding of python for example How to install to get started, how to declare the variables and what are the data types are available in python. I recommended checking the last tutorial for better understanding. Here are the links Introduction to python to get started, Variables declaration of python and Data types of python.

In this tutorial, we will learn the conditional and loop flow of python. Let’s get started to understand the basic concept of conditional and loops. Using conditional statements, we can write Python code that makes decisions and repeats actions.

1. If else and elif

The if… statement is used to evaluate whether a condition is True or False and, depending on the result. Suppose we want to write a program, that will determine whether a number is greater than other. In python every condition or loop it should end with colon :

x = 10
y = 20

if x > y:
    print(str(x)+ " is greater than " + str(y))  # Here we need to type cast int to string.
else:
    print(str(y) + " is greater than " + str(x))

Result: 20 is greater than 10

If we do not write or execute in else condition then we can use  pass . For example.

if x > y:
    print(x + " is greater than " +y) # Here we need to type cast int to string.
    # this line is not executing that why it is not giving error.
    # Otherwise it gives this error TypeError: unsupported operand type(s) for +: 'int' and 'str'
else: pass   # this will pass without any thing print

Now come to see another example to understand the elif condition.

x = 10
y = 20
z = 30

if x > y & x > z:
    print(str(x) + " is the greatest number")
elif y > x & y > z:
    print(str(y) + " is the greatest number")
else:
    print(str(z) + " is the greatest number")

The execution of the program will start from the first statement, if the first statement is true then it will execute else it will go to check the elif condition otherwise else condition.

Result: 30 is the greatest number

2. While loop

Python while loop is used to repeatedly execute some statements till the condition is true. It means use the while loop to check a condition before each execution of the loop.

# Let's check the loop condition

print("********While loop test**********")
x = 1
while x < 5:
    print(x)
    x += 1

Here while loop always checks the condition before executing the statement.  In python, there is no do while loop.

Result :

********While loop test**********
1
2
3
4

In the above example, we can write the else condition also, if the while condition is failed, it will execute the else condition. This is the good feature in python. Let’s check the same example with else condition.

x = 1
while x < 5:
    print(x)
    x += 1
else: 
    print("condition false")

3. For loop

Python’s loop is more flexible than that of other languages. We can do more interesting things here. Python’s for loop is versatile. First, let’s check the example of the range which can execute like for loop.

print("********For loop range test**********")
for x in range(1,5):
    print(x)

Output :

********For loop range test**********
1
2
3
4

Similarly, we can see the example of the sequence for the loop.

print("********For loop test**********")
list = [1, 2, 3, 4, 5]
for x in list:
    print(x)

As I above mention for loop is very versatile in python. It means we can use reverse order traverse or we can traverse the loop based on sorted items. Let’s check both for an example.

print("********For loop reverse test**********")
list = [1, 2, 3, 4, 5]
for x in reversed(list):
    print(x)

Output:

********For loop reverse test**********
5
4
3
2
1

Let’s check the item traverse based on the sorted item.

print("********For loop sorted test**********")
list = [5, 3, 2, 4, 1]
for x in sorted(list):
    print(x)

Output:

********For loop sorted test**********
1
2
3
4
5

Now the question arises here if you are java or other language know? how can use the index based traverse the item? So I can say python is so smart language. yes, you can iterate with index and value both together.  Let’s see this as an example.

print("********For loop index and value test**********")
for index,value in enumerate(list):
        # print the index along with their value
        print ("value of "+str(index)+" is = "+str(value))

Output :

********For loop index and value test**********
value of 0 is = 1
value of 1 is = 2
value of 2 is = 3
value of 3 is = 4
value of 4 is = 5

4. Break and Continue

Python break and continue statements are used only in loop. It helps to modify loop behavior. Suppose you’re executing a loop, at one phase you need to terminate the loop or skip some statements then you need these statements.

print("********For loop break**********")
list = [1, 2, 3, 4, 5]
for x in list:
    if(x > 3):
        print("break")
        break
    print(x)

Output:

********For loop break**********
1
2
3
break

Let’s check the same example by using continue for the loop with skip an item.

print("********For loop contine**********")
list = [1, 2, 3, 4, 5]
for x in list:
    if(x == 3):
        print("skipped", x)
        continue
    print(x)

OutPut:

********For loop continue**********
1
2
skipped 3
4
5

Now we have a good understanding of the loop and conditional statement of python. In my next tutorial, we will learn basic understanding about the function in python.

If you are wondering to learn Android then Please Learn from Android category and Wondering to lean Kotlin then Kotlin Category will help you.

Please do subscribe your email to get the newsletter on this blog on below and if you like this post then do not forget to share like and comment on below section.

You can learn all articles of MobologicPlus from the android app, which is available to download below.

[appbox googleplay  mobi.androapp.mobologicplus.c7929]

Happy coding 🙂

0 0 votes
Article Rating
Understanding the conditional Statement and Loop of python

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago