# Intro to Python ## Week 4 ### Boolean logic #### (Conditional expressions) 0. Review: readable code 1. Review: _order of operations_ 2. New: _conditional expressions_ 3. New: `if` _statements_ (switches) 4. Advanced _syntactic sugar_ note: 0. This week you will learn how to reason about code, you will develop a mental model of the logic rules that the machine follows 1. First we'll make sure you understand the order of operations 2. You'll learn how to read and write conditional expressions 3. You'll learn how to use conditional expressions in if statements 4. You'll learn how to sweeten your code with `or` in variable assignments --- ## Attendance ```python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. ... ``` - Pick a favorite term (word or concept) - Write it on the whiteboard with +1 (good) or -1 (bad) or 0?
**While you wait** - Think of an example and counter example (its opposite) - Can you find and open `this.py`? - Can you make it more pythonic (Zen of Python) note: - KISS --- ## Find `this` module's `.py` file ```python >>> this.__file__ '/home/hobs/.local/share/uv/python/cpython-3.12.13-linux-x86_64-gnu/lib/python3.12/this.py' >>> print(this.__file__) /home/hobs/.local/share/uv/python/cpython-3.12.13-linux-x86_64-gnu/lib/python3.12/this.py >>> import turtle >>> turtle
>>> turtle.__file__ '/home/hobs/.local/share/uv/python/cpython-3.12.13-linux-x86_64-gnu/lib/python3.12/turtle.py' ``` note: - if you can import it, you can find its source code note: - if you can import it, you can find its source code - if you try to find ``math.__file__`` it is not there! Why? (compiled to be fast) --- ## `open` a path in Sublime `$ subl ~/.local/share/uv/python/cpython-*/lib/python*/this.py` ### OR - select the path - [ctrl]-[shift]-[c] (copy the path) - open Sublime Text - [ctrl]-[o] - [ctrl]-[v] (paste the path) - [enter] --- ## [CTRL]-[O] [](./wk4/sublime-ctrl-o.png) --- ## [CTRL]-[v] [](./wk4/sublime-ctrl-v.png) --- ## [ENTER] (open) [](./wk4/sublime-ctrl-o.png) --- ## ``open``ing and ``read``ing files Students that want to get ahead: ```python >>> print(open(this.__file__).read()) s = """Gur Mra bs Clguba, ol Gvz Crgref Ornhgvshy vf orggre guna htyl. Rkcyvpvg vf orggre guna vzcyvpvg. Fvzcyr vf orggre guna pbzcyrk. Pbzcyrk vf orggre guna pbzcyvpngrq. Syng vf orggre guna arfgrq. Fcnefr vf orggre guna qrafr. Ernqnovyvgl pbhagf. Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. Nygubhtu cenpgvpnyvgl orngf chevgl. Reebef fubhyq arire cnff fvyragyl. Hayrff rkcyvpvgyl fvyraprq. Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. Abj vf orggre guna arire. Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""" d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) ``` --- ## Python style - Stanford's [Python Style Guide](https://cs.stanford.edu/people/nick/py/python-style-readable.html) by Nick Parlante - [Parlante's Basic Python Style Guide](https://cs.stanford.edu/people/nick/py/python-style-basics.html) - [Parlante's Readable Python Style Guide](https://cs.stanford.edu/people/nick/py/python-style-readable.html) note: - Good style is best practice - a `pattern` is like in fashion class, it's a code patter you want to imitate - `idomatic` is the one best way to do things (according to the Python core developers) - an `anti-pattern` is something you want to avoid --- ## pattern #### vs ## antipattern - a `pattern` is like in fashion class, it's a code patter you want to imitate - `idomatic` is the one best way to do things (according to the Python core developers) - an `antipattern` is something you want to avoid - Anyone have some patterns or antipatterns they want to share from the Zen of Python --- ## [PEP8 Names](https://peps.python.org/pep-0008/) - `PascalCase` - _class_ names (like `Turtle`) - `SCREAMING_SNAKE_CASE` - `global` constants - `_hidden_snake_case` better than `snake_case_hidden_` - `__system_object__` better than `__system_object` - `cammelCase` - ugly, tricky system functions (not for you!) - `snake_case` - everything else note: - You should not be creating new class names with `PascalCase` until end of course - Python libraries use `snake_case` for most global constants but some people like to use `SCREAMING_SNAKE_CASE` when they are really import (program level namespace) - You should never use `camelCase` in this course - Python students should always use `snake_case` --- ## [PEP8 Whitespace](https://peps.python.org/pep-0008/) - [ ] Indent with 4 spaces - [ ] Two newlines between function definitions - [ ] Two newlines below imports - [ ] Docstrings at top of functions and files --- ## [Readable Python](https://peps.python.org/pep-0008/) - [ ] Minimal comments (don't say the same thing as the code) - [ ] Self-documenting code - [ ] Active verbs for function names - [ ] Plural nouns for containers like `list`s - [ ] Math variables for math only - [ ] Words where practical - [ ] No uncommon abbreviations or acronyms --- ## [Reusable Python](https://peps.python.org/pep-0008/) - [ ] Simple functions that do one thing in `< 13` lines - [ ] Functions always return something useful to the caller --- #### ``__name__ == "__main__"`` pattern ```python >>> import math >>> def main(): ... answer = input('What is your name? ') ... print(f'Hi {answer}!') >>> if __name__ == '__main__': ... main() ``` note: - What is ``__name__``? - What is ``"__main__"``? - What is ``main()``? --- #### ``__name__ == "__main__"`` pattern ```python >>> import math >>> def f(x): ... return 0 + 1*x + 2*x**2 + 3*x**3 >>> def main(): ... x = float(input('Give me a number: ')) ... print(f'f({x}) is {f(x)}') >>> if __name__ == '__main__': ... main() ``` - What is ``__name__``? - What is ``"__main__"``? - What is ``main()``? --- #### ``__name__ == "__main__"`` pattern ```python >>> import math >>> def f(x): ... return 0 + 1*x + 2*x**2 + 3*x**3 >>> if __name__ == '__main__': ... main() ``` - ``__name__`` -- _runtime_ system variable containing the name of the module being run - ``"__main__"`` -- ``str`` literal name of the module -- name global namespace ``==`` **"\_\_main\_\_"** - What is ``main()`` -- a function you ``def``ined somewhere else in the code note: - I love the Python lets the programmer use these *RUNTIME* system variables - Using this pattern lets you run any module as a _program_ ( _script_ ) --- ## What's it for? ```python >>> import math >>> def f(x): ... return 0 + 1*x + 2*x**2 + 3*x**3 >>> if __name__ == '__main__': ... main() ``` #### Lets you run any _module_ as a _program_ ( _script_ ) #### Lets you import a _module_ without running it!!! /home/hobs/code/mesa_python/mesa_python/src/mesa/data/public/canvas/syllabus.pdf --- ## Lab Walk a turtle through this maze: [](./wk4/maze1.png) [./wk4/maze1.py](./wk4/maze1.py) Use the `__name__ == __main__` pattern! --- ## Use `stride` ### `stride` is the spacing between grid squares [](./wk4/maze2.png) [./wk4/maze2.py](./wk4/maze2.py) --- ## Blind turtle? What if Timmy can only feel walls left, forward and right? ```python >>> timmy.look_around() (1, 0, 1) >>> timmy.look_left() # wall_on_my_left() 1 >>> timmy.look_right() # wall_on_my_right() 1 >>> timmy.look_forward() # wall_in_front_of_me() 0 ``` --- ## FIXME: `maze2` blind? ```python >>> timmy.look() (1, 0, 1) >>> timmy.step_forward() (1, 0, 1) >>> timmy.step_forward() (1, 1, 0) >>> timmy.turn_right() (1, 0, 0) >>> timmy.step_forward() (1, 0, 1) ``` [./wk4/dark_maze.py](./wk4/dark_maze.py) note: - Naming functions hard --- ## [](https://www.nbcnews.com/tech/video-games/elon-musk-faces-gamers-wrath-path-exile-2-streams-rcna188030) 
Elon Musk, LA April 13, 2024 by Etienne Laurent (AFP) via Getty Images
--- ## [Gamer Musk](https://youtu.be/wlCCtrOCvu0) [](./wk4/musk-gamer-cringe.png)
Elon Musk, LA April 13, 2024 by Etienne Laurent (AFP) via Getty Images
--- ## [Manly Zuck](https://finance.yahoo.com/news/mark-zuckerberg-says-corporate-america-144742522.html) [](./wk4/zuck.png) --- ## Math `is` logic Math to decide whether to 👍 a [post](https://www.reddit.com/r/SelfDrivingCars/comments/1c2zdys/comment/kzftrut/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button) ```python funny = 1 cringe = -1 like = funny + cringe ``` --- ## Style guides - [Stanford's Python Style Guide](https://cs.stanford.edu/people/nick/py/python-style-readable.html) by Nick Parlante - [Parlante's Basic Python Style Guide](https://cs.stanford.edu/people/nick/py/python-style-basics.html) - [Parlante's Readable Python Style Guide](https://cs.stanford.edu/people/nick/py/python-style-readable.html) - [Clean [Python] Code](https://elpythonista.com/review-of-clean-code) by Bob Martin --- ### Links 1. [slides.nlpia.org](https://nlpia.org) 2. [starter code](./wk4/wk4.py) 3. [sdccd-edu.zoom.us/my/dlane](https://sdccd-edu.zoom.us/my/dlane) - Mon 10AM & 7PM 4. [astral.sh/uv](https://docs.astral.sh/uv/getting-started/installation/)