Post Contents
Being one of the best python training institutes in Delhi, AIDM has always innovated its method of delivering the knowledge to its students or its view on the online platforms.
This tutorial contains in-depth knowledge of Loops in python.
Lets begin!
Usually, statements are executed in a sequential way then loop is required. The first statement in function is executed first, then second and so on. There may be situations while coding in python, you will require to execute a block of code several times. To fulfill the need of that situation, you will require a loop function.
Join our online & offline python training in Delhi to become an expert in this field.
The Python programming language provides various structures that allow it to execute complicated paths. A loop statement helps you to execute a single statement of a group of statements multiple times.
Three types of loops in python programming language are
It will be good if you learn Data Science course in delhi yourself by joining the Django training in delhi
“For” loop
For loop allows a programmer to execute a sequence of statements several times, it abbreviates the code which helps to manage loop variables.
For loop syntax
for val in sequence:
Body of for
Here’s its flow chart, which will give you an idea about how it gets implemented.
If a sequence has a list of expressions, it is evaluated first. After this, the first item in the sequence is assigned to iterate with a value “iterating_var”. Next the block containing statements will be executed.
Now, each item in the list will be assigned to iterating_var and block having statements will be executed in the next step until the entire sequence is exhausted.
Live Code
#!/usr/bin/python
for letter in ‘Python’: # First Example
print ‘Current Letter :’, letter
fruits = [‘banana’, ‘apple’, ‘mango’]
for fruit in fruits: # Second Example
print ‘Current fruit :’, fruit
print “Good bye!”
The above code will result the output, which are shown below
Output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
To boost your career as a python developer, you can join the best python training institute in Delhi.
For loop using else statement
Python programming language allows a programmer to utilize the else statement associated with a loop statement. If the else statement is being utilized, then the else statement will be executed till the loop has exhausted iterating the list.
Below example illustrates the use of else statements with for loops that search for prime numbers from 10 to 20.
Live Demo
#!/usr/bin/python
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print ‘%d equals %d * %d’ % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, ‘is a prime number’
break
This output will be shown if the above code is executed properly.
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
“While” loop
While loop allows a programmer to repeat a single statement or a group of statements for TRUE condition. It verifies the condition before executing the loop.
While loop syntax in Python programming language
while expression:
statement(s)
Here, in the place of statements, it may be possible there is a single statement or a block of statements. The condition may contain any expression and it can be true for any non zero value. The loop will iterate every time when the value is found true. If the condition is found false, the program will follow the immediate next line of the loop.
In python programming language, all the statements are indebted by the same number of character space while writing a code for a single block. It always uses the method of indentation as a grouping statement.
Here is the important point of the while loop, which shows that the loop might not ever run. When the condition is found false, the loop body will be skipped and the statement of while loop will be implemented.
Example
Live Demo
#!/usr/bin/python
count = 0
while (count < 9):
print ‘The count is:’, count
count = count + 1
print “Good bye!”
Output
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Here the block which consists of the print and increment statements, is iterated until the count is no longer less than 9. With each execution, the current of the index count is increased by 1.
Join our online & offline PHP training in Delhi and Artificial Intelligence course in Delhi to become an expert in this field.
The infinite Loop
A loop becomes an infinite loop if a condition never turns out to be FALSE. You should utilize alert when utilizing while loops as a result of the likelihood that this condition never makes plans to a FALSE. This outcomes in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop may be valuable in client/server programming where the server needs to run persistently so client programs can speak with it as and when required.
Example
#!/usr/bin/python
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input(“Enter a number :”)
print “You entered: “, num
print “Good bye!”
Output
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File “test.py”, line 5, in <module>
num = raw_input(“Enter a number :”)
KeyboardInterrupt
The iteration in the above example will not stop unless you do not exit the program by pressing CTRL+C command.
Keep yourself updated with our python online course and you can also join AIDM – the best python training institute in Delhi to get physical classes under the guidance of industry experts.
“Nested” loops
Nested loop allows a programmer to use one or more loops inside any other for or while loop etc.
Syntax for “Nested” loops in python programming language
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
You can put any type of loop inside of any other type of loop using the nested loop. For example For loop can be inserted in while loop or vice versa.
Example
#!/usr/bin/python
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, ” is prime”
i = i + 1
print “Good bye!”
Output
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
Join our online & offline java training institute in delhi and android app development course for beginners to become an expert in this field.
Conclusion: This is all about the three types of loops used in python programming language. If you want to explore more, you can join our online & offline courses at AIDM, which is one of the best python training institutes in Laxmi nagar Delhi.
Recommended Blog:
- Number system, random module, math library, decimal in the python programming language
- Variable and datatypes work and behaviours in python language
- Python setup and a basic understanding of python language
- How to use casting and string in python
- Use of Boolean Datatype and Python Operators
- Use case of the tuple in python difference between list and tuple
- Python Sets And Dictionaries Python Lists, Python Sets & Dictionary
- Difference Between For and While Loop In Python