Python Loops: In Python, Loops are used to execute a block of code multiple times according to the condition. A loop function uses almost identical logic and syntax in all programming languages. Thus, a specific statement or a group of instructions is continuously executed until a specific loop body or boundary condition is reached.
A loop is divided into two parts:
- Loop Statement: It defines the time limit to be true for the continuous loop that is contingent on the attached conditional statement.
- Loop Body: While the statement’s code or instructions, it is executed with each loop cycle.
Python for loop
It is used for iterating over a sequence such as a list (or) strings. If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
#!/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!"
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
Python While loop
It is used for executing a set of statements as long as a condition is true. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.
And in Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
i = 1 while i < 6: print(i)i += 1
NOTE: remember to increment i, or else the loop will continue forever.
Python Loops through Strings
In loops, strings are also iterable objects. They contain a sequence of characters.
for x in "grape":print(x)
Python Else in for loop
It describes a block of code to be executed when the loop is finished.
for x in range (5): print(x) else: print("Finally finished!")
Python Nested Loops
A loop inside another loop. And the “Inner loop” will be executed one time for “outer loop”.
adj=["red","big","tasty"] fruits=["apple","banana","cherry"] for x in adj:for y in fruits: print(x, y)
Python Range() function Using for loop
It returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for x in range(4):#range value starts from 0 print(x)