Source

Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree

Conditionals

An if chain runs the first body whose condition is true. elif and else are optional.

temperature = 25
if temperature > 30:
    print("hot")
elif temperature > 20:
    print("warm")        # this one runs
else:
    print("cool")

While and For Loops

Loop forms:

  • while condition: repeats the body as long as the condition stays true, so the body must update something (e.g. a counter)
  • for element in iterable: runs the body once for each item of a list, string or range
  • range(start, stop, step) gives start, start + step, ... up to but not including stop, so range(n-1, -1, -1) counts backwards from to
count = 5
while count > 0:
    print(count)
    count -= 1           # 5 4 3 2 1
 
for fruit in ["apple", "banana"]:
    print(fruit)

Break and Continue

Loop control:

  • break stops the whole while or for loop at once
  • continue skips the rest of the current pass only, and the loop goes on with the next pass
  • in nested loops, both act only on the innermost loop that contains them
for x in range(0, 2):
    for y in range(0, 2):
        if x == y:
            continue     # skip print for x == y
        print(x, y)      # prints 0 1 and 1 0

Functions

A function is defined with def. The return statement sends a value back and ends the function at once.

def greet(name):
    """Greet the user by name."""
    return "Hello, " + name
 
print(greet("Alice"))

Input and Files

Basic input and output:

  • input(prompt) shows a prompt and returns the typed characters as a string, so convert with int() or float() before doing maths
  • fp = open('sample.txt') opens a file and returns a file object to read from
n = int(input("Enter n: "))
a = []
for k in range(n):
    a = a + [int(input("Enter element: "))]   # build an array from user input

These patterns are used directly in the Array Loop Examples.