Python Conditional statements and Iterators | Sole Concept Lab
Python For data scienceTutorials

Python Conditional statements and Iterators A guide to control statements and python iterators

Introduction

This post aims to take you through the net set of fundamentals. I will keep this introduction short and quickly introduce you to today’s topics i.e

  • Conditional statements
  • Iterators

In python, conditional statements are those that impose a criterion on a task. Iterators are equally important. These are very commonly used to go over a list and this is done in two forms. I will walk you through both the forms here. What I mean by forms will be understood once we proceed. Let’s get started straight away.

Python Control statements

Now, I am pretty sure that most of us would have ……. hmm no have come across situations both in life and in programming where we had to impose conditions on a situation.

Yes! By now you would have guessed it right, we are going to look at if-else statements in python. These impose conditions on a given input. How do you code them? it is very simple.

 

Look at the example below.

1
2
3
4
5
6
7
8
name = input("Hi there what is your name? ") #Asking for users input

if isinstance(name,str):

print('yes')
else:

print(type(name)+' '+ 'is not a string')

Most of the code above is what is already seen in the previous blog. The input and print statements must be pretty clear by now. Also, the variable type should be clear. Here I am sending in a str and checking if the thing is actually a string. Why should you do this?

The answer is simple.  The name is a string always right? But is that just the thing? I leave it to you to find out.

Exercise: Try to input a number rather than a string and find its type. Whats the type? Can you find the type in python? You can leave it in comments here.

The else condition is also pretty simple to understand the first thing that the code does is to check if the input is a string. If not it moves on and says that it is not a string.

Important note: Make sure to use ‘:’  and proper indentation afterwords. A tab is a must. I will set up an exercise page soon so that you can walk through and solve the problems. The exercises mentioned here.

Let’s Now move on to the other very useful and widely used construct in python.

Iterators in Python:

An iterator is pretty basic and can be understood easily. The simplest example which can demonstrate the use of an ‘Iterator‘ is iterating through a list of numbers and finding if the numbers are odd or even and also count the number of even and odd numbers. What are the things to check here let’s have a look.

  • Generate a list of numbers
  • If the number is even and maintain a counter for the same
  • Check if the number is odd and maintain a counter for the same
  • Check the number of zeros

Let’s get started right away,

Generating random numbers in python

I am going to import a module called random in python using the import statement. The next step will be to generate thousand random numbers in the range 0 to 20 and store it in a list. The code for the same is shown below.

1
2
3
4
import random
numbers = []
for x in range(1000):
numbers.append(random.randint(0,20))

Let me show you the first 20 numbers.

An Output showing the list of numbers randomly generated from the code

The output of the list of random numbers Pretty neat isn’t it?

Now the next part of the code

what we have to do now is to check if the numbers are even odd or zero and count the number of even numbers, odd numbers, and zeros How do we go about doing so? We will use a for loop and counters. This loop will iterate through every element of the list divide it by two and check the remainder. Most of the code is pretty self-explanatory. But I will walk you through it.

1
2
3
4
5
6
7
8
9
10
11
even = [] # a list to store all the even numbers
odd = [] # list to store odd numbers
zeros =[] #list to store zeros

for i in numbers:
if i!=0 and i%2 == 0: #check two conditions
even.append(i)
elif i%2 !=0: # Check for odd
odd.append(i)
else : #else it is apparent it should be zeros
zeros.append(i)

Ok so let’s take a look at what does this code do and go line by line. The first thing that this code does is to iterate through the list ‘numbers’ that we created earlier. For every number in the list, it does the following operations

  • The first if condition does two things simultaneously firstly it checks if the number is zer0 and checks for the even number by dividing it by 2 and checking the remainder. Only if the number is not zero and even the number is appended to the list even. What does append do you can read it here . Only if both the conditions are satisfied it will proceed. Point to note ‘and‘ condition used here is a logical operation. I will introduce that later on in the series. But its pretty simple to understand.
  • The second condition appends the number to the list odd only if the remainder is not equal to 0. The ‘%‘ symbol denotes the operator which calculates the remainder. The symbol ‘ !=‘ denotes not equal to .
  • The third operation is simple if the number does not fall into any of these categories then append it to the zeros list.

Fair enough, So how do we check the number of elements in each list? Simple we will use the len() method to check the length of the list which is nothing but the number of elements in the list and print it out in a nice way. The code is below.

1
2
3
print("The zeros list has {} elements".format(len(zeros)))
print("The even list has {} elements".format(len(even)))
print("The odd list has {} elements".format(len(odd)))

So how many numbers have we got in each list lets check it out

There it goes. I will conclude with a small summary here. This post exhaustively covers the conditional statements and iterators. Walking along and reproducing the code …. what I mean is that if you code along while reading it will help you get the basics stronger. We saw how to construct and use conditional statements in python.

Also, we saw how to use iterators in python. The important point is that we did not cover iterators alone. I showed you how to combine conditional statements with loops.

In the next post, I will cover functions and show you amazing use cases. Ciao!!

Sharing is caring!

No Responses

Leave a Comment