├── .gitignore ├── LICENSE ├── README.md ├── code-snippets ├── README.md └── pretty-json.sh └── exercises ├── README.md ├── exercise01.py ├── exercise02.py ├── exercise03.py ├── exercise04.py ├── exercise05.py ├── exercise06.py ├── exercise07.py ├── exercise08.py ├── exercise09.py ├── exercise10.py ├── exercise11.py ├── exercise12.py ├── exercise13.py ├── exercise14.py ├── exercise15.py ├── exercise15_data.txt ├── exercise16.py ├── exercise17.py ├── exercise17_data.txt ├── exercise18.py ├── exercise19.py ├── exercise20.py ├── exercise20_data.txt ├── exercise21.py ├── exercise22.py ├── exercise23.py ├── exercise24.py ├── exercise25.py ├── exercise26_broken.py ├── exercise26_fixed.py ├── exercise27.py ├── exercise28.py ├── exercise29.py ├── exercise30.py ├── exercise31.py ├── exercise32.py ├── exercise33.py ├── exercise34.py ├── exercise35.py ├── exercise36.py ├── exercise37.py ├── exercise38.py ├── exercise39.py ├── exercise40_1.py ├── exercise40_2.py ├── exercise40_3.py ├── exercise41.py ├── exercise42.py ├── exercise43.py ├── exercise44a.py ├── exercise44b.py ├── exercise45.py ├── exercise46 └── skeleton │ ├── NAME │ └── __init__.py │ ├── bin │ └── empty │ ├── docs │ └── empty │ ├── setup.py │ └── tests │ ├── NAME_tests.py │ └── __init__.py ├── exercise47 ├── bin │ └── empty ├── docs │ └── empty ├── exercise47 │ ├── __init__.py │ └── game.py ├── setup.py └── tests │ ├── exercise47_tests.py │ └── game_tests.py ├── exercise48 ├── bin │ └── empty ├── docs │ └── empty ├── exercise48 │ ├── __init__.py │ ├── lexicon.py │ └── parser.py ├── setup.py └── tests │ ├── __init__.py │ ├── lexicon_tests.py │ └── parser_tests.py ├── exercise50 └── gothonweb │ ├── bin │ └── app.py │ ├── gothonweb │ └── __init__.py │ ├── templates │ ├── hello_form.html │ ├── index.html │ └── layout.html │ └── tests │ ├── __init__.py │ ├── app_tests.py │ └── tools.py └── exercise52 ├── game ├── bin │ ├── app.py │ └── map.py ├── gothonweb │ └── __init__.py ├── templates │ ├── layout.html │ ├── show_room.html │ └── you_died.html └── tests │ └── map_tests.py └── gothonweb ├── bin └── app.py └── gothonweb └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | # bin/ # I want to include bin directory in this repository 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # Installer logs 26 | pip-log.txt 27 | pip-delete-this-directory.txt 28 | 29 | # Unit test / coverage reports 30 | htmlcov/ 31 | .tox/ 32 | .coverage 33 | .cache 34 | nosetests.xml 35 | coverage.xml 36 | 37 | # Translations 38 | *.mo 39 | 40 | # Mr Developer 41 | .mr.developer.cfg 42 | .project 43 | .pydevproject 44 | 45 | # Rope 46 | .ropeproject 47 | 48 | # Django stuff: 49 | *.log 50 | *.pot 51 | 52 | # Sphinx documentation 53 | docs/_build/ 54 | 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Piotr Wittchen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Learn Python - The Hard Way 2 | ========================= 3 | 4 | ### Overview 5 | 6 | Set of simple programs written during learning **basics of Python** language based on *[Learn Python - The Hard Way](http://learnpythonthehardway.org/book/)* course. All tasks can be found in *exercises* directory. In the same directory, we can found another `README.md` file including list of all tasks. Moreover, this `README.md` file includes **important and essential information concerning programming in Python**. You can also read [a short article about this project on my blog](http://wittchen.io/2015/09/01/learning-python/). 7 | 8 | ### Contents 9 | * [Requirements](#requirements) 10 | * [Installing Python](#installing-python) 11 | * [Executing Python scripts from terminal](#executing-python-scripts-from-terminal) 12 | * [Pip](#pip) 13 | * [Installing Pip on Windows](#installing-pip-on-windows) 14 | * [Installing Pip on Linux](#installing-pip-on-linux) 15 | * [Installing Pip on macOS](#installing-pip-on-macos) 16 | * [Using Pip](#using-pip) 17 | * [Unit Testing](#unit-testing) 18 | * [Virtualenv](#virtualenv) 19 | * [Pipenv](#pipenv) 20 | * [Pyenv](#pyenv) 21 | * [Scripts on Linux](#scripts-on-linux) 22 | * [Style Guide for Python Code](#style-guide-for-python-code) 23 | * [Static code analysis](#static-code-analysis) 24 | * [Development Environments](#development-environments) 25 | * [Python web frameworks](#python-web-frameworks) 26 | * [Useful Python libraries](#useful-python-libraries) 27 | * [Tools written in Python](#tools-written-in-python) 28 | * [Collections of tools written in Python](#collections-of-tools-written-in-python) 29 | * [Resources](#resources) 30 | * [Videos](#videos) 31 | * [Books](#books) 32 | * [License](#license) 33 | 34 | ### Requirements 35 | * Windows, Linux or Mac OS X 36 | * Python 2.7 37 | * Pip (Python Package Manager) 38 | 39 | ### Installing Python 40 | * on Linux: Most of the Linux distributions should have installed Python by default 41 | * on Windows: Download Python at: https://www.python.org/downloads/windows/ and run installer 42 | * on Mac OS X: Download Python at: https://www.python.org/downloads/mac-osx/ 43 | 44 | ### Executing Python scripts from terminal 45 | * on Linux: Most of the Linux distributions should have enabled Python by default, so simply open terminal and type *python* to see if everything works. 46 | * on Windows: add `/PythonXX` (e.g. `C:/Python27`) into `Path` environmental variable. Location of the Python directory depends on your configuration. Next, re-run terminal window and type `python` 47 | * in order to check installed version of the Python, type: `python --version` 48 | * in order to exit python console type `exit()` 49 | 50 | ### Pip 51 | Pip is a Python Package Manager. 52 | 53 | #### Installing Pip on Windows 54 | 1. Download: https://bootstrap.pypa.io/get-pip.py script 55 | 2. Execute: `python get-pip.py` 56 | 3. *pip.exe* and *easy_install.exe* files now should be located at: */PythonXX/Scripts* (e.g. *C:/Python27/Scripts*) 57 | 4. Add */PythonXX/Scripts* (e.g. *C:/Python27/Scripts*) directory into *Path* environmental variable. 58 | 5. Re-run terminal window 59 | 6. Type `pip`, to check if package manager works 60 | 7. You can type `pip --version`, in order to check version of the pip 61 | 62 | #### Installing Pip on Linux 63 | 1. Open terminal 64 | 2. Type `sudo apt-get install python-pip` 65 | 66 | #### Installing Pip on macOS 67 | 1. Open terminal 68 | 2. Type `brew install python3` 69 | 70 | This command will install python and pip. 71 | 72 | #### Using Pip 73 | * In order to install desired package just type `pip install desired_package` (e.g. `pip install Flask`) 74 | * If you are working on Linux, type `sudo pip install desired_package` (e.g. `sudo pip install Flask`) 75 | * Index of available packages can be found at: https://pypi.python.org/pypi/ 76 | * List of installed packages can be displayed with `pip freeze` command. 77 | 78 | ### Unit Testing 79 | * UT in Python can be done with [nose](https://pypi.python.org/pypi/nose/). Install it via pip with the following command: `sudo pip install nose` 80 | * UT can be also created with [unittest](https://docs.python.org/2/library/unittest.html) package provided with Python. 81 | 82 | ### Virtualenv 83 | 84 | `virtualenv` is a tool to create isolated Python environments. 85 | 86 | More information: 87 | * [Official docs and user guide](https://virtualenv.pypa.io/en/latest/) 88 | * [Overview on PyPi](https://pypi.python.org/pypi/virtualenv) 89 | * [Virtualenv tutorial](http://simononsoftware.com/virtualenv-tutorial/) 90 | * [A primer on virtualenv](http://iamzed.com/2009/05/07/a-primer-on-virtualenv/) 91 | * [Virtual Environments on Python Guide](http://docs.python-guide.org/en/latest/dev/virtualenvs/) 92 | 93 | ### Pipenv 94 | 95 | `pipenv` is Python Development Workflow for Humans. 96 | 97 | It automatically creates and manages a virtualenv for your projects, as well as adds/removes packages from your Pipfile as you install/uninstall packages. 98 | 99 | More information: 100 | * https://github.com/pypa/pipenv 101 | 102 | ### Pyenv 103 | 104 | [pyenv](https://github.com/pyenv/pyenv/) is a simple Python version management. 105 | 106 | ### Scripts on Linux 107 | 108 | If we want to create a Python script for Linux, we should set the following header: 109 | 110 | ```python 111 | #!/usr/bin/python -u 112 | 113 | # your Python script code goes here... 114 | ``` 115 | 116 | After that when our script was saved in `script.py` file, we can execute our script as follows: 117 | 118 | ``` 119 | ./script.py 120 | ``` 121 | 122 | ### Style Guide for Python Code 123 | 124 | **PEP 0008** is a current Style Guide for Python Code. 125 | 126 | link: https://www.python.org/dev/peps/pep-0008/ 127 | 128 | code style: https://docs.python-guide.org/writing/style/ 129 | 130 | ### Static Code Analysis 131 | 132 | - [Pylint](https://www.pylint.org/) 133 | - [Pytype (by Google)](https://github.com/google/pytype) 134 | - [Review of Python static code analysis tools](https://blog.codacy.com/review-of-python-static-analysis-tools-ff8e7e27f972) 135 | - [Awesome static analysis for Python](https://github.com/mre/awesome-static-analysis#python) 136 | 137 | ### Development Environments 138 | * [PyCharm](https://www.jetbrains.com/pycharm/) 139 | * [Sublime Text](http://www.sublimetext.com/) 140 | * [Atom](https://atom.io/) 141 | 142 | ### Python web frameworks 143 | * [Django](https://www.djangoproject.com/) 144 | * [Django Rest Framework](https://github.com/tomchristie/django-rest-framework) 145 | * [Silk - smooth profiling for Django](https://github.com/mtford90/silk) 146 | * [Flask](http://flask.pocoo.org/) 147 | * [Flask Restful](https://github.com/flask-restful/flask-restful) 148 | * [Flask Profiler](https://github.com/muatik/flask-profiler) 149 | * [Bottle](http://bottlepy.org/) 150 | * [Weppy](https://github.com/gi0baro/weppy) 151 | * [Growler](https://github.com/pyGrowler/Growler) 152 | 153 | ### Web servers 154 | * [Sanic - python 3.5+ web server that's written to go fast](https://github.com/channelcat/sanic) 155 | 156 | ### Useful Python libraries 157 | * [Requests - HTTP requests for humans](https://github.com/kennethreitz/requests) 158 | * [Httpie - CLI HTTP client](https://github.com/jkbrzt/httpie) 159 | * [Python Rex - regular expressions for humans](https://github.com/cypreess/python-rex) 160 | * [PythonVerbalExpressions - readable API for regular expressions](https://github.com/VerbalExpressions/PythonVerbalExpressions) 161 | * [Envelopes - mailing for human beings](https://github.com/tomekwojcik/envelopes) 162 | * [Tornado - web framework and asynchronous networking library](https://github.com/tornadoweb/tornado) 163 | * [Schedule - Python job scheduling for humans](https://github.com/dbader/schedule) 164 | * [Agate - data analysis for humans](https://github.com/onyxfish/agate) 165 | * [Gspread - Google Spreadsheets Python API](https://github.com/burnash/gspread) 166 | * [EFILTER (dotty) - a general-purpose destructuring and search language](https://github.com/google/dotty) 167 | * [Scrapy - web crawling & scraping framework](https://github.com/scrapy/scrapy) 168 | * [sh - Python process launching (allows you to call any program as if it were a function)](https://github.com/amoffat/sh) 169 | * [furl - url parsing and manipulation](https://github.com/gruns/furl) 170 | * [schedule - python job scheduling for humans](https://github.com/dbader/schedule/) 171 | 172 | ### Tools written in Python 173 | 174 | * [Wifite - an automated wireless attack tool](https://github.com/derv82/wifite) 175 | * [Glances - an Eye on your system](https://github.com/nicolargo/glances) 176 | * [Pidcat - colored and improved logcat for Android apps](https://github.com/JakeWharton/pidcat) 177 | * [Caffeine-plus - indicator preventing from turning screensaver/screenlock on](https://github.com/mildmojo/caffeine-plus) 178 | * [Spaceship generator - a script for Blender](https://github.com/a1studmuffin/SpaceshipGenerator) 179 | * [neighbourhood - Layer 2 network neighbourhood discovery tool that uses scapy](https://github.com/bwaldvogel/neighbourhood) 180 | * [Routersploit - The Router Exploitation Framework](https://github.com/reverse-shell/routersploit) 181 | * [scanless - port scanner](https://github.com/vesche/scanless) 182 | * [graph-cli - plot graphs out of csv files](https://github.com/mcastorina/graph-cli) 183 | 184 | ### Collections of tools written in Python 185 | * [Python Pentest Tools](https://github.com/dloss/python-pentest-tools) 186 | * [awesome-python - curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) 187 | * [one-python - best Python libraries](https://github.com/geekan/one-python) 188 | 189 | ### Resources 190 | * https://www.python.org/ 191 | * http://learnpythonthehardway.org/book/ 192 | * http://www.codecademy.com/en/tracks/python 193 | * http://www.diveintopython.net/ 194 | * https://github.com/kennethreitz/python-guide 195 | * http://www.pyvideo.org/speaker/138/raymond-hettinger 196 | * https://github.com/s16h/py-must-watch 197 | * http://pymust.watch/ 198 | * http://slides.com/fwkz/awesome-python 199 | * http://docs.python-guide.org/en/latest/ 200 | * https://github.com/bslatkin/effectivepython 201 | * https://github.com/kennethreitz/python-guide 202 | * https://github.com/Junnplus/awesome-python-books 203 | * https://github.com/crazyguitar/pysheeet 204 | * https://github.com/satwikkansal/wtfpython 205 | * https://mail.python.org/pipermail/python-list/1999-June/001951.html 206 | * https://github.com/trekhleb/learn-python 207 | * https://docs.python-guide.org/writing/style/ 208 | * https://realpython.com/ 209 | * https://python-for-system-administrators.readthedocs.io/en/latest/ 210 | * https://konradhalas.pl/articles/python-resources/ 211 | * https://github.com/machinelearningmindset/machine-learning-course 212 | 213 | ### Videos 214 | * [Transforming code into beautiful, idiomatic Python](https://www.youtube.com/watch?v=OSGv2VnC0go) 215 | 216 | ### Books 217 | * [Effective Python](http://www.effectivepython.com/) 218 | 219 | ### License 220 | MIT 221 | -------------------------------------------------------------------------------- /code-snippets/README.md: -------------------------------------------------------------------------------- 1 | Code snippets 2 | ------------- 3 | 4 | This directory contains simple, but useful code snippets for Python scripts and terminal tasks. 5 | 6 | List of code snippets 7 | --------------------- 8 | - pretty-json.sh - prints pretty json in terminal with Python 9 | -------------------------------------------------------------------------------- /code-snippets/pretty-json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # To print pretty JSON in terminal with Python 2.6+ you can just do: 4 | echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool 5 | -------------------------------------------------------------------------------- /exercises/README.md: -------------------------------------------------------------------------------- 1 | List of exercises 2 | ----------------- 3 | Based on [Learn Python - The Hard Way](http://learnpythonthehardway.org/book/). 4 | Number in the file name should correspond to appropriate exercise. 5 | - Exercise 0: The Setup 6 | - Exercise 1: A Good First Program 7 | - Exercise 2: Comments And Pound Characters 8 | - Exercise 3: Numbers And Math 9 | - Exercise 4: Variables And Names 10 | - Exercise 5: More Variables And Printing 11 | - Exercise 6: Strings And Text 12 | - Exercise 7: More Printing 13 | - Exercise 8: Printing, Printing 14 | - Exercise 9: Printing, Printing, Printing 15 | - Exercise 10: What Was That? 16 | - Exercise 11: Asking Questions 17 | - Exercise 12: Prompting People 18 | - Exercise 13: Parameters, Unpacking, Variables 19 | - Exercise 14: Prompting And Passing 20 | - Exercise 15: Reading Files 21 | - Exercise 16: Reading And Writing Files 22 | - Exercise 17: More Files 23 | - Exercise 18: Names, Variables, Code, Functions 24 | - Exercise 19: Functions And Variables 25 | - Exercise 20: Functions And Files 26 | - Exercise 21: Functions Can Return Something 27 | - Exercise 22: What Do You Know So Far? 28 | - Exercise 23: Read Some Code 29 | - Exercise 24: More Practice 30 | - Exercise 25: Even More Practice 31 | - Exercise 26: Congratulations, Take A Test! 32 | - Exercise 27: Memorizing Logic 33 | - Exercise 28: Boolean Practice 34 | - Exercise 29: What If 35 | - Exercise 30: Else And If 36 | - Exercise 31: Making Decisions 37 | - Exercise 32: Loops And Lists 38 | - Exercise 33: While Loops 39 | - Exercise 34: Accessing Elements Of Lists 40 | - Exercise 35: Branches and Functions 41 | - Exercise 36: Designing and Debugging 42 | - Exercise 37: Symbol Review 43 | - Exercise 38: Doing Things To Lists 44 | - Exercise 39: Dictionaries, Oh Lovely Dictionaries 45 | - Exercise 40: Modules, Classes, And Objects 46 | - Exercise 41: Learning To Speak Object Oriented 47 | - Exercise 42: Is-A, Has-A, Objects, and Classes 48 | - Exercise 43: Gothons From Planet Percal #25 49 | - Exercise 44: Inheritance Vs. Composition 50 | - Exercise 45: You Make A Game 51 | - Exercise 46: A Project Skeleton 52 | - Exercise 47: Automated Testing 53 | - Exercise 48: Advanced User Input 54 | - Exercise 49: Making Sentences 55 | - Exercise 50: Your First Website 56 | - Exercise 51: Getting Input From A Browser 57 | - Exercise 52: The Start Of Your Web Game 58 | -------------------------------------------------------------------------------- /exercises/exercise01.py: -------------------------------------------------------------------------------- 1 | # Exercise 1: A Good First Program 2 | print "Hello World!" 3 | -------------------------------------------------------------------------------- /exercises/exercise02.py: -------------------------------------------------------------------------------- 1 | # Exercise 2: Comments 2 | print "Hello World!" 3 | #single line comment 4 | """multiple 5 | lines 6 | comment""" 7 | -------------------------------------------------------------------------------- /exercises/exercise03.py: -------------------------------------------------------------------------------- 1 | # Exercise 3: Numbers and Math 2 | print "I will now count my chickens:" 3 | 4 | print "Hens", 25 + 30 / 6 5 | print "Roosters", 100 - 25 * 3 % 4 6 | 7 | print "Now I will count the eggs:" 8 | 9 | print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 10 | 11 | print "Is it true that 3 + 2 < 5 - 7?" 12 | 13 | print 3 + 2 < 5 - 7 14 | 15 | print "What is 3 + 2?", 3 + 2 16 | print "What is 5 - 7?", 5 - 7 17 | 18 | print "Oh, that's why it's False." 19 | 20 | print "How about some more." 21 | 22 | print "Is it greater?", 5 > -2 23 | print "Is it greater or equal?", 5 >= -2 24 | print "Is it less or equal?", 5 <= -2 25 | -------------------------------------------------------------------------------- /exercises/exercise04.py: -------------------------------------------------------------------------------- 1 | # Exercise 4: Variables And Names 2 | cars = 100 3 | space_in_a_car = 4.0 4 | drivers = 30 5 | passengers = 90 6 | cars_not_driven = cars - drivers 7 | cars_driven = drivers 8 | carpool_capacity = cars_driven * space_in_a_car 9 | average_passengers_per_car = passengers / cars_driven 10 | 11 | 12 | print "There are", cars, "cars available." 13 | print "There are only", drivers, "drivers available." 14 | print "There will be", cars_not_driven, "empty cars today." 15 | print "We can transport", carpool_capacity, "people today." 16 | print "We have", passengers, "to carpool today." 17 | print "We need to put about", average_passengers_per_car, "in each car." 18 | -------------------------------------------------------------------------------- /exercises/exercise05.py: -------------------------------------------------------------------------------- 1 | # Exercise 5: More Variables and Printing 2 | # -- coding: utf-8 -- 3 | my_name = 'Zed A. Shaw' 4 | my_age = 35 # not a lie 5 | my_height = 74 # inches 6 | my_weight = 180 # lbs 7 | my_eyes = 'Blue' 8 | my_teeth = 'White' 9 | my_hair = 'Brown' 10 | 11 | print "Let's talk about %s." % my_name 12 | print "He's %d inches tall." % my_height 13 | print "He's %d pounds heavy." % my_weight 14 | print "Actually that's not too heavy." 15 | print "He's got %s eyes and %s hair." % (my_eyes, my_hair) 16 | print "His teeth are usually %s depending on the coffee." % my_teeth 17 | 18 | # this line is tricky, try to get it exactly right 19 | print "If I add %d, %d, and %d I get %d." % ( 20 | my_age, my_height, my_weight, my_age + my_height + my_weight) 21 | -------------------------------------------------------------------------------- /exercises/exercise06.py: -------------------------------------------------------------------------------- 1 | # Exercise 6: Strings and Text 2 | x = "There are %d types of people." % 10 3 | binary = "binary" 4 | do_not = "don't" 5 | y = "Those who know %s and those who %s." % (binary, do_not) 6 | 7 | print x 8 | print y 9 | 10 | print "I said: %r." % x # %r stands for "raw" input data 11 | print "I also said: '%s'." % y 12 | 13 | hilarious = False 14 | joke_evaluation = "Isn't that joke so funny?! %r" 15 | 16 | print joke_evaluation % hilarious 17 | 18 | w = "This is the left side of..." 19 | e = "a string with a right side." 20 | 21 | print w + e 22 | -------------------------------------------------------------------------------- /exercises/exercise07.py: -------------------------------------------------------------------------------- 1 | # Exercise 7: More Printing 2 | print "Mary had a little lamb." 3 | print "Its fleece was white as %s." % 'snow' 4 | print "And everywhere that Mary went." 5 | print "." * 10 # what'd that do? 6 | 7 | end1 = "C" 8 | end2 = "h" 9 | end3 = "e" 10 | end4 = "e" 11 | end5 = "s" 12 | end6 = "e" 13 | end7 = "B" 14 | end8 = "u" 15 | end9 = "r" 16 | end10 = "g" 17 | end11 = "e" 18 | end12 = "r" 19 | 20 | # watch that comma at the end. try removing it to see what happens 21 | print end1 + end2 + end3 + end4 + end5 + end6, 22 | print end7 + end8 + end9 + end10 + end11 + end12 23 | 24 | #print end1 + end2 + end3 + end4 + end5 + end6 25 | #print end7 + end8 + end9 + end10 + end11 + end1274 26 | 27 | -------------------------------------------------------------------------------- /exercises/exercise08.py: -------------------------------------------------------------------------------- 1 | # Exercise 8: Printing, printing 2 | formatter = "%r %r %r %r" 3 | 4 | print formatter % (1, 2, 3, 4) 5 | print formatter % ("one", "two", "three", "four") 6 | print formatter % (True, False, False, True) 7 | print formatter % (formatter, formatter, formatter, formatter) 8 | print formatter % ( 9 | "I had this thing.", 10 | "That you could type up right.", 11 | "But it didn't sing.", 12 | "So I said goodnight." 13 | ) -------------------------------------------------------------------------------- /exercises/exercise09.py: -------------------------------------------------------------------------------- 1 | # Exercise 9: Printing, printing, printing 2 | # Here's some new strange stuff, remember type it exactly. 3 | 4 | days = "Mon Tue Wed Thu Fri Sat Sun" 5 | months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" 6 | 7 | print "Here are the days: ", days 8 | print "Here are the months: ", months 9 | 10 | print """ 11 | There's something going on here. 12 | With the three double-quotes. 13 | We'll be able to type as much as we like. 14 | Even 4 lines if we want, or 5, or 6. 15 | """ -------------------------------------------------------------------------------- /exercises/exercise10.py: -------------------------------------------------------------------------------- 1 | # Exercise 10: What Was That? 2 | 3 | print "I am 6'2\" tall." # escape double-quote inside string 4 | print 'I am 6\'2" tall.' # escape single-quote inside string 5 | 6 | tabby_cat = "\tI'm tabbed in." 7 | persian_cat = "I'm split\non a line." 8 | backslash_cat = "I'm \\ a \\ cat." 9 | 10 | fat_cat = """ 11 | I'll do a list: 12 | \t* Cat food 13 | \t* Fishies 14 | \t* Catnip\n\t* Grass 15 | """ 16 | 17 | print tabby_cat 18 | print persian_cat 19 | print backslash_cat 20 | print fat_cat 21 | 22 | #uncomment while instruction below, run it and see what happens! 23 | 24 | """ 25 | while True: 26 | for i in ["/","-","|","\\","|"]: 27 | print "%s\r" % i, 28 | """ 29 | 30 | # Escape Sequences 31 | 32 | # Escape What it does 33 | #=========================== 34 | #\\ Backslash () 35 | #\' Single-quote (') 36 | #\" Double-quote (") 37 | #\a ASCII bell (BEL) 38 | #\b ASCII backspace (BS) 39 | #\f ASCII formfeed (FF) 40 | #\n ASCII linefeed (LF) 41 | #\N{name} Character named name in the Unicode database (Unicode only) 42 | #\r ASCII Carriage Return (CR) 43 | #\t ASCII Horizontal Tab (TAB) 44 | #\uxxxx Character with 16-bit hex value xxxx (Unicode only) 45 | #\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) 46 | #\v ASCII vertical tab (VT) 47 | #\ooo Character with octal value ooo 48 | #\xhh Character with hex value hh 49 | -------------------------------------------------------------------------------- /exercises/exercise11.py: -------------------------------------------------------------------------------- 1 | # Exercise 11: Asking questions and reading input 2 | 3 | print "How old are you?", 4 | age = raw_input() 5 | print "How tall are you (in cm)?", 6 | height = raw_input() 7 | print "How much do you weigh (in kg)?", 8 | weight = raw_input() 9 | 10 | print "So, you're %r-years old, %r cm tall and %r kg heavy." % (age, height, weight) -------------------------------------------------------------------------------- /exercises/exercise12.py: -------------------------------------------------------------------------------- 1 | # Exercise 12: Prompting people 2 | 3 | age = raw_input("How old are you? ") 4 | height = raw_input("How tall are you? ") 5 | weight = raw_input("How much do you weigh? ") 6 | 7 | print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) -------------------------------------------------------------------------------- /exercises/exercise13.py: -------------------------------------------------------------------------------- 1 | # Exercise 13: Parameters, Unpacking, Variables 2 | 3 | from sys import argv 4 | 5 | script, first, second, third = argv 6 | 7 | print "The script is called:", script 8 | print "Your first variable is:", first 9 | print "Your second variable is:", second 10 | print "Your third variable is:", third 11 | 12 | # from terminal window run e.g.: 13 | # python exercise13.py a b c -------------------------------------------------------------------------------- /exercises/exercise14.py: -------------------------------------------------------------------------------- 1 | # Exercise 14: Prompting and Passing 2 | 3 | from sys import argv 4 | 5 | script, user_name = argv 6 | prompt = '> ' 7 | 8 | print "Hi %s, I'm the %s script." % (user_name, script) 9 | print "I'd like to ask you a few questions." 10 | print "Do you like me %s?" % user_name 11 | likes = raw_input(prompt) 12 | 13 | print "Where do you live %s?" % user_name 14 | lives = raw_input(prompt) 15 | 16 | print "What kind of computer do you have?" 17 | computer = raw_input(prompt) 18 | 19 | print """ 20 | Alright, so you said %r about liking me. 21 | You live in %r. Not sure where that is. 22 | And you have a %r computer. Nice. 23 | """ % (likes, lives, computer) 24 | 25 | # You can run the script with e.g. the following command: 26 | # python exercise14.py zed -------------------------------------------------------------------------------- /exercises/exercise15.py: -------------------------------------------------------------------------------- 1 | # Exercise 15: Reading files 2 | from sys import argv 3 | 4 | script, filename = argv 5 | 6 | txt = open(filename) 7 | 8 | print "Here's your file %r:" % filename 9 | print txt.read() 10 | txt.close() 11 | 12 | print "Type the filename again:" 13 | file_again = raw_input("> ") 14 | 15 | txt_again = open(file_again) 16 | 17 | print txt_again.read() 18 | txt.close() 19 | 20 | # in order to read file named exercise15_data.txt run the following command: 21 | # python exercise15.py exercise15_data.txt -------------------------------------------------------------------------------- /exercises/exercise15_data.txt: -------------------------------------------------------------------------------- 1 | This is stuff I typed into a file. 2 | It is really cool stuff. 3 | Lots and lots of fun to have in here. -------------------------------------------------------------------------------- /exercises/exercise16.py: -------------------------------------------------------------------------------- 1 | # Exercise 16: Reading and Writing Files 2 | from sys import argv 3 | 4 | script, filename = argv 5 | 6 | print "We're going to erase %r." % filename 7 | print "If you don't want that, hit CTRL-C (^C)." 8 | print "If you do want that, hit RETURN." 9 | 10 | raw_input("?") 11 | 12 | print "Opening the file..." 13 | target = open(filename, 'w') 14 | 15 | print "Truncating the file. Goodbye!" 16 | target.truncate() 17 | 18 | print "Now I'm going to ask you for three lines." 19 | 20 | line1 = raw_input("line 1: ") 21 | line2 = raw_input("line 2: ") 22 | line3 = raw_input("line 3: ") 23 | 24 | print "I'm going to write these to the file." 25 | 26 | target.write(line1) 27 | target.write("\n") 28 | target.write(line2) 29 | target.write("\n") 30 | target.write(line3) 31 | target.write("\n") 32 | 33 | print "And finally, we close it." 34 | target.close() 35 | 36 | # script can be executed from the terminal in the following way: 37 | # python exercise16.py exercise16_data.txt -------------------------------------------------------------------------------- /exercises/exercise17.py: -------------------------------------------------------------------------------- 1 | # Exercise 17: More files 2 | 3 | from sys import argv 4 | from os.path import exists 5 | 6 | script, from_file, to_file = argv 7 | 8 | print "Copying from %s to %s" % (from_file, to_file) 9 | 10 | # we could do these two on one line too, how? 11 | # indata = open(from_file).read() # probably, like that 12 | in_file = open(from_file) 13 | indata = in_file.read() 14 | 15 | print "The input file is %d bytes long" % len(indata) 16 | 17 | print "Does the output file exist? %r" % exists(to_file) 18 | print "Ready, hit RETURN to continue, CTRL-C to abort." 19 | raw_input() 20 | 21 | out_file = open(to_file, 'w') 22 | out_file.write(indata) 23 | 24 | print "Alright, all done." 25 | 26 | out_file.close() 27 | in_file.close() -------------------------------------------------------------------------------- /exercises/exercise17_data.txt: -------------------------------------------------------------------------------- 1 | Sample data for exercise17 2 | -------------------------------------------------------------------------------- /exercises/exercise18.py: -------------------------------------------------------------------------------- 1 | # Exercise 18: Names, Variables, Code, Functions 2 | 3 | # this one is like your scripts with argv 4 | def print_two(*args): 5 | arg1, arg2 = args 6 | print "arg1: %r, arg2: %r" % (arg1, arg2) 7 | 8 | # ok, that *args is actually pointless, we can just do this 9 | def print_two_again(arg1, arg2): 10 | print "arg1: %r, arg2: %r" % (arg1, arg2) 11 | 12 | # this just takes one argument 13 | def print_one(arg1): 14 | print "arg1: %r" % arg1 15 | 16 | # this one takes no arguments 17 | def print_none(): 18 | print "I got nothin'." 19 | 20 | 21 | print_two("Zed","Shaw") 22 | print_two_again("Zed","Shaw") 23 | print_one("First!") 24 | print_none() -------------------------------------------------------------------------------- /exercises/exercise19.py: -------------------------------------------------------------------------------- 1 | # Exercise 19: Functions and Variables 2 | 3 | def cheese_and_crackers(cheese_count, boxes_of_crackers): 4 | print "You have %d cheeses!" % cheese_count 5 | print "You have %d boxes of crackers!" % boxes_of_crackers 6 | print "Man that's enough for a party!" 7 | print "Get a blanket.\n" 8 | 9 | 10 | print "We can just give the function numbers directly:" 11 | cheese_and_crackers(20, 30) 12 | 13 | 14 | print "OR, we can use variables from our script:" 15 | amount_of_cheese = 10 16 | amount_of_crackers = 50 17 | 18 | cheese_and_crackers(amount_of_cheese, amount_of_crackers) 19 | 20 | 21 | print "We can even do math inside too:" 22 | cheese_and_crackers(10 + 20, 5 + 6) 23 | 24 | 25 | print "And we can combine the two, variables and math:" 26 | cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) 27 | -------------------------------------------------------------------------------- /exercises/exercise20.py: -------------------------------------------------------------------------------- 1 | # Exercise 20: Functions and Files 2 | 3 | from sys import argv 4 | 5 | script, input_file = argv 6 | 7 | def print_all(f): 8 | print f.read() 9 | 10 | def rewind(f): 11 | f.seek(0) 12 | 13 | def print_a_line(line_count, f): 14 | print line_count, f.readline() 15 | 16 | current_file = open(input_file) 17 | 18 | print "First let's print the whole file:\n" 19 | 20 | print_all(current_file) 21 | 22 | print "Now let's rewind, kind of like a tape." 23 | 24 | rewind(current_file) 25 | 26 | print "Let's print three lines:" 27 | 28 | current_line = 1 29 | print_a_line(current_line, current_file) 30 | 31 | current_line = current_line + 1 32 | print_a_line(current_line, current_file) 33 | 34 | current_line = current_line + 1 35 | print_a_line(current_line, current_file) 36 | -------------------------------------------------------------------------------- /exercises/exercise20_data.txt: -------------------------------------------------------------------------------- 1 | This is line 1 2 | This is line 2 3 | This is line 3 4 | -------------------------------------------------------------------------------- /exercises/exercise21.py: -------------------------------------------------------------------------------- 1 | # Exercise 21: Functions Can Return Something 2 | 3 | def add(a, b): 4 | print "ADDING %d + %d" % (a, b) 5 | return a + b 6 | 7 | def subtract(a, b): 8 | print "SUBTRACTING %d - %d" % (a, b) 9 | return a - b 10 | 11 | def multiply(a, b): 12 | print "MULTIPLYING %d * %d" % (a, b) 13 | return a * b 14 | 15 | def divide(a, b): 16 | print "DIVIDING %d / %d" % (a, b) 17 | return a / b 18 | 19 | 20 | print "Let's do some math with just functions!" 21 | 22 | age = add(30, 5) 23 | height = subtract(78, 4) 24 | weight = multiply(90, 2) 25 | iq = divide(100, 2) 26 | 27 | print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) 28 | 29 | 30 | # A puzzle for the extra credit, type it in anyway. 31 | print "Here is a puzzle." 32 | 33 | what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) 34 | 35 | print "That becomes: ", what, "Can you do it by hand?" 36 | -------------------------------------------------------------------------------- /exercises/exercise22.py: -------------------------------------------------------------------------------- 1 | # Exercise 22: What Do You Know So Far? 2 | # No code 3 | # Read: http://learnpythonthehardway.org/book/ex22.html 4 | -------------------------------------------------------------------------------- /exercises/exercise23.py: -------------------------------------------------------------------------------- 1 | # Exercise 23: Read Some Code 2 | # No code 3 | # Read: http://learnpythonthehardway.org/book/ex23.html 4 | -------------------------------------------------------------------------------- /exercises/exercise24.py: -------------------------------------------------------------------------------- 1 | # Exercise 24: More Practice 2 | print "Let's practice everything." 3 | print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' 4 | 5 | poem = """ 6 | \tThe lovely world 7 | with logic so firmly planted 8 | cannot discern \n the needs of love 9 | nor comprehend passion from intuition 10 | and requires an explanation 11 | \n\t\twhere there is none. 12 | """ 13 | 14 | print "--------------" 15 | print poem 16 | print "--------------" 17 | 18 | 19 | five = 10 - 2 + 3 - 6 20 | print "This should be five: %s" % five 21 | 22 | def secret_formula(started): 23 | jelly_beans = started * 500 24 | jars = jelly_beans / 1000 25 | crates = jars / 100 26 | return jelly_beans, jars, crates 27 | 28 | 29 | start_point = 10000 30 | beans, jars, crates = secret_formula(start_point) 31 | 32 | print "With a starting point of: %d" % start_point 33 | print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 34 | 35 | start_point = start_point / 10 36 | 37 | print "We can also do that this way:" 38 | print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) 39 | -------------------------------------------------------------------------------- /exercises/exercise25.py: -------------------------------------------------------------------------------- 1 | # Exercise 25: Even More Practice 2 | def break_words(stuff): 3 | """This function will break up words for us.""" 4 | words = stuff.split(' ') 5 | return words 6 | 7 | def sort_words(words): 8 | """Sorts the words.""" 9 | return sorted(words) 10 | 11 | def print_first_word(words): 12 | """Prints the first word after popping it off.""" 13 | word = words.pop(0) 14 | print word 15 | 16 | def print_last_word(words): 17 | """Prints the last word after popping it off.""" 18 | word = words.pop(-1) 19 | print word 20 | 21 | def sort_sentence(sentence): 22 | """Takes in a full sentence and returns the sorted words.""" 23 | words = break_words(sentence) 24 | return sort_words(words) 25 | 26 | def print_first_and_last(sentence): 27 | """Prints the first and last words of the sentence.""" 28 | words = break_words(sentence) 29 | print_first_word(words) 30 | print_last_word(words) 31 | 32 | def print_first_and_last_sorted(sentence): 33 | """Sorts the words then prints the first and last one.""" 34 | words = sort_sentence(sentence) 35 | print_first_word(words) 36 | print_last_word(words) 37 | 38 | # output of the training performed in terminal is available below 39 | 40 | """ 41 | $ python 42 | Python 2.7.6 (default, Mar 22 2014, 22:59:56) 43 | [GCC 4.8.2] on linux2 44 | Type "help", "copyright", "credits" or "license" for more information. 45 | >>> import exercise25 46 | >>> sentence = "All good things come to those who wait" 47 | >>> words = exercise25.break_words(sentence) 48 | >>> words 49 | ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait'] 50 | >>> sorted_words = exercise25.sort_words(words) 51 | >>> sorted_words 52 | ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who'] 53 | >>> exercise25.print_first_word(words) 54 | All 55 | >>> exercise25.print_last_word(words) 56 | wait 57 | >>> words 58 | ['good', 'things', 'come', 'to', 'those', 'who'] 59 | >>> exercise25.print_first_word(sorted_words) 60 | All 61 | >>> exercise25.print_last_word(sorted_words) 62 | who 63 | >>> sorted_words 64 | ['come', 'good', 'things', 'those', 'to', 'wait'] 65 | >>> sorted_words = exercise25.sort_sentence(sentence) 66 | >>> sorted_words 67 | ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who'] 68 | >>> exercise25.print_first_and_last(sentence) 69 | All 70 | wait 71 | >>> exercise25.print_first_and_last_sorted(sentence) 72 | All 73 | who 74 | >>> 75 | $ python 76 | Python 2.7.6 (default, Mar 22 2014, 22:59:56) 77 | [GCC 4.8.2] on linux2 78 | Type "help", "copyright", "credits" or "license" for more information. 79 | >>> import exercise25 80 | >>> sentence = "All good things come to those who wait" 81 | >>> words = exercise25.break_words(sentence) 82 | >>> words 83 | ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait'] 84 | >>> sorted_words = exercise25.sort_words(words) 85 | >>> sorted_words 86 | ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who'] 87 | >>> exercise25.print_first_word(words) 88 | All 89 | >>> exercise25.print_last_word(words) 90 | wait 91 | >>> words 92 | ['good', 'things', 'come', 'to', 'those', 'who'] 93 | >>> exercise25.print_first_word(sorted_words) 94 | All 95 | >>> exercise25.print_last_word(sorted_words) 96 | who 97 | >>> sorted_words 98 | ['come', 'good', 'things', 'those', 'to', 'wait'] 99 | >>> sorted_words = exercise25.sort_sentence(sentence) 100 | >>> sorted_words 101 | ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who'] 102 | >>> exercise25.print_first_and_last(sentence) 103 | All 104 | wait 105 | >>> exercise25.print_first_and_last_sorted(sentence) 106 | All 107 | who 108 | """ 109 | -------------------------------------------------------------------------------- /exercises/exercise26_broken.py: -------------------------------------------------------------------------------- 1 | # Exercise 26: Test - this code is broken 2 | # Fixed version of this code is going to be in exercise26_fixed.py 3 | 4 | def break_words(stuff): 5 | """This function will break up words for us.""" 6 | words = stuff.split(' ') 7 | return words 8 | 9 | def sort_words(words): 10 | """Sorts the words.""" 11 | return sorted(words) 12 | 13 | def print_first_word(words) 14 | """Prints the first word after popping it off.""" 15 | word = words.poop(0) 16 | print word 17 | 18 | def print_last_word(words): 19 | """Prints the last word after popping it off.""" 20 | word = words.pop(-1 21 | print word 22 | 23 | def sort_sentence(sentence): 24 | """Takes in a full sentence and returns the sorted words.""" 25 | words = break_words(sentence) 26 | return sort_words(words) 27 | 28 | def print_first_and_last(sentence): 29 | """Prints the first and last words of the sentence.""" 30 | words = break_words(sentence) 31 | print_first_word(words) 32 | print_last_word(words) 33 | 34 | def print_first_and_last_sorted(sentence): 35 | """Sorts the words then prints the first and last one.""" 36 | words = sort_sentence(sentence) 37 | print_first_word(words) 38 | print_last_word(words) 39 | 40 | 41 | print "Let's practice everything." 42 | print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' 43 | 44 | poem = """ 45 | \tThe lovely world 46 | with logic so firmly planted 47 | cannot discern \n the needs of love 48 | nor comprehend passion from intuition 49 | and requires an explantion 50 | \n\t\twhere there is none. 51 | """ 52 | 53 | 54 | print "--------------" 55 | print poem 56 | print "--------------" 57 | 58 | five = 10 - 2 + 3 - 5 59 | print "This should be five: %s" % five 60 | 61 | def secret_formula(started): 62 | jelly_beans = started * 500 63 | jars = jelly_beans \ 1000 64 | crates = jars / 100 65 | return jelly_beans, jars, crates 66 | 67 | 68 | start_point = 10000 69 | beans, jars, crates == secret_formula(start-point) 70 | 71 | print "With a starting point of: %d" % start_point 72 | print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates) 73 | 74 | start_point = start_point / 10 75 | 76 | print "We can also do that this way:" 77 | print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_pont 78 | 79 | 80 | sentence = "All god\tthings come to those who weight." 81 | 82 | words = ex25.break_words(sentence) 83 | sorted_words = ex25.sort_words(words) 84 | 85 | print_first_word(words) 86 | print_last_word(words) 87 | .print_first_word(sorted_words) 88 | print_last_word(sorted_words) 89 | sorted_words = ex25.sort_sentence(sentence) 90 | prin sorted_words 91 | 92 | print_irst_and_last(sentence) 93 | 94 | print_first_a_last_sorted(senence) 95 | exer 96 | -------------------------------------------------------------------------------- /exercises/exercise26_fixed.py: -------------------------------------------------------------------------------- 1 | # Exercise 26: Test - this code is fixed 2 | # Fixed version of exercise26_broken.py script 3 | 4 | import exercise25 5 | 6 | def break_words(stuff): 7 | """This function will break up words for us.""" 8 | words = stuff.split(' ') 9 | return words 10 | 11 | def sort_words(words): 12 | """Sorts the words.""" 13 | return sorted(words) 14 | 15 | def print_first_word(words): 16 | """Prints the first word after popping it off.""" 17 | word = words.pop(0) 18 | print word 19 | 20 | def print_last_word(words): 21 | """Prints the last word after popping it off.""" 22 | word = words.pop(-1) 23 | print word 24 | 25 | def sort_sentence(sentence): 26 | """Takes in a full sentence and returns the sorted words.""" 27 | words = break_words(sentence) 28 | return sort_words(words) 29 | 30 | def print_first_and_last(sentence): 31 | """Prints the first and last words of the sentence.""" 32 | words = break_words(sentence) 33 | print_first_word(words) 34 | print_last_word(words) 35 | 36 | def print_first_and_last_sorted(sentence): 37 | """Sorts the words then prints the first and last one.""" 38 | words = sort_sentence(sentence) 39 | print_first_word(words) 40 | print_last_word(words) 41 | 42 | 43 | print "Let's practice everything." 44 | print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' 45 | 46 | poem = """ 47 | \tThe lovely world 48 | with logic so firmly planted 49 | cannot discern \nthe needs of love 50 | nor comprehend passion from intuition 51 | and requires an explantion 52 | \n\t\twhere there is none. 53 | """ 54 | 55 | 56 | print "--------------" 57 | print poem 58 | print "--------------" 59 | 60 | five = 10 - 2 + 3 - 6 61 | print "This should be five: %s" % five 62 | 63 | def secret_formula(started): 64 | beans = started * 500 65 | jars = beans / 1000 66 | crates = jars / 100 67 | return beans, jars, crates 68 | 69 | 70 | start_point = 10000 71 | beans, jars, crates = secret_formula(start_point) 72 | 73 | print "With a starting point of: %d" % start_point 74 | print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 75 | 76 | start_point = start_point / 10 77 | 78 | print "We can also do that this way:" 79 | print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) 80 | 81 | 82 | sentence = "All good\tthings come to those who wait." 83 | 84 | words = exercise25.break_words(sentence) 85 | sorted_words = exercise25.sort_words(words) 86 | 87 | print_first_word(words) 88 | print_last_word(words) 89 | print_first_word(sorted_words) 90 | print_last_word(sorted_words) 91 | sorted_words = exercise25.sort_sentence(sentence) 92 | print sorted_words 93 | 94 | print_first_and_last(sentence) 95 | print_first_and_last_sorted(sentence) 96 | -------------------------------------------------------------------------------- /exercises/exercise27.py: -------------------------------------------------------------------------------- 1 | # Exercise 27: Memorizing logic 2 | # No code 3 | # Read: http://learnpythonthehardway.org/book/ex27.html 4 | -------------------------------------------------------------------------------- /exercises/exercise28.py: -------------------------------------------------------------------------------- 1 | # Exercise 28: Boolean practice 2 | 3 | print True and True 4 | print False and True 5 | print 1 == 1 and 2 == 1 6 | print "test" == "test" 7 | print 1 == 1 or 2 != 1 8 | print True and 1 == 1 9 | print False and 0 != 0 10 | print True or 1 == 1 11 | print "test" == "testing" 12 | print 1 != 0 and 2 == 1 13 | print "test" != "testing" 14 | print "test" == 1 15 | print not (True and False) 16 | print not (1 == 1 and 0 != 1) 17 | print not (10 == 1 or 1000 == 1000) 18 | print not (1 != 10 or 3 == 4) 19 | print not ("testing" == "testing" and "Zed" == "Cool Guy") 20 | print 1 == 1 and (not ("testing" == 1 or 1 == 0)) 21 | print "chunky" == "bacon" and (not (3 == 4 or 3 == 3)) 22 | print 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")) 23 | -------------------------------------------------------------------------------- /exercises/exercise29.py: -------------------------------------------------------------------------------- 1 | # Exercise 29: What if 2 | 3 | people = 20 4 | cats = 30 5 | dogs = 15 6 | 7 | if people < cats: 8 | print "Too many cats! The world is doomed!" 9 | 10 | if people > cats: 11 | print "Not many cats! The world is saved!" 12 | 13 | if people < dogs: 14 | print "The world is drooled on!" 15 | 16 | if people > dogs: 17 | print "The world is dry!" 18 | 19 | dogs += 5 20 | 21 | if people >= dogs: 22 | print "People are greater than or equal to dogs." 23 | 24 | if people <= dogs: 25 | print "People are less than or equal to dogs." 26 | 27 | if people == dogs: 28 | print "People are dogs." 29 | -------------------------------------------------------------------------------- /exercises/exercise30.py: -------------------------------------------------------------------------------- 1 | # Exercise 30: Else and if 2 | 3 | people = 30 4 | cars = 40 5 | trucks = 15 6 | 7 | if cars > people: 8 | print "We should take the cars." 9 | elif cars < people: 10 | print "We should not take the cars." 11 | else: 12 | print "We can't decide." 13 | 14 | if trucks > cars: 15 | print "That's too many trucks." 16 | elif trucks < cars: 17 | print "Maybe we could take the trucks." 18 | else: 19 | print "We still can't decide." 20 | 21 | if people > trucks: 22 | print "Alright, let's just take the trucks." 23 | else: 24 | print "Fine, let's stay home then." 25 | -------------------------------------------------------------------------------- /exercises/exercise31.py: -------------------------------------------------------------------------------- 1 | # Exercise 31: Making decisions 2 | 3 | print "You enter a dark room with two doors. Do you go through door #1 or door #2?" 4 | 5 | door = raw_input("> ") 6 | 7 | if door == "1": 8 | print "There's a giant bear here eating a cheese cake. What do you do?" 9 | print "1. Take the cake." 10 | print "2. Scream at the bear." 11 | 12 | bear = raw_input("> ") 13 | 14 | if bear == "1": 15 | print "The bear eats your face off. Good job!" 16 | elif bear == "2": 17 | print "The bear eats your legs off. Good job!" 18 | else: 19 | print "Well, doing %s is probably better. Bear runs away." % bear 20 | 21 | elif door == "2": 22 | print "You stare into the endless abyss at Cthulhu's retina." 23 | print "1. Blueberries." 24 | print "2. Yellow jacket clothespins." 25 | print "3. Understanding revolvers yelling melodies." 26 | 27 | insanity = raw_input("> ") 28 | 29 | if insanity == "1" or insanity == "2": 30 | print "Your body survives powered by a mind of jello. Good job!" 31 | else: 32 | print "The insanity rots your eyes into a pool of muck. Good job!" 33 | 34 | else: 35 | print "You stumble around and fall on a knife and die. Good job!" 36 | -------------------------------------------------------------------------------- /exercises/exercise32.py: -------------------------------------------------------------------------------- 1 | # Exercise 32: Loops and lists 2 | 3 | the_count = [1, 2, 3, 4, 5] 4 | fruits = ['apples', 'oranges', 'pears', 'apricots'] 5 | change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] 6 | 7 | # this first kind of for-loop goes through a list 8 | for number in the_count: 9 | print "This is count %d" % number 10 | 11 | # same as above 12 | for fruit in fruits: 13 | print "A fruit of type: %s" % fruit 14 | 15 | # also we can go through mixed lists too 16 | # notice we have to use %r since we don't know what's in it 17 | for i in change: 18 | print "I got %r" % i 19 | 20 | # we can also build lists, first start with an empty one 21 | elements = [] 22 | 23 | # then use the range function to do 0 to 5 counts 24 | for i in range(0, 6): 25 | print "Adding %d to the list." % i 26 | # append is a function that lists understand 27 | elements.append(i) 28 | 29 | # now we can print them out too 30 | for i in elements: 31 | print "Element was: %d" % i 32 | -------------------------------------------------------------------------------- /exercises/exercise33.py: -------------------------------------------------------------------------------- 1 | # Exercise 33: While loops 2 | 3 | i = 0 4 | numbers = [] 5 | 6 | while i < 6: 7 | print "At the top i is %d" % i 8 | numbers.append(i) 9 | i = i + 1 10 | print "Numbers now: ", numbers 11 | print "At the bottom i is %d" % i 12 | 13 | print "The numbers: " 14 | 15 | for num in numbers: 16 | print num 17 | -------------------------------------------------------------------------------- /exercises/exercise34.py: -------------------------------------------------------------------------------- 1 | # Exercise 34: Accessing elements of Lists 2 | 3 | animals = ['bear', 'tiger', 'penguin', 'zebra'] 4 | print "animals =", animals 5 | print "animals[0] =", animals[0] 6 | print "animals[2] =", animals[2] 7 | -------------------------------------------------------------------------------- /exercises/exercise35.py: -------------------------------------------------------------------------------- 1 | # Exercise 35: Branches and Functions 2 | 3 | from sys import exit 4 | 5 | def gold_room(): 6 | print "This room is full of gold. How much do you take?" 7 | 8 | choice = raw_input("> ") 9 | if "0" in choice or "1" in choice: 10 | how_much = int(choice) 11 | else: 12 | dead("Man, learn to type a number.") 13 | 14 | if how_much < 50: 15 | print "Nice, you're not greedy, you win!" 16 | exit(0) 17 | else: 18 | dead("You greedy bastard!") 19 | 20 | 21 | def bear_room(): 22 | print "There is a bear here." 23 | print "The bear has a bunch of honey." 24 | print "The fat bear is in front of another door." 25 | print "How are you going to move the bear?" 26 | bear_moved = False 27 | 28 | while True: 29 | choice = raw_input("> ") 30 | 31 | if choice == "take honey": 32 | dead("The bear looks at you then slaps your face off.") 33 | elif choice == "taunt bear" and not bear_moved: 34 | print "The bear has moved from the door. You can go through it now." 35 | bear_moved = True 36 | elif choice == "taunt bear" and bear_moved: 37 | dead("The bear gets pissed off and chews your leg off.") 38 | elif choice == "open door" and bear_moved: 39 | gold_room() 40 | else: 41 | print "I got no idea what that means." 42 | 43 | 44 | def cthulhu_room(): 45 | print "Here you see the great evil Cthulhu." 46 | print "He, it, whatever stares at you and you go insane." 47 | print "Do you flee for your life or eat your head?" 48 | 49 | choice = raw_input("> ") 50 | 51 | if "flee" in choice: 52 | start() 53 | elif "head" in choice: 54 | dead("Well that was tasty!") 55 | else: 56 | cthulhu_room() 57 | 58 | 59 | def dead(why): 60 | print why, "Good job!" 61 | exit(0) 62 | 63 | def start(): 64 | print "You are in a dark room." 65 | print "There is a door to your right and left." 66 | print "Which one do you take?" 67 | 68 | choice = raw_input("> ") 69 | 70 | if choice == "left": 71 | bear_room() 72 | elif choice == "right": 73 | cthulhu_room() 74 | else: 75 | dead("You stumble around the room until you starve.") 76 | 77 | 78 | start() 79 | -------------------------------------------------------------------------------- /exercises/exercise36.py: -------------------------------------------------------------------------------- 1 | # Exercise 36: Designing and debugging 2 | # No code 3 | # Read: http://learnpythonthehardway.org/book/ex36.html 4 | -------------------------------------------------------------------------------- /exercises/exercise37.py: -------------------------------------------------------------------------------- 1 | # Exercise 37: Symbol review 2 | # No code 3 | # Read: http://learnpythonthehardway.org/book/ex37.html 4 | -------------------------------------------------------------------------------- /exercises/exercise38.py: -------------------------------------------------------------------------------- 1 | # Exercise 38: Doing Things to Lists 2 | 3 | ten_things = "Apples Oranges Crows Telephone Light Sugar" 4 | 5 | print "Wait there are not 10 things in that list. Let's fix that." 6 | 7 | stuff = ten_things.split(' ') 8 | more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 9 | 10 | while len(stuff) != 10: 11 | next_one = more_stuff.pop() 12 | print "Adding: ", next_one 13 | stuff.append(next_one) 14 | print "There are %d items now." % len(stuff) 15 | 16 | print "There we go: ", stuff 17 | 18 | print "Let's do some things with stuff." 19 | 20 | print stuff[1] 21 | print stuff[-1] # whoa! fancy 22 | print stuff.pop() 23 | print ' '.join(stuff) # what? cool! 24 | print '#'.join(stuff[3:5]) # super stellar! 25 | -------------------------------------------------------------------------------- /exercises/exercise39.py: -------------------------------------------------------------------------------- 1 | # Exercise 39: Dictionaries 2 | 3 | # create a mapping of state to abbreviation 4 | states = { 5 | 'Oregon': 'OR', 6 | 'Florida': 'FL', 7 | 'California': 'CA', 8 | 'New York': 'NY', 9 | 'Michigan': 'MI' 10 | } 11 | 12 | # create a basic set of states and some cities in them 13 | cities = { 14 | 'CA': 'San Francisco', 15 | 'MI': 'Detroit', 16 | 'FL': 'Jacksonville' 17 | } 18 | 19 | # add some more cities 20 | cities['NY'] = 'New York' 21 | cities['OR'] = 'Portland' 22 | 23 | # print out some cities 24 | print '-' * 10 25 | print "NY State has: ", cities['NY'] 26 | print "OR State has: ", cities['OR'] 27 | 28 | # print some states 29 | print '-' * 10 30 | print "Michigan's abbreviation is: ", states['Michigan'] 31 | print "Florida's abbreviation is: ", states['Florida'] 32 | 33 | # do it by using the state then cities dict 34 | print '-' * 10 35 | print "Michigan has: ", cities[states['Michigan']] 36 | print "Florida has: ", cities[states['Florida']] 37 | 38 | # print every state abbreviation 39 | print '-' * 10 40 | for state, abbrev in states.items(): 41 | print "%s is abbreviated %s" % (state, abbrev) 42 | 43 | # print every city in state 44 | print '-' * 10 45 | for abbrev, city in cities.items(): 46 | print "%s has the city %s" % (abbrev, city) 47 | 48 | # now do both at the same time 49 | print '-' * 10 50 | for state, abbrev in states.items(): 51 | print "%s state is abbreviated %s and has city %s" % ( 52 | state, abbrev, cities[abbrev]) 53 | 54 | print '-' * 10 55 | # safely get a abbreviation by state that might not be there 56 | state = states.get('Texas') 57 | 58 | if not state: 59 | print "Sorry, no Texas." 60 | 61 | # get a city with a default value 62 | city = cities.get('TX', 'Does Not Exist') 63 | print "The city for the state 'TX' is: %s" % city 64 | -------------------------------------------------------------------------------- /exercises/exercise40_1.py: -------------------------------------------------------------------------------- 1 | # Exercise 40: Modules, Classes, and Objects - part 1 2 | 3 | ''' 4 | # dictionary example 5 | mystuff = {'apple': "I AM APPLES!"} 6 | print mystuff['apple'] 7 | 8 | # modules are like dictionaries 9 | 10 | # this goes in mystuff.py 11 | def apple(): 12 | print "I AM APPLES!" 13 | 14 | # accessing module 15 | 16 | import mystuff 17 | mystuff.apple() 18 | 19 | # updated module 20 | 21 | def apple(): 22 | print "I AM APPLES!" 23 | 24 | # this is just a variable 25 | tangerine = "Living reflection of a dream" 26 | 27 | # accessing module 28 | 29 | import mystuff 30 | 31 | mystuff.apple() 32 | print mystuff.tangerine 33 | 34 | mystuff['apple'] # get apple from dict 35 | mystuff.apple() # get apple from the module 36 | mystuff.tangerine # same thing, it's just a variable 37 | 38 | # classes are like modules - go to exercise40_2.py 39 | 40 | ''' 41 | -------------------------------------------------------------------------------- /exercises/exercise40_2.py: -------------------------------------------------------------------------------- 1 | # Exercise 40: Modules, Classes, and Objects - part 2 2 | 3 | class MyStuff(object): 4 | 5 | def __init__(self): 6 | self.tangerine = "And now a thousand years between" 7 | 8 | def apple(self): 9 | print "I AM CLASSY APPLES!" 10 | 11 | thing = MyStuff() 12 | thing.apple() 13 | print thing.tangerine 14 | 15 | ''' 16 | # Getting Things from Things 17 | 18 | # dict style 19 | mystuff['apples'] 20 | 21 | # module style 22 | import mystuff 23 | mystuff.apples() 24 | print mystuff.tangerine 25 | 26 | # class style 27 | thing = MyStuff() 28 | thing.apples() 29 | print thing.tangerine 30 | 31 | ''' 32 | -------------------------------------------------------------------------------- /exercises/exercise40_3.py: -------------------------------------------------------------------------------- 1 | # Exercise 40: Modules, Classes, and Objects - part 3 2 | 3 | class Song(object): 4 | my_public_variable = "test public" # variables without any prefix are treated as public 5 | __my_private_variable = "test private" # variables with prefix __ are trated as private 6 | _my_protected_variable = "test protected" # variables with prefix _ are treated as protected 7 | 8 | def __init__(self, lyrics): 9 | self.lyrics = lyrics 10 | 11 | def sing_me_a_song(self): 12 | for line in self.lyrics: 13 | print line 14 | 15 | def get_lyrics(self): 16 | return self.lyrics 17 | 18 | def __my_private_method(self): # methods with prefix __ are treated as private, rest is public; same story as variables above 19 | print "private stuff" 20 | 21 | 22 | happy_bday = Song(["Happy birthday to you", 23 | "I don't want to get sued", 24 | "So I'll stop right there"]) 25 | 26 | bulls_on_parade = Song(["They rally around tha family", 27 | "With pockets full of shells"]) 28 | 29 | happy_bday.sing_me_a_song() 30 | 31 | bulls_on_parade.sing_me_a_song() 32 | -------------------------------------------------------------------------------- /exercises/exercise41.py: -------------------------------------------------------------------------------- 1 | # Exercise 41: Learning To Speak Object Oriented 2 | 3 | import random 4 | from urllib import urlopen 5 | import sys 6 | 7 | WORD_URL = "http://learncodethehardway.org/words.txt" 8 | WORDS = [] 9 | 10 | PHRASES = { 11 | "class %%%(%%%):": 12 | "Make a class named %%% that is-a %%%.", 13 | "class %%%(object):\n\tdef __init__(self, ***)" : 14 | "class %%% has-a __init__ that takes self and *** parameters.", 15 | "class %%%(object):\n\tdef ***(self, @@@)": 16 | "class %%% has-a function named *** that takes self and @@@ parameters.", 17 | "*** = %%%()": 18 | "Set *** to an instance of class %%%.", 19 | "***.***(@@@)": 20 | "From *** get the *** function, and call it with parameters self, @@@.", 21 | "***.*** = '***'": 22 | "From *** get the *** attribute and set it to '***'." 23 | } 24 | 25 | # do they want to drill phrases first 26 | if len(sys.argv) == 2 and sys.argv[1] == "english": 27 | PHRASE_FIRST = True 28 | else: 29 | PHRASE_FIRST = False 30 | 31 | # load up the words from the website 32 | for word in urlopen(WORD_URL).readlines(): 33 | WORDS.append(word.strip()) 34 | 35 | 36 | def convert(snippet, phrase): 37 | class_names = [w.capitalize() for w in 38 | random.sample(WORDS, snippet.count("%%%"))] 39 | other_names = random.sample(WORDS, snippet.count("***")) 40 | results = [] 41 | param_names = [] 42 | 43 | for i in range(0, snippet.count("@@@")): 44 | param_count = random.randint(1,3) 45 | param_names.append(', '.join(random.sample(WORDS, param_count))) 46 | 47 | for sentence in snippet, phrase: 48 | result = sentence[:] 49 | 50 | # fake class names 51 | for word in class_names: 52 | result = result.replace("%%%", word, 1) 53 | 54 | # fake other names 55 | for word in other_names: 56 | result = result.replace("***", word, 1) 57 | 58 | # fake parameter lists 59 | for word in param_names: 60 | result = result.replace("@@@", word, 1) 61 | 62 | results.append(result) 63 | 64 | return results 65 | 66 | 67 | # keep going until they hit CTRL-D 68 | try: 69 | while True: 70 | snippets = PHRASES.keys() 71 | random.shuffle(snippets) 72 | 73 | for snippet in snippets: 74 | phrase = PHRASES[snippet] 75 | question, answer = convert(snippet, phrase) 76 | if PHRASE_FIRST: 77 | question, answer = answer, question 78 | 79 | print question 80 | 81 | raw_input("> ") 82 | print "ANSWER: %s\n\n" % answer 83 | except EOFError: 84 | print "\nBye" 85 | -------------------------------------------------------------------------------- /exercises/exercise42.py: -------------------------------------------------------------------------------- 1 | # Exercise 42: Is-A, Has-A, Objects, and Classes 2 | 3 | ## Animal is-a object (yes, sort of confusing) look at the extra credit 4 | class Animal(object): 5 | pass 6 | 7 | ## Dog is-a Animal 8 | class Dog(Animal): 9 | 10 | def __init__(self, name): 11 | ## ?? 12 | self.name = name 13 | 14 | ## Cat is-a Animal 15 | class Cat(Animal): 16 | 17 | def __init__(self, name): 18 | ## Animal has-a name 19 | self.name = name 20 | 21 | ## Person is-a object 22 | class Person(object): 23 | 24 | def __init__(self, name): 25 | ## Person has-a name 26 | self.name = name 27 | 28 | ## Person has-a pet of some kind 29 | self.pet = None 30 | 31 | ## Employee is-a person 32 | class Employee(Person): 33 | 34 | def __init__(self, name, salary): 35 | ## ?? hmm what is this strange magic? 36 | ## We are calling constructor of the class which we are extending (Person with a name) 37 | super(Employee, self).__init__(name) 38 | ## Employee has-a salary 39 | self.salary = salary 40 | 41 | ## Fish is-a object 42 | class Fish(object): 43 | pass 44 | 45 | ## Salomon is-a Fish 46 | class Salmon(Fish): 47 | pass 48 | 49 | ## Halibut is-a fish 50 | class Halibut(Fish): 51 | pass 52 | 53 | 54 | ## rover is-a Dog 55 | rover = Dog("Rover") 56 | 57 | ## satan is-a Cat 58 | satan = Cat("Satan") 59 | 60 | ## mary is-a Person 61 | mary = Person("Mary") 62 | 63 | ## mary has-a Cat called satan 64 | mary.pet = satan 65 | 66 | ## frank is an Employee whos salary is 120000 67 | frank = Employee("Frank", 120000) 68 | 69 | ## frank has-a pet called rover 70 | frank.pet = rover 71 | 72 | ## flipper is-a Fish 73 | flipper = Fish() 74 | 75 | ## crouse is-a Salomon 76 | crouse = Salmon() 77 | 78 | ## harry is-a Halibut 79 | harry = Halibut() 80 | -------------------------------------------------------------------------------- /exercises/exercise43.py: -------------------------------------------------------------------------------- 1 | # Exercise 43: Basic Object-Oriented Analysis and Design 2 | 3 | from sys import exit 4 | from random import randint 5 | 6 | class Scene(object): 7 | 8 | def enter(self): 9 | print "This scene is not yet configured. Subclass it and implement enter()." 10 | exit(1) 11 | 12 | 13 | class Engine(object): 14 | 15 | def __init__(self, scene_map): 16 | self.scene_map = scene_map 17 | 18 | def play(self): 19 | current_scene = self.scene_map.opening_scene() 20 | last_scene = self.scene_map.next_scene('finished') 21 | 22 | while current_scene != last_scene: 23 | next_scene_name = current_scene.enter() 24 | current_scene = self.scene_map.next_scene(next_scene_name) 25 | 26 | # be sure to print out the last scene 27 | current_scene.enter() 28 | 29 | class Death(Scene): 30 | 31 | quips = [ 32 | "You died. You kinda suck at this.", 33 | "Your mom would be proud...if she were smarter.", 34 | "Such a luser.", 35 | "I have a small puppy that's better at this." 36 | ] 37 | 38 | def enter(self): 39 | print Death.quips[randint(0, len(self.quips)-1)] 40 | exit(1) 41 | 42 | class CentralCorridor(Scene): 43 | 44 | def enter(self): 45 | print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" 46 | print "your entire crew. You are the last surviving member and your last" 47 | print "mission is to get the neutron destruct bomb from the Weapons Armory," 48 | print "put it in the bridge, and blow the ship up after getting into an " 49 | print "escape pod." 50 | print "\n" 51 | print "You're running down the central corridor to the Weapons Armory when" 52 | print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" 53 | print "flowing around his hate filled body. He's blocking the door to the" 54 | print "Armory and about to pull a weapon to blast you." 55 | 56 | action = raw_input("> ") 57 | 58 | if action == "shoot!": 59 | print "Quick on the draw you yank out your blaster and fire it at the Gothon." 60 | print "His clown costume is flowing and moving around his body, which throws" 61 | print "off your aim. Your laser hits his costume but misses him entirely. This" 62 | print "completely ruins his brand new costume his mother bought him, which" 63 | print "makes him fly into an insane rage and blast you repeatedly in the face until" 64 | print "you are dead. Then he eats you." 65 | return 'death' 66 | 67 | elif action == "dodge!": 68 | print "Like a world class boxer you dodge, weave, slip and slide right" 69 | print "as the Gothon's blaster cranks a laser past your head." 70 | print "In the middle of your artful dodge your foot slips and you" 71 | print "bang your head on the metal wall and pass out." 72 | print "You wake up shortly after only to die as the Gothon stomps on" 73 | print "your head and eats you." 74 | return 'death' 75 | 76 | elif action == "tell a joke": 77 | print "Lucky for you they made you learn Gothon insults in the academy." 78 | print "You tell the one Gothon joke you know:" 79 | print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr." 80 | print "The Gothon stops, tries not to laugh, then busts out laughing and can't move." 81 | print "While he's laughing you run up and shoot him square in the head" 82 | print "putting him down, then jump through the Weapon Armory door." 83 | return 'laser_weapon_armory' 84 | 85 | else: 86 | print "DOES NOT COMPUTE!" 87 | return 'central_corridor' 88 | 89 | class LaserWeaponArmory(Scene): 90 | 91 | def enter(self): 92 | print "You do a dive roll into the Weapon Armory, crouch and scan the room" 93 | print "for more Gothons that might be hiding. It's dead quiet, too quiet." 94 | print "You stand up and run to the far side of the room and find the" 95 | print "neutron bomb in its container. There's a keypad lock on the box" 96 | print "and you need the code to get the bomb out. If you get the code" 97 | print "wrong 10 times then the lock closes forever and you can't" 98 | print "get the bomb. The code is 3 digits." 99 | code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) 100 | guess = raw_input("[keypad]> ") 101 | guesses = 0 102 | 103 | while guess != code and guesses < 10: 104 | print "BZZZZEDDD!" 105 | guesses += 1 106 | guess = raw_input("[keypad]> ") 107 | 108 | if guess == code: 109 | print "The container clicks open and the seal breaks, letting gas out." 110 | print "You grab the neutron bomb and run as fast as you can to the" 111 | print "bridge where you must place it in the right spot." 112 | return 'the_bridge' 113 | else: 114 | print "The lock buzzes one last time and then you hear a sickening" 115 | print "melting sound as the mechanism is fused together." 116 | print "You decide to sit there, and finally the Gothons blow up the" 117 | print "ship from their ship and you die." 118 | return 'death' 119 | 120 | class TheBridge(Scene): 121 | 122 | def enter(self): 123 | print "You burst onto the Bridge with the netron destruct bomb" 124 | print "under your arm and surprise 5 Gothons who are trying to" 125 | print "take control of the ship. Each of them has an even uglier" 126 | print "clown costume than the last. They haven't pulled their" 127 | print "weapons out yet, as they see the active bomb under your" 128 | print "arm and don't want to set it off." 129 | 130 | action = raw_input("> ") 131 | 132 | if action == "throw the bomb": 133 | print "In a panic you throw the bomb at the group of Gothons" 134 | print "and make a leap for the door. Right as you drop it a" 135 | print "Gothon shoots you right in the back killing you." 136 | print "As you die you see another Gothon frantically try to disarm" 137 | print "the bomb. You die knowing they will probably blow up when" 138 | print "it goes off." 139 | return 'death' 140 | 141 | elif action == "slowly place the bomb": 142 | print "You point your blaster at the bomb under your arm" 143 | print "and the Gothons put their hands up and start to sweat." 144 | print "You inch backward to the door, open it, and then carefully" 145 | print "place the bomb on the floor, pointing your blaster at it." 146 | print "You then jump back through the door, punch the close button" 147 | print "and blast the lock so the Gothons can't get out." 148 | print "Now that the bomb is placed you run to the escape pod to" 149 | print "get off this tin can." 150 | return 'escape_pod' 151 | else: 152 | print "DOES NOT COMPUTE!" 153 | return "the_bridge" 154 | 155 | class EscapePod(Scene): 156 | 157 | def enter(self): 158 | print "You rush through the ship desperately trying to make it to" 159 | print "the escape pod before the whole ship explodes. It seems like" 160 | print "hardly any Gothons are on the ship, so your run is clear of" 161 | print "interference. You get to the chamber with the escape pods, and" 162 | print "now need to pick one to take. Some of them could be damaged" 163 | print "but you don't have time to look. There's 5 pods, which one" 164 | print "do you take?" 165 | 166 | good_pod = randint(1,5) 167 | guess = raw_input("[pod #]> ") 168 | 169 | 170 | if int(guess) != good_pod: 171 | print "You jump into pod %s and hit the eject button." % guess 172 | print "The pod escapes out into the void of space, then" 173 | print "implodes as the hull ruptures, crushing your body" 174 | print "into jam jelly." 175 | return 'death' 176 | else: 177 | print "You jump into pod %s and hit the eject button." % guess 178 | print "The pod easily slides out into space heading to" 179 | print "the planet below. As it flies to the planet, you look" 180 | print "back and see your ship implode then explode like a" 181 | print "bright star, taking out the Gothon ship at the same" 182 | print "time. You won!" 183 | 184 | return 'finished' 185 | 186 | class Finished(Scene): 187 | 188 | def enter(self): 189 | print "You won! Good job." 190 | return 'finished' 191 | 192 | class Map(object): 193 | 194 | scenes = { 195 | 'central_corridor': CentralCorridor(), 196 | 'laser_weapon_armory': LaserWeaponArmory(), 197 | 'the_bridge': TheBridge(), 198 | 'escape_pod': EscapePod(), 199 | 'death': Death(), 200 | 'finished': Finished(), 201 | } 202 | 203 | def __init__(self, start_scene): 204 | self.start_scene = start_scene 205 | 206 | def next_scene(self, scene_name): 207 | val = Map.scenes.get(scene_name) 208 | return val 209 | 210 | def opening_scene(self): 211 | return self.next_scene(self.start_scene) 212 | 213 | a_map = Map('central_corridor') 214 | a_game = Engine(a_map) 215 | a_game.play() 216 | -------------------------------------------------------------------------------- /exercises/exercise44a.py: -------------------------------------------------------------------------------- 1 | # Exercise 44: Inheritance Versus Composition (Part 1 - Inheritance) 2 | 3 | # Implicit Inheritance 4 | 5 | class ParentA(object): 6 | 7 | def implicit(self): 8 | print "PARENT A implicit()" 9 | 10 | class ChildA(ParentA): 11 | pass 12 | 13 | dadA = ParentA() 14 | sonA = ChildA() 15 | 16 | dadA.implicit() 17 | sonA.implicit() 18 | 19 | # Override Explicitly 20 | 21 | class ParentB(object): 22 | 23 | def override(self): 24 | print "PARENT B override()" 25 | 26 | class ChildB(ParentB): 27 | 28 | def override(self): 29 | print "CHILD B override()" 30 | 31 | dadB = ParentB() 32 | sonB = ChildB() 33 | 34 | dadB.override() 35 | sonB.override() 36 | 37 | # Alter before of after 38 | 39 | class ParentC(object): 40 | 41 | def altered(self): 42 | print "PARENT C altered()" 43 | 44 | class ChildC(ParentC): 45 | 46 | def altered(self): 47 | print "CHILD C, BEFORE PARENT C altered()" 48 | super(ChildC, self).altered() 49 | print "CHILD C, AFTER PARENT C altered()" 50 | 51 | dadC = ParentC() 52 | sonC = ChildC() 53 | 54 | dadC.altered() 55 | sonC.altered() 56 | 57 | # All three combined 58 | 59 | class ParentD(object): 60 | 61 | def override(self): 62 | print "PARENT D override()" 63 | 64 | def implicit(self): 65 | print "PARENT D implicit()" 66 | 67 | def altered(self): 68 | print "PARENT D altered()" 69 | 70 | class ChildD(ParentD): 71 | 72 | def override(self): 73 | print "CHILD D override()" 74 | 75 | def altered(self): 76 | print "CHILD D, BEFORE PARENT D altered()" 77 | super(ChildD, self).altered() 78 | print "CHILD D, AFTER PARENT D altered()" 79 | 80 | dadD = ParentD() 81 | sonD = ChildD() 82 | 83 | dadD.implicit() 84 | sonD.implicit() 85 | 86 | dadD.override() 87 | sonD.override() 88 | 89 | dadD.altered() 90 | sonD.altered() 91 | -------------------------------------------------------------------------------- /exercises/exercise44b.py: -------------------------------------------------------------------------------- 1 | # Exercise 44: Inheritance Versus Composition (Part 2 - Composition) 2 | 3 | class Other(object): 4 | 5 | def override(self): 6 | print "OTHER override()" 7 | 8 | def implicit(self): 9 | print "OTHER implicit()" 10 | 11 | def altered(self): 12 | print "OTHER altered()" 13 | 14 | class Child(object): 15 | 16 | def __init__(self): 17 | self.other = Other() 18 | 19 | def implicit(self): 20 | self.other.implicit() 21 | 22 | def override(self): 23 | print "CHILD override()" 24 | 25 | def altered(self): 26 | print "CHILD, BEFORE OTHER altered()" 27 | self.other.altered() 28 | print "CHILD, AFTER OTHER altered()" 29 | 30 | son = Child() 31 | 32 | son.implicit() 33 | son.override() 34 | son.altered() 35 | -------------------------------------------------------------------------------- /exercises/exercise45.py: -------------------------------------------------------------------------------- 1 | # Exercise 45: You Make A Game 2 | 3 | ''' 4 | It's a very simple example of a "text-based game", 5 | where you can go to one room or another. 6 | It uses classes, inheritance and composition. 7 | Of course, it can be improved or extended in the future. 8 | ''' 9 | 10 | class Game(object): 11 | def __init__(self): 12 | self.kitchen = Kitchen() 13 | self.living_room = LivingRoom() 14 | 15 | def start(self): 16 | print "starting game..." 17 | action = raw_input("choose room: ") 18 | if action == "kitchen": 19 | self.kitchen.enter() 20 | elif action == "living_room": 21 | self.living_room.enter() 22 | else: 23 | print "I don't know that place" 24 | 25 | class Room(object): 26 | def enter(self): 27 | pass 28 | 29 | def leave(self): 30 | print "leaving room" 31 | 32 | class Kitchen(Room): 33 | def enter(self): 34 | print "entering Kitchen..." 35 | 36 | class LivingRoom(Room): 37 | def enter(self): 38 | print "entering Living Room..." 39 | 40 | game = Game() 41 | game.start() 42 | -------------------------------------------------------------------------------- /exercises/exercise46/skeleton/NAME/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise46/skeleton/NAME/__init__.py -------------------------------------------------------------------------------- /exercises/exercise46/skeleton/bin/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise46/skeleton/bin/empty -------------------------------------------------------------------------------- /exercises/exercise46/skeleton/docs/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise46/skeleton/docs/empty -------------------------------------------------------------------------------- /exercises/exercise46/skeleton/setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | config = { 7 | 'description': 'My Project', 8 | 'author': 'My Name', 9 | 'url': 'URL to get it at.', 10 | 'download_url': 'Where to download it.', 11 | 'author_email': 'My email.', 12 | 'version': '0.1', 13 | 'install_requires': ['nose'], 14 | 'packages': ['NAME'], 15 | 'scripts': [], 16 | 'name': 'projectname' 17 | } 18 | 19 | setup(**config) 20 | -------------------------------------------------------------------------------- /exercises/exercise46/skeleton/tests/NAME_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import NAME 3 | 4 | def setup(): 5 | print "SETUP!" 6 | 7 | def teardown(): 8 | print "TEAR DOWN!" 9 | 10 | def test_basic(): 11 | print "I RAN!" 12 | -------------------------------------------------------------------------------- /exercises/exercise46/skeleton/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise46/skeleton/tests/__init__.py -------------------------------------------------------------------------------- /exercises/exercise47/bin/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise47/bin/empty -------------------------------------------------------------------------------- /exercises/exercise47/docs/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise47/docs/empty -------------------------------------------------------------------------------- /exercises/exercise47/exercise47/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise47/exercise47/__init__.py -------------------------------------------------------------------------------- /exercises/exercise47/exercise47/game.py: -------------------------------------------------------------------------------- 1 | class Room(object): 2 | 3 | def __init__(self, name, description): 4 | self.name = name 5 | self.description = description 6 | self.paths = {} 7 | 8 | def go(self, direction): 9 | return self.paths.get(direction, None) 10 | 11 | def add_paths(self, paths): 12 | self.paths.update(paths) 13 | -------------------------------------------------------------------------------- /exercises/exercise47/setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | config = { 7 | 'description': 'My Project - exercise 47', 8 | 'author': 'My Name', 9 | 'url': 'URL to get it at.', 10 | 'download_url': 'Where to download it.', 11 | 'author_email': 'My email.', 12 | 'version': '0.1', 13 | 'install_requires': ['nose'], 14 | 'packages': ['exercise47'], 15 | 'scripts': [], 16 | 'name': 'projectname' 17 | } 18 | 19 | setup(**config) 20 | -------------------------------------------------------------------------------- /exercises/exercise47/tests/exercise47_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | import exercise47 3 | 4 | def setup(): 5 | print "SETUP!" 6 | 7 | def teardown(): 8 | print "TEAR DOWN!" 9 | 10 | def test_basic(): 11 | print "I RAN!" 12 | -------------------------------------------------------------------------------- /exercises/exercise47/tests/game_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | from exercise47.game import Room 3 | 4 | 5 | def test_room(): 6 | gold = Room("GoldRoom", 7 | """This room has gold in it you can grab. There's a 8 | door to the north.""") 9 | assert_equal(gold.name, "GoldRoom") 10 | assert_equal(gold.paths, {}) 11 | 12 | def test_room_paths(): 13 | center = Room("Center", "Test room in the center.") 14 | north = Room("North", "Test room in the north.") 15 | south = Room("South", "Test room in the south.") 16 | 17 | center.add_paths({'north': north, 'south': south}) 18 | assert_equal(center.go('north'), north) 19 | assert_equal(center.go('south'), south) 20 | 21 | def test_map(): 22 | start = Room("Start", "You can go west and down a hole.") 23 | west = Room("Trees", "There are trees here, you can go east.") 24 | down = Room("Dungeon", "It's dark down here, you can go up.") 25 | 26 | start.add_paths({'west': west, 'down': down}) 27 | west.add_paths({'east': start}) 28 | down.add_paths({'up': start}) 29 | 30 | assert_equal(start.go('west'), west) 31 | assert_equal(start.go('west').go('east'), start) 32 | assert_equal(start.go('down').go('up'), start) 33 | -------------------------------------------------------------------------------- /exercises/exercise48/bin/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise48/bin/empty -------------------------------------------------------------------------------- /exercises/exercise48/docs/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise48/docs/empty -------------------------------------------------------------------------------- /exercises/exercise48/exercise48/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise48/exercise48/__init__.py -------------------------------------------------------------------------------- /exercises/exercise48/exercise48/lexicon.py: -------------------------------------------------------------------------------- 1 | directions = ["north","south","east","west"] 2 | verbs = ["go","kill","eat"] 3 | stops = ["the","in","of"] 4 | nouns = ["bear","princess"] 5 | 6 | def scan(input): 7 | words = input.split() 8 | tuples = [] 9 | for value in words: 10 | tuples.append((get_type(value), get_value(value))) 11 | return tuples 12 | 13 | def get_type(input): 14 | if input in directions: return "direction" 15 | elif input in verbs: return "verb" 16 | elif input in stops: return "stop" 17 | elif input in nouns: return "noun" 18 | elif is_number(input): return "number" 19 | else: return "error" 20 | 21 | def get_value(input): 22 | converted_number = convert_number(input) 23 | if converted_number != None: 24 | return converted_number 25 | else: 26 | return input 27 | 28 | def is_number(input): 29 | return convert_number(input) != None 30 | 31 | def convert_number(input): 32 | try: 33 | return int(input) 34 | except ValueError: 35 | return None 36 | -------------------------------------------------------------------------------- /exercises/exercise48/exercise48/parser.py: -------------------------------------------------------------------------------- 1 | class ParserError(Exception): 2 | pass 3 | 4 | class Sentence(object): 5 | def __init__(self, subject, verb, obj): 6 | # remember we take ('noun','princess') tuples and convert them 7 | self.subject = subject[1] 8 | self.verb = verb[1] 9 | self.object = obj[1] 10 | 11 | def peek(word_list): 12 | if word_list: 13 | word = word_list[0] 14 | return word[0] 15 | else: 16 | return None 17 | 18 | def match(word_list, expecting): 19 | if word_list: 20 | word = word_list.pop(0) 21 | 22 | if word[0] == expecting: 23 | return word 24 | else: 25 | return None 26 | else: 27 | return None 28 | 29 | def skip(word_list, word_type): 30 | while peek(word_list) == word_type: 31 | match(word_list, word_type) 32 | 33 | def parse_verb(word_list): 34 | skip(word_list, 'stop') 35 | 36 | if peek(word_list) == 'verb': 37 | return match(word_list, 'verb') 38 | else: 39 | raise ParserError("Expected a verb next.") 40 | 41 | def parse_object(word_list): 42 | skip(word_list, 'stop') 43 | next_word = peek(word_list) 44 | 45 | if next_word == 'noun': 46 | return match(word_list, 'noun') 47 | elif next_word == 'direction': 48 | return match(word_list, 'direction') 49 | else: 50 | raise ParserError("Expected a noun or direction next.") 51 | 52 | def parse_subject(word_list): 53 | skip(word_list, 'stop') 54 | next_word = peek(word_list) 55 | 56 | if next_word == 'noun': 57 | return match(word_list, 'noun') 58 | elif next_word == 'verb': 59 | return ('noun', 'player') 60 | else: 61 | raise ParserError("Expected a verb next.") 62 | 63 | def parse_sentence(word_list): 64 | subj = parse_subject(word_list) 65 | verb = parse_verb(word_list) 66 | obj = parse_object(word_list) 67 | 68 | return Sentence(subj, verb, obj) 69 | -------------------------------------------------------------------------------- /exercises/exercise48/setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | config = { 7 | 'description': 'My Project - exercise 48', 8 | 'author': 'My Name', 9 | 'url': 'URL to get it at.', 10 | 'download_url': 'Where to download it.', 11 | 'author_email': 'My email.', 12 | 'version': '0.1', 13 | 'install_requires': ['nose'], 14 | 'packages': ['exercise48'], 15 | 'scripts': [], 16 | 'name': 'projectname' 17 | } 18 | 19 | setup(**config) 20 | -------------------------------------------------------------------------------- /exercises/exercise48/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise48/tests/__init__.py -------------------------------------------------------------------------------- /exercises/exercise48/tests/lexicon_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | from exercise48 import lexicon 3 | 4 | 5 | def test_directions(): 6 | assert_equal(lexicon.scan("north"), [('direction', 'north')]) 7 | result = lexicon.scan("north south east") 8 | assert_equal(result, [('direction', 'north'), 9 | ('direction', 'south'), 10 | ('direction', 'east')]) 11 | 12 | def test_verbs(): 13 | assert_equal(lexicon.scan("go"), [('verb', 'go')]) 14 | result = lexicon.scan("go kill eat") 15 | assert_equal(result, [('verb', 'go'), 16 | ('verb', 'kill'), 17 | ('verb', 'eat')]) 18 | 19 | def test_stops(): 20 | assert_equal(lexicon.scan("the"), [('stop', 'the')]) 21 | result = lexicon.scan("the in of") 22 | assert_equal(result, [('stop', 'the'), 23 | ('stop', 'in'), 24 | ('stop', 'of')]) 25 | 26 | def test_nouns(): 27 | assert_equal(lexicon.scan("bear"), [('noun', 'bear')]) 28 | result = lexicon.scan("bear princess") 29 | assert_equal(result, [('noun', 'bear'), 30 | ('noun', 'princess')]) 31 | 32 | def test_numbers(): 33 | assert_equal(lexicon.scan("1234"), [('number', 1234)]) 34 | result = lexicon.scan("3 91234") 35 | assert_equal(result, [('number', 3), 36 | ('number', 91234)]) 37 | 38 | def test_errors(): 39 | assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')]) 40 | result = lexicon.scan("bear IAS princess") 41 | assert_equal(result, [('noun', 'bear'), 42 | ('error', 'IAS'), 43 | ('noun', 'princess')]) 44 | -------------------------------------------------------------------------------- /exercises/exercise48/tests/parser_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | from exercise48.parser import * 3 | 4 | 5 | def test_parse_sentence(): 6 | sentence = parse_sentence([('verb', 'run'), ('direction', 'north')]) 7 | assert_equal(sentence.subject, 'player') 8 | assert_equal(sentence.verb, 'run') 9 | assert_equal(sentence.object, 'north') 10 | -------------------------------------------------------------------------------- /exercises/exercise50/gothonweb/bin/app.py: -------------------------------------------------------------------------------- 1 | import web 2 | 3 | urls = ( 4 | '/hello', 'Index' 5 | ) 6 | 7 | app = web.application(urls, globals()) 8 | render = web.template.render('templates/', base="layout") 9 | 10 | class Index: 11 | def GET(self): 12 | return render.hello_form() 13 | 14 | def POST(self): 15 | form = web.input(name="Nobody", greet="Hello") 16 | greeting = "%s, %s" % (form.greet, form.name) 17 | return render.index(greeting = greeting) 18 | 19 | if __name__ == "__main__": 20 | app.run() 21 | -------------------------------------------------------------------------------- /exercises/exercise50/gothonweb/gothonweb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise50/gothonweb/gothonweb/__init__.py -------------------------------------------------------------------------------- /exercises/exercise50/gothonweb/templates/hello_form.html: -------------------------------------------------------------------------------- 1 |
6 | $room.description 7 |8 | 9 | $if room.name == "death": 10 | 11 | $else: 12 |
13 |
16 | 17 | -------------------------------------------------------------------------------- /exercises/exercise52/game/templates/you_died.html: -------------------------------------------------------------------------------- 1 |Looks like you bit the dust.
4 | 5 | -------------------------------------------------------------------------------- /exercises/exercise52/game/tests/map_tests.py: -------------------------------------------------------------------------------- 1 | from nose.tools import * 2 | from game.bin.map import * 3 | 4 | def test_room(): 5 | gold = Room("GoldRoom", 6 | """This room has gold in it you can grab. There's a 7 | door to the north.""") 8 | assert_equal(gold.name, "GoldRoom") 9 | assert_equal(gold.paths, {}) 10 | 11 | def test_room_paths(): 12 | center = Room("Center", "Test room in the center.") 13 | north = Room("North", "Test room in the north.") 14 | south = Room("South", "Test room in the south.") 15 | 16 | center.add_paths({'north': north, 'south': south}) 17 | assert_equal(center.go('north'), north) 18 | assert_equal(center.go('south'), south) 19 | 20 | def test_map(): 21 | start = Room("Start", "You can go west and down a hole.") 22 | west = Room("Trees", "There are trees here, you can go east.") 23 | down = Room("Dungeon", "It's dark down here, you can go up.") 24 | 25 | start.add_paths({'west': west, 'down': down}) 26 | west.add_paths({'east': start}) 27 | down.add_paths({'up': start}) 28 | 29 | assert_equal(start.go('west'), west) 30 | assert_equal(start.go('west').go('east'), start) 31 | assert_equal(start.go('down').go('up'), start) 32 | 33 | def test_gothon_game_map(): 34 | assert_equal(START.go('shoot!'), generic_death) 35 | assert_equal(START.go('dodge!'), generic_death) 36 | 37 | room = START.go('tell a joke') 38 | assert_equal(room, laser_weapon_armory) 39 | -------------------------------------------------------------------------------- /exercises/exercise52/gothonweb/bin/app.py: -------------------------------------------------------------------------------- 1 | import web 2 | 3 | web.config.debug = False 4 | 5 | urls = ( 6 | "/count", "count", 7 | "/reset", "reset" 8 | ) 9 | app = web.application(urls, locals()) 10 | store = web.session.DiskStore('sessions') 11 | session = web.session.Session(app, store, initializer={'count': 0}) 12 | 13 | class count: 14 | def GET(self): 15 | session.count += 1 16 | return str(session.count) 17 | 18 | class reset: 19 | def GET(self): 20 | session.kill() 21 | return "" 22 | 23 | if __name__ == "__main__": 24 | app.run() 25 | -------------------------------------------------------------------------------- /exercises/exercise52/gothonweb/gothonweb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pwittchen/learn-python-the-hard-way/00907431c74d83468b75a95e4b6551a87d4ffdad/exercises/exercise52/gothonweb/gothonweb/__init__.py --------------------------------------------------------------------------------