Print Statement: As you saw on the previous page the print statement converted the number i
into a string and printed it to the command line. This is more or less the equivalent of "say" in Snap!. Print statements allow a programmer to print values and variables at a chosen location in the code.
|
Return: If print
is Python's version of "say", then return
is Python's version of "report". return
should be used when you want to end a function and report a value.
|
If you're testing a function in Python like above, the interpreter will often print the return value so you can see what it was.
Below is the now familiar count_up
function written using a while
loop. Unlike the for
loop, while
does not have a built-in index variable (but we can easily define our own using the variable i
below).
|
The while
loop is analogous to the repeat until
loop in Snap! However, in Python the loop ends when the condition becomes False
(so you can think of a while loop as "repeat the code in the loop while True"). This is the opposite of Snap!'s repeat until
loop, which waits for its condition to become True
.
Write an exponent(num, power)
function that takes two arguments (a number and an exponent value) and returns the computed result. Write the function in your lab1.py
file. Below are a few example inputs. Make sure you return
your result instead of just printing it!
>>> exponent(10, 0)
1
>>> exponent(5, 3)
125
>>> exponent(2, 10)
1024
We've written a small autograder to help you test your functions. Right click on this link, choose "Save As", and save the file to the same directory that your lab1.py
file is in. To test exercises 1-3, use the following command:
python3 autograder.py lab1.py
This will run a series of tests to validate the functionality of your exponent definition (and the definitions for exercises 2 and 3). Check the output to make sure it worked!