Looping Structure

By Looping structure is a executes a statement or group multiple times.
Looping structure mainly two types,

We can control our looping statement three way.

1) for Loop

It executes a sequence of statements many times and abbreviates the code that manages the loop variable.

Syntax

for val in sequence:
body of for

Example

numbers = [6,5,3,8,4,2,5,4,1]
sum = 0
for val in numbers:
sum =  sum + val
print("The sum is ", sum)

The sum is 38

2) While Loop

It repeats a statement or group of statements while a given condition is TRUE.
It tests the condition before executing the loop body.

Syntax

while test_expression:
body of for

Example

n = 1
sum = 0
i =1
while i <= n:
sum = sum + i
i = i + 1
print("The sum is ", sum)

The sum is 1

While loop with else

In the While loop, the user can have an optional else block.
The else part is executed if the condition is moved to False.
The while loop must be terminated with a break statement.

Example

counter = 0
while counter < 1:
print("Inside loop")
counter =  counter + 1
else:
print("Inside else")

Inside loop
Inside else

While with condition at middle

here we can write condition between the code,

Example

vowels = "aeiouAEIOU"
#infinite loop

while True:
v = input("Enter a vowel:")
if v in vowels:
break
print("That is not a vowel. try again")
print("Thank you")

Output

Enter a vowel:a
Thank you
Enter a vowel:g
That is not a vowel. try again

1) Break

Terminates the loop statement and transfers execution to the statement immediately following the loop.

Example

for val in "Python":
if val == "t":
break
print(val)
print("The end")

P
y
The end

2) Continue

The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
The loop does not terminate, but continues on to the next iteration.

break

Example

for val in "Python":
if val == "t":
continue
print(val)
print("The end")

P
y
h
o
n
The end

3) Pass Statement

‘pass’ is a null statement.
The pass statement is used when a statement is required syntactically, but you do not want any command or code to execute.
However, nothing happens when the pass is executed.
It results into no operation. This is like a “void” keyword, it does not return any value.

Example

se = {'p','a','s','s'}
for val in se:
pass
print("The end")

The end

Latest Blog

What is New in Android studio 3.5

Android studio 3.5 include some of the new features and behavioures changes. like, Memory Management Setting, Memory usage report,...

Application Of Various Operation Research Techniques

Application Of Various Operation Research Techniques are, Linear programming, Decision theory, Simulation, Inventory control, Network techniques and CPM