Quantcast
Channel: Cloud Training Program
Viewing all articles
Browse latest Browse all 1891

Beginners Guide To Loops And Control Statements In Python

$
0
0

In this blog, we are going to loop at all the looping conditions and control statements available in Python like while loop, for loop, nested loop, break, continue etc.

Looping Statements

The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several times.
Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement −

Loop Architecture

Python programming language provides the following types of loops to handle looping requirements.

Loop Type & Description

While Loop Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
For Loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Nested Loop You can use one or more loops inside any another while, for or do..while loop.

1. While Loop

while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

Syntax
The syntax of a while loop in the Python programming language is −

while expression:
   statement(s)

Here, statement(s) may be a single statement or a block of statements. 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.

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.

Flow Diagram

Here, the key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.

count = 0
while (count < 9):
   print('The count is:', count)
   count = count + 1

print("Good bye!")

2. For Loop

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:
   statements(s)

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.

Flow Diagram

Example:

In this code we are iterate the each letter of the string using for loop.

for letter in 'Python':    
   print('Current Letter :', letter)

3. Nested Loop

Python programming language allows using of one loop inside another loop. The following section shows few examples to illustrate the concept.

Syntax

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

The syntax for a nested while loop statement in the Python programming language is as follows −

while expression:
   while expression:
      statement(s)
   statement(s)

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.

Example 

The following program uses a nested for loop to find the prime numbers from 2 to 20 −

i = 2
while(i < 20):
   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!")

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their detail.

Let us go through the loop control statements briefly

Control Statements & Description

Break Statement Terminates the loop statement and transfers execution to the statement immediately following the loop
Continue Statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Pass Statement The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

1. Break Statement

It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

Syntax

The syntax for a break statement in Python is as follows −

break

Flow Diagram

Example:

for letter in 'Python':     
   if letter == 'h':
      break
   print('Current Letter :', letter)

2. Continue Statement

It returns the control to the beginning of the while loop.. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

Syntax

continue

Flow Diagram

Example:

for letter in 'Python':   
   if letter == 'h':
      continue
   print('Current Letter :', letter)

3. Pass Statement

It is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example)

Syntax

pass

Example:

for letter in 'Python': 
   if letter == 'h':
      pass
      print('This is pass block')
   print('Current Letter :', letter)

print("Good bye!")

4. Difference between Break and Continue in Python

The main difference between break and continue in python is loop termination. In this tutorial, we will explain the use of break and the continue statements in the python language. The break statement will exist in python to get exit or break for and while conditional loop. The break and continue can alter the flow of normal loops and iterate over the block of code until the test expression is false.

Basis for comparison

Break

Continue

Task It eliminates the execution of the remaining iteration of the loop It will terminate only the current iteration of the loop.
Control after break/continue ‘break’ will resume control of the program to the end of the loop enclosing that ‘break’. The ‘continue’ will resume the control of the program to the next iteration of that loop enclosing ‘continue’
causes It early terminates the loop. It causes the early execution of the next iteration.
continuation The ‘break ‘stop the continuation of the loop. The ‘continue’ does not stop the continuation of the loop and it stops the current.
Other It is used with the ‘switch’, ‘label’ Cannot be executed with the switch and labels.

Related References

Next Task For You…

Python’s growth is very promising in the near future. Gaining the right skills through the right platform will get you to the perfect job.

We are launching our course Python For Data Science (AI/ML) & Data Engineers (Python For Beginners) which will you help and guide you towards your first steps to Python. Register for our FREE CLASS to know more about it.

Free Class Python

The post Beginners Guide To Loops And Control Statements In Python appeared first on Cloud Training Program.


Viewing all articles
Browse latest Browse all 1891

Trending Articles