Change language

Loops and control statements (continue, break and walk) in Python

| |

While the loop

Syntax:

 while expression: statement (s) 

In Python, all statements indented by the same number of character spaces after the code construct are considered part of the same block of code. Python uses indentation as its method of grouping statements.

# prints Hello Geek 3 times

count = 0

while (count " 3 ): 

count = count + 1

  print ( "Hello Geek" )

Output:

 Hello Geek Hello Geek Hello Geek 

See this is for an example where a while loop is used for iterators. As mentioned in the article, it is not recommended to use a while loop for iterators in python.

For in a loop

In Python there is no C style for loop, i.e. for (i = 0; i "n; i ++). There is a for loop that looks like for iterator_var in sequence: statements (s)

It can be used to iterate over iterators and range.

# Loop through the list

print ( " List Iteration " )

l = [ " geeks " , "for" , "geeks" ]

for i in l:

  print (i)

  
# Iterate over a tuple (immutable)

print ( "Tuple Iteration" )

t = ( "geeks" , "for" , " geeks " )

for i in t:

print (i)

  
# Iterate over the line

print ( "String Iteration"

s = "Geeks"

for i in s:

print (i)

  
# Looping through the dictionary

print ( "Dictionary Iteration"

d = dict () 

d [ ’xyz’ ] = 123

d [ ’abc’ ] = 345

for i in d:

print ( "% s % d" % (i, d [i]))

Output:

 List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G eeks Dictionary Iteration xyz 123 abc 345 

We can use an in loop for custom iterators. See for iterator_var in sequence: for iterator_var in sequence: statements (s) statements (s)

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

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

The final note about nesting loops is that we can put any type of loop inside any other type of loop ... For example, a for loop can be inside a while loop or vice versa.

from __ future__ import print_function

for i in range ( 1 , 5 ):

for j in range (i):

  print (i, end = ’’ )

  print ( )

Output:

 1 2 2 3 3 3 4 4 4 4 

Loop control statements

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

Continue Statement
Returns the control to the beginning of the loop.

Exit:

 Current Letter: g Current Letter: k Current Letter: f Current Letter: o Current Letter: r Current Letter: g Current Letter: k 

Break Statement
This brings control out of the loop

# Prints all letters except & # 39; e & # 39; and & # 39; s & # 39;

for letter in ’pythonengineering’

  if letter = = ’e’ or letter = = ’s’ :

continue

print ’ Current Letter: ’ , letter

var = 10

Logout:

 Current Letter: e 

Pass Application
We use the pass statement to write empty loops. Pass is also used for empty control statement, function and classes.

for letter in ’pythonengineering’

 

# break the loop as soon as it sees" e "

  # or & # 39; s & # 39;

if letter = = ’e’ or letter = = ’s’ :

  break

 

print ’Current Letter:’ , letter

# Empty loop

for letter in ’ pythonengineering’ :

pass

print ’Last Letter:’ , letter

Output:

 Last Letter: s 

Exercise:
How to print a list in reverse order (last to first element) using while and for loops.

This article contributed by Ashirvad Kumar. If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See my article appearing on the Python.Engineering homepage and help other geeks. 
Please post comments if you find something wrong or if you would like to share more information on the topic under discussion

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically