Intro to Python
Copyright (c) 2017 Kathi Fisler
1 Starting Pycharm
We talked about creating a Pycharm Project to store the files for a single assignment. We showed that the analogue to the Pyret interactions window is under the "Python Console" button at the bottom left of the Pycharm window. We showed how to run your code by right-clicking on the code area and choosing the "run file" option near the very bottom of the menu that comes up.
2 Python vs Pyret code
We showed how to translate the free-bags function from the pyret starter file that is linked to the lectures page. Here’s the corresponding Python code:
from testlight import * # load the testing library |
|
def free_bags(status : str) -> int: |
'''return number of free bags based on status''' |
if status == "gold": |
return 2 |
elif status == "silver": |
return 1 |
else: |
return 0 |
|
# examples don't go inside functions |
def test_bags(): |
test("check gold", free_bags("gold"), 2) |
test("check silver", free_bags("silver"), 1) |
Here’s an image of the spots in the Python code that differ from the Pyret version:
3 No Need to "End" Functions
Python figures out that you have ended a function definition by detecting that the next definition has started. It can do this because \emph{indentation carries meaning in Python}. Once Python detects an unindented line, it ends the previous definition.
This behavior can lead to subtle bugs in your code, as we’ll see later. Unlike Pyret, there is no reliable auto-reindent in Python. We’ll talk more about this as we go along.
4 The Need for Return
One big difference in Python is the need to mark the output of a function with return. Here are three versions of a function that add 1 to an input number. Each does something quite different.
def add1v1(x: int) -> int: |
return x + 1 |
|
def add1v2(x: int) -> int: |
print(x + 1) |
|
def add1v3(x: int) -> int: |
x + 1 |
The first version is an actual function as in Pyret: it will return an integer that you can use in other computations, as in 3 * add1v1(4).
The second version \emph{appears} to do the same thing as the first if you run it in the console, but it doesn’t actually yield a value. Evaluating 3 * add1v2(4) would yield an error about * not taking a NoneType value (Python’s way of saying "there was no output"). Print just displays in the console.
The third version will make it look like your function "did nothing". Python did compute x + 1 as instructed, but the code doesn’t \emph{do} anything with that value (in contrast to the first two versions). {\bf If it looks like your function "did nothing", check to see whether you forgot to include the return.}