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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With