Main Menu

search

You are here

Python: Control Structures

[last updated: 2024-09-21]
Python home page
Python: Programming
-----

On this page:

  • For
  • If
  • While

-----

  • For loop:
    for x in range(0, 3):
         [statements]

    the 'range' can be a predefined list, eg:
    listToRun = {1, 4, 6, 7}
    for x in listToRun:
         [statements]

    If you want to break out of the for-loop before it's done:
    if [expression]:
         if [expression]:
              break

  • If test:
    if [expression]:
         [statements]
    else:
         [statements]

    The [expression] can be any statement that evaluates to T/F
    The else statement is optional but there can only be one of them at most.


    If you have more than one 'else' condition to test, use elif:
    if [expression]:
         [statements]
    elif [expression]:
         [statements]
    elif [expression]:
         [statements]

  • While loop:
    i = 1
    while i < 6:
          print(i)
          if i == 3:
                break
                i += 1

.

.

.

eof