Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python know a block of code is in a loop? [duplicate]

Tags:

python

In loops, how does Python decide which statements belong to the loop?

For example, in C, one can write:

for(int i=0; i<=n; n++)
{ // Start of block
      Statement 1
} // End of block
Statement 2

But in the Python code below

 for i in range(5):
    statement 1
 statement 2

my intention is that statement 2 is out of the loop.

How will Python identify the end of this block? By using TAB spaces?

I'm confused as to what happens, especially if there are nested loops.

like image 786
Veerendra Avatar asked Aug 24 '15 06:08

Veerendra


People also ask

How do you check for duplicates in a loop Python?

Method 1: Use set() and List to return a Duplicate-Free List. Method 2: Use set() , For loop and List to return a List of Duplicates found. Method 3: Use a For loop to return Duplicates and Counts. Method 4: Use any() to check for Duplicates and return a Boolean.

How do you know if Python is repeating?

A for loop lets you repeat code (a branch). To repeat Python code, the for keyword can be used. This lets you iterate over one or more lines of code. Sometimes you need to execute a block of code more than once, for loops solve that problem.

Which loop in Python is used to repeat a block of statement for a given number of time until the given condition is false?

In python, a 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.

Does Python have a repeat loop?

There are also loops that repeat statements a specific number of times. The following looping statements are available in Python: for - Uses a counter or loops through a each item in a list a specified number of times. while - Loops while a condition is True.


1 Answers

This is indeed done by indentation. So in your example, statement 1 is in the for-loop, statement 2 isn't. You can use spaces and tabs as indentation, as long as you are using the same thing everywhere in the code.

An example of a nested for-loop:

for i in range(5):
    for j in range(10):
        print j
    print i
print 'Done!'

print j is done in the j-for-loop. print i is done in the i-for-loop. Done! will only be printed once, in the end.

like image 97
Mathias711 Avatar answered Sep 20 '22 14:09

Mathias711