Fandom

Python Wiki

Loops

43pages on
this wiki
Add New Page
Talk0 Share

for StatementEdit

For loops are used to iterate an iterable. They are most often used to execute code n about of times.

for i in xrange(1, 3):
    print i

Output:

1
2
3


Nested LoopsEdit

for i in xrange(1, 3):
    for j in xrange(i, 4):    
        print i, j


For..ElseEdit

Code block after else is executed after after the for, but only if loop is terminates in standard way (brake statement is not used)

for i in xrange(1, 3):
    print i
else: 
    print 'after for'

Output:

1
2
3
after for


while StatementEdit

While loop, like for, is used for executing code many times. Main difference between those two is fact that while loop isn't executed n times, but until a defined condition is false.


Loop control statementsEdit

Loop control statements change standard loop execution flow.

while result = do_something():
    print result

Execution of this loop is stopped do_something() returns False


breakEdit

Break terminates the current loop and resume next statement execution.

for i in (1, 2, 3):
    if i == 2:
        break
    print i
print 'test'

Output:

1
test


continueEdit

Continue stops execution of current iteration and moves the control back to the top of next iteration.


for i in (1, 2, 3):
    if i == 2:
        continue
    print i
print 'test'

Output:

1
3
test


passEdit

Pass statement is a *null* operator in Python. Nothing happen when it executes. It's placeholder used when statement is required by syntax, but no code is needed to be executed.

for i in (1, 2, 3):
    pass

Output:

(empty output)

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.