Week II Cheat Sheet

Dictionary

Python dictionaries store objects by key (instead of positions like list or tuple), and map keys to associated values. We can index the dictionary by key to fetch and change the keys’ associated values. It's very similar to python list, but the item in the square brackets is a key, not a relative position.

Function

Functions are reusable pieces of programs. They allow you to give a name to a block of statements, to run that block using the specified name anywhere in your program and any number of times. This is known as calling the function.

Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some parameters, and by the final colon that ends the line. Next follows the block of statements that are part of this function.

def num_seq(start, end=10):
    # check the parameter
    if end <= start: 
        print("input number too small")
        return  # return break the function
    elif type(start) is not int or type(end) is not int:
        print("input number is not an interger")
        return
    my_list = []
    for i in range(end + 1):
        my_list.append(i)
    return my_list

my_list = num_seq(5)  
print(my_list)

The return statement is used to return from a function i.e. break out of the function. We can optionally return a value from the function as well.

pass is a null operation -- when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed. It is useful when you have started writing your function but have not finished it yet.

def num_seq(start, end):
    pass

Last updated