Loops in Python: Know the Full Tutorial with the Best Examples

Loops in Python_ Full Tutorial with the Best Examples

Loops in Python is one of the important concepts in Python Programming Language. You may think loop as a circle when you hear about it. You are somewhat correct. But in Programming field it is somehow different. There is a block in a piece of code which is code block. In all programming language, you have code-block. We have to repeatedly execute this code block. But, How we can execute code block repeatedly. It comes in mind of every programmer.  There is a solution to it that is Loops. Loops are use when you have code block and want to execute code repeatedly. There are various types of loops for the execution.  In this article, you will know the different types of loops for executing the code block. All the types of loops are explained with the best and simple examples to make these loops easily understandable.

However, if you are new in Python Programming Language, then you must read the Introduction to Python Programming before reading the whole article. To learn the loops in the article you make sure that Python 3 version has installed in your computer. Python Installation Tutorial will guide you to install Python in your working computer.

Where are Loops in Python used in the Real World:

Loops in python are use for performing a task that requires to execute more than one times. This is the main importance of loops in python. It will be bit confusing to know it if you are completely new in this field. If you are one of them then you must read the whole article. However, this section will mainly focus on the use of Loops in Python in the real world.

Now let’s take the real example of loops in python programming language. Consider, there is a company A with less than 100 employees. There is first 50 employees get a salary of 2000$ per month whereas other 50 employees get the salary of 5000$. You as a programmer, you have to perform a task related to A company’s employees. The following task you have given. The below example is the very easy and basic example of a real-life problem.

  1. You have to print the name of employees having the salary of less than 2000$.
  2. Print the name of employees having the salary between more than 2000$.
  3. Name of employees having the salary greater than 5000$.

Solving the above problem statement using Loops

You can think all the above tasks as queries in a program. The real world may have a number of queries according to user-base and the project requirements. You have to find queries by own or by receiving feedbacks from the user-base. Then proceed to find the solutions to the queries. Now you must be thinking about how we can solve the above task. To solve the above tasks we have to use the loops. You must remember one thing in mind that which loops are you using inside the code will depend on the problem statements. Therefore to solve the above tasks we have to use if and else control flow statement and for loop. The following is pseudo-code of the above problem.

for(employees=1 to employees=100 )

if(employees_salary less than 2000) print the employee_name

elif(employees_salary greater than 2000) print the employee_name

else print the employee_name

Basic Overview of Python For the Beginners

If you have the basic knowledge of any other programming languages like C, C++, Java, e.t.c. Then it will be very easy for you to understand the basic concept and syntax of Python. But if you are beginners then it is also okay. You will easily remember the syntax of the Python programming language. However, you must do some practical work for it. It means you have to write code on these syntaxes to memorize it. There are many concepts in Python. But here you will only know the most commonly used syntax. You will further come to know that, these syntaxes are used in the Loops. Therefore, you can take reference of this section while reading the loops in details.

Declaring a Variable

You can declare the variables in Python by using the assignment operator. There are five types of data types in python.

  1. String
  2. Numbers
  3. Lists
  4. Tuple 
  5. Dictionary

Below is the syntax for declaring the variables for different data types.

String

There are two ways of assigning strings to the variable. It is either single or double quotes. You have the choice to choose single or double quotes. But I will prefer you use double quotes. However, there can be a rare situation where you have to use single quotes. Below is the syntax for the string variable

variable_name =' "Demo Text " '

# Printing the string variable

print(variable_name)

There are other things you can do with strings .For example to concatenate two strings. There are also various built in method for the strings. Like

, capitalize() to convertthe first letter of the string to capital letter. strip() to remove the identical character from it.  You can find more built in methods here.

Python Built in Methods for the String

Number

In python variable of type, numbers are assigned without any quotes.  Only four types of numbers are supported by Python

  1. int
  2. long
  3. float
  4. complex

The syntax for the declare variable of number are given below

variable_name = int or float or long or complex (types)

Lists

It is a datatype which contains comma separated values inside the square brackets. Below is the syntax for list datatype.

lists_variable_name = [ value1,  value2,  value3, value4 ]

Values can be anything. It can be either integer, either strings or float. Values can be access using the index of the values. All indexes start with 0. For example to access the first value we use lists_variable_name[0]. In the similar way for third values use   lists_variable_name[2] .

lists_variable_name[0] #value1

lists_variable_name[1] #value2

lists_variable_name[2] #value3

lists_variable_name[3] #value4

lists_variable_name[1 : 3] # From value2 to value4

Tuples

Tuples is an object of sequence in Python. It contains values separated by commas with brackets. The following the syntax for tuples.

tuple_variable_name = ( value1,  value2,  value3, value4 );

Tuples can be access by the following ways

tuple_variable_name[0] #value1

tuple_variable_name[1] #value2

tuple_variable_name[2] #value3

tuple_variable_name[3] #value4

tuple_variable_name[1 : 3] # From value2 to value4

Difference between tuples and lists

You will notice at first that list and tuples are the same thing.  But there is difference  between list and tuples. Lists are mutable whereas tuples are not. It means ,you can change the values of lists but tuples cannot be changed like lists. Lists uses square brackets whereas tuples uses parenthesis.

Dictionary

Dictionary contains two part one is key and other is value. Each key and value in it is separated by a colon. All the items are separated by commas and whole thing it enclosed by curly braces. Following is the syntax for declaring and accessing the dictionary items. Values can be of any data type like float, int, string.

dic_name = { 'Name' : ' Rocky ' , 'Age' : 25 , 'Location' : 'USA'} # Declaring the dictionary

The item inside the dictionary is access by disc_name[ ‘Name’]. It will give the output Rocky.

Different types of Loops In Python

You will find there are many loops in python similar to other programming languages. In this section, you will know the various types of loops used in Python as well as how to use it with different data types in Python.

For Loops in Python

It is used when you want to repeat a block of code for a finite number of times. The syntax of for loops is given below.

for variable_name in sequence:

statement1

statement2 -------------

statementN

Below are the different example of loops. You make sure to practice while learning in the editor to learn more.

#list
list = [10,20,0,"Python",30.4] #List
#for loop
for l in list:
print(l)

Output

10
20
0
Python
30.4

If Loop in Python

It will execute a set of statements after a condition is true or False. Below is the syntax for the if loop in Python.

if(conditon1) :

statment1

elif(condition2)

statement2

else

statement3

The below example will clear you more on if else loop,

number = int(input("Enter the number"))
if (number == 100):
print ("number is 100")

elif (number ==200) :
print("Number is 200")

elif (number ==500):
print("Number is 500")
else:
print("It is a different number")

Output

Enter the number500
Number is 500

While Loop in Python

The while loops is also condition loop. The difference is that first, you set the counter and then check conditions on that counter for executing the statement.

Lets clear query with the example.

# while loop
count =0
while(count<len(list)):
print(list[count])
count =count+1

Output

10
20
0
Python
30.4

Conclusion

Loops in python are generally used while designing the algorithm and the functions. In fact, you will use it everywhere whether it is machine learning or artificial intelligence field. You should practice yourself in the editor for memorizing the syntaxes of the all the loops in python. Feel free to contact us for adding any suggestion from you. Please subscribe us to get new post available directly in your inbox from the Python world.

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner