Transitioning to Python
Copyright (c) 2017 Kathi Fisler
Here’s a collection of references for migrating to Python:
1 Mapping Pyret to Python
Eli has prepared a useful cheat sheet showing how the various constructs you’ve learned in Pyret appear in Python.
2 Useful Documentation
Don’t worry about material outside of section 5.1 – we haven’t gotten to those parts yet.
In addition to these, you also have filter (and map) as shown in class:
>>> list(filter(lambda n: n > 5, [1, 7, 4, 9, 2]))
[7, 9]
>>> list(map(lambda n: n + 5, [1, 7, 4, 9, 2]))
[6, 12, 9, 14, 7]
Remember that you have to wrap list around calls to filter and map (due to internals of Python).
the full Python 3 documentation (though this is likely more than you’ll need other than for the basics). at first).
3 Tidbits
Python doesn’t have block comments
The convention is instead to use multi-line strings (with three double-quote marks to open and close), though this doesn’t work if you are commenting out code that itself has docstrings.
Python doesn’t check the argument types to functions
There’s a separate type checker which you can use, and which will report violations of types, but you won’t be alerted about type errors when you load or run code. We will still annotate with types as it is a useful practice for explaining your code to others.
4 Errors and what they might indicate
Python error messages are a bit more obtuse than Pyret’s. Here are some common messages and what problems they might point to:
SyntaxError: can’t assign to operator
Check whether you used a hyphen rather than an underscore in the name of a variable. For example, my-num = 3 will raise this error.
TypeError: ’NoneType’ object is not subscriptable
Check whether you are missing a return statement. If you meant to return a value from a function but left off the return, the value returned is a NoneType value. If you then try to extract an attribute from the NoneType, you get the above error
IndentationError: unexpected indent
In Python, indentation carries meaning: if your indentation is off, Python will report your program as having an error even though the constructs and logic of the program are fine. Indentation should be done with spaces, not the tab key. Use 4 spaces to indent inner constructs. Python editors will do this for you automatically when you hit return, but you need to know this in order to fix indentation problems (selecting all and hitting tab will NOT work in Python).
In Atom, under "Edit | Lines | Auto Indent", there’s an option to indent lines that you’ve selected. It’s worth trying that if you get stuck on indentation errors (though Kathi has had a handful of programs on which that doesn’t work properly: in particular, it doesn’t seem to work if you try to auto-indent multiple function definitions at once).