# Loops

• Difficulty Level : Easy
• Last Updated : 13 May, 2022

Python programming language provides the following types of loops to handle looping requirements. Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.

1. While Loop:
2. In python, while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed.

Syntax :

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

3. 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.
Example:

## Python

 `# Python program to illustrate``# while loop``count ``=` `0``while` `(count < ``3``):    ``    ``count ``=` `count ``+` `1``    ``print``(``"Hello Geek"``)`

Output:

```Hello Geek
Hello Geek
Hello Geek```
• Using else statement with while loops: As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
If else like this:

## Python

 `if` `condition:``    ``# execute these statements``else``:``    ``# execute these statements`
• and while loop like this are similar

## Python

 `while` `condition:``     ``# execute these statements``else``:``     ``# execute these statements`

## Python

 `#Python program to illustrate``# combining else with while``count ``=` `0``while` `(count < ``3``):    ``    ``count ``=` `count ``+` `1``    ``print``(``"Hello Geek"``)``else``:``    ``print``(``"In Else Block"``)`

Output:

```Hello Geek
Hello Geek
Hello Geek
In Else Block```
• Single statement while block: Just like the if block, if the while block consists of a single statement the we can declare the entire loop in a single line as shown below:

## Python

 `# Python program to illustrate``# Single statement while block``count ``=` `0``while` `(count ``=``=` `0``): ``print``(``"Hello Geek"``)`
• Note: It is suggested not to use this type of loops as it is a never ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.
1. for in Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals.

Syntax:

```for iterator_var in sequence:
statements(s)```

It can be used to iterate over a range and iterators.

## Python3

 `# Python program to illustrate``# Iterating over range 0 to n-1`` ` `n ``=` `4``for` `i ``in` `range``(``0``, n):``    ``print``(i)`

Output :

```0
1
2
3```

## Python

 `# Python program to illustrate``# Iterating over a list``print``(``"List Iteration"``)``l ``=` `[``"geeks"``, ``"for"``, ``"geeks"``]``for` `i ``in` `l:``    ``print``(i)``      ` `# Iterating over a tuple (immutable)``print``(``"\nTuple Iteration"``)``t ``=` `(``"geeks"``, ``"for"``, ``"geeks"``)``for` `i ``in` `t:``    ``print``(i)``      ` `# Iterating over a String``print``(``"\nString Iteration"``)    ``s ``=` `"Geeks"``for` `i ``in` `s :``    ``print``(i)``      ` `# Iterating over dictionary``print``(``"\nDictionary Iteration"``)   ``d ``=` `dict``() ``d[``'xyz'``] ``=` `123``d[``'abc'``] ``=` `345``for` `i ``in` `d :``    ``print``(``"%s  %d"` `%``(i, d[i]))``     ` `#Iterating over a set``print``(``"\nSet Iteration"``)``set1 ``=` `{``1``,``2``,``3``,``4``,``5``,``6``}``for` `i ``in` `set1:``    ``print``(i),`

Output:

```List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345```

Iterating by the index of sequences: We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length.
See the below example:

## Python

 `# Python program to illustrate``# Iterating by index`` ` `list` `=` `[``"geeks"``, ``"for"``, ``"geeks"``]``for` `index ``in` `range``(``len``(``list``)):``    ``print` `list``[index]`

Output:

```geeks
for
geeks```

Nested Loops: Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax:

## Python

 `for` `iterator_var ``in` `sequence:``    ``for` `iterator_var ``in` `sequence:``        ``statements(s)``        ``statements(s)`

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

## Python

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

A final note on loop nesting is that we 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.

## Python

 `# Python program to illustrate ``# nested for loops in Python``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```

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.76848465,"math_prob":0.6758124,"size":4747,"snap":"2022-05-2022-21","text_gpt3_token_len":1260,"char_repetition_ratio":0.15580855,"word_repetition_ratio":0.107744105,"special_character_ratio":0.26374552,"punctuation_ratio":0.1134594,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9569908,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-16T13:23:51Z\",\"WARC-Record-ID\":\"<urn:uuid:6a4cb80d-89e6-48ac-8697-8ef5954fe74b>\",\"Content-Length\":\"149986\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1b6ede5a-d487-4141-8433-762a53e85d8e>\",\"WARC-Concurrent-To\":\"<urn:uuid:6401f203-9a99-4466-9562-a8be2bddb7f2>\",\"WARC-IP-Address\":\"23.221.227.168\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/loops-in-python/?ref=lbp\",\"WARC-Payload-Digest\":\"sha1:3FGSVOIBAJYMHLVD6NTDKW4DA4V2RLQ2\",\"WARC-Block-Digest\":\"sha1:QJUG4LTBQK6B3VJ6AUDBOGKNXM7YNDIW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662510117.12_warc_CC-MAIN-20220516104933-20220516134933-00453.warc.gz\"}"}