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 . In Python, all parameters must come at the end of a function, between parentheses
()
.
In order to call a function, type the function name, followed by the inputs in parentheses. For example, if you wanted to run count_up
above with num = 4
, you would type count_up(4)
.
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 your file lab1.py
, copy and paste the following code.
def count_up(num):
for i in range(1, num+1):
print(i)
Then, in the terminal run your Python file using the command python -i lab1.py
. This will run the code in your file and leave the interpreter open for you, in case you want to run more code.
Now that you have your terminal open, you can call count_up
. Call count_up(4)
and see what it prints! Is this what you expected?
>>> 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
.