Python For Loop
for loop can be used to iterate over a list of items and perform a set of actions on each item. The syntax of a
for loop consists of assigning a temporary value to a variable on each successive iteration.
When writing a
for loop, remember to properly indent each action, otherwise an
IndentationError will result.
for loops can be used to iterate over and perform an action one time for each element in a list.
for loop syntax assigns a temporary value, the current item of the list, to a variable on each successive iteration:
for <temporary value> in <a list>:
for loop bodies must be indented to avoid an
Python Loops with
In Python, a
for loop can be used to perform an action a specific number of times in a row.
range() function can be used to create a list that can be used to specify the number of iterations in a
Remember, a loop always visits items in sequential order. This means it will visit every item in start from finish every time.
The first line of code will print 1 - 4. The next one will print 4- 1. What matters is the order of the values within the list, not their size.
In a Python loop, the
break keyword escapes the loop, regardless of the iteration number. Once
break executes, the program will continue to execute after the loop.
In this example, the output would be:
Negative number detected!
In Python, the
continue keyword is used inside a loop to skip the remaining code inside the loop code block and begin the next loop iteration.
In Python, a
while loop will repeatedly execute a code block as long as a condition evaluates to
The condition of a
while loop is always checked first before the block of code runs. If the condition is not met initially, then the code block will never run.
Python Nested Loops
In Python, loops can be nested inside other loops. Nested loops can be used to access items of lists which are inside other lists. The item selected from the outer loop can be used as the list for the inner loop to iterate over.
Python List Comprehension
Python list comprehensions provide a concise way for creating lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses:
[EXPRESSION for ITEM in LIST <if CONDITIONAL>].
The expressions can be anything - any kind of object can go into a list.
A list comprehension always returns a list.