Defining a function in Python is easy! In your text editor, a function count-up in Python may look like this (to the right is the exact same function written in snap):

Function Header: Like in Snap!, the function header specifies the name of the function, and any arguments (a.k.a. input variables, parameters) of the function. Notice the line must begin with the keyword def and end with a :. This lets the Python interpreter know that the indented lines that follow are part of a function definition.

In Snap! it's common to have text between function parameters, such as the Snap! mod block. In Python, all parameters must come at the end of a function, between parentheses().

For Loop: The for loop in Python works similarly to our Snap! for loop with some key differences. To have the index variable i increment from 1 to num, we have to create an iterable. For now, think of an iterable as anything that can act like a list of items. Starting with the first item, i takes each consecutive item of the list as its value. The range(x, y) function receives two numbers and returns an iterable of all numbers beginning with x and ending with y-1.

In file: Lab1.py


def count_up(num):
    for i in range(1, num+1):
        print(i)
              

Run python -i Lab1.py


>>> count_up(4)
1
2
3
4
>>>
            

Make sure you notice: The iterable returned by range(x,y) does NOT include y. For this reason, if we want the count-up to include the input num, the count_up function must use a range that goes from 1 to num + 1.