├── .gitignore ├── LICENSE ├── README.md ├── chapters ├── Ch.00.Prologue.ipynb ├── Ch.01.IntroducingPython.ipynb ├── Ch.02.DataTypes.ipynb ├── Ch.03.Collections.ipynb ├── Ch.04.ConditionalsLoopsErrors.ipynb ├── Ch.05.FunctionsClasses.ipynb ├── Ch.06.TheFileSystem.ipynb └── Ch.07.WhereToNext.ipynb ├── exercises ├── Ch.A01.ShortQuestions.ipynb ├── Ch.A02.ShortAnswers.ipynb ├── Ch.A03.LongerIdeas.ipynb └── MASTER_Ch.A.ShortQuestions.ipynb ├── latex └── build_book.py └── pdf └── IntroducingPython.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | # User defined 2 | .DS_Store 3 | /latex/tex/* 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | pip-wheel-metadata/ 28 | share/python-wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .nox/ 48 | .coverage 49 | .coverage.* 50 | .cache 51 | nosetests.xml 52 | coverage.xml 53 | *.cover 54 | *.py,cover 55 | .hypothesis/ 56 | .pytest_cache/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 99 | __pypackages__/ 100 | 101 | # Celery stuff 102 | celerybeat-schedule 103 | celerybeat.pid 104 | 105 | # SageMath parsed files 106 | *.sage.py 107 | 108 | # Environments 109 | .env 110 | .venv 111 | env/ 112 | venv/ 113 | ENV/ 114 | env.bak/ 115 | venv.bak/ 116 | 117 | # Spyder project settings 118 | .spyderproject 119 | .spyproject 120 | 121 | # Rope project settings 122 | .ropeproject 123 | 124 | # mkdocs documentation 125 | /site 126 | 127 | # mypy 128 | .mypy_cache/ 129 | .dmypy.json 130 | dmypy.json 131 | 132 | # Pyre type checker 133 | .pyre/ 134 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introducing Python 2 | 3 | An introductory course on Python Programming from [Bernie Hogan](https://www.oii.ox.ac.uk/people/profiles/bernie-hogan/) at the [Oxford Internet Institute](https://www.oii.ox.ac.uk/). This course goes through some of the basics of Python using Jupyter Lab. The course can be considered as a [prinable PDF document](https://github.com/berniehogan/introducingpython/blob/main/pdf/IntroducingPython.pdf) or as a series of Jupyter Lab notebooks. 4 | 5 | The notebooks will allow you to run the code yourself and tinker with it. These can be run on your own machine by cloning this repository to your desktop. You can also save the raw files as `*.ipynb` (such as `Ch.00.Prologue.ipynb`) and run them locally. Then you can run them using Jupyter Lab. You can alternatively run them online using the buttons at the top of each file that signal "Run in Colab" or "launch binder", like the following: 6 | 7 | [![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/berniehogan/introducingpython/main?filepath=chapters%2FCh.00.Prologue.ipynb) 8 | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/berniehogan/introducingpython/blob/main/chapters/Ch.00.Prologue.ipynb) 9 | 10 | Jupyter Lab is covered in Chapter 1. So if you do not have it installed, you can read this via the PDF, the GitHub repository, or via Colab / Binder until you get it sorted. 11 | 12 | ## Table of contents 13 | 14 | - **Prologue**. A short introduction and welcome; 15 | - **Chapter 1**. An orientation to Jupyter Lab and programming in Python; 16 | - **Chpater 2**. Introducing simple data types: from characters to numbers to strings; 17 | - **Chapter 3**. Collections: ordering data by position, index, and membership; 18 | - **Chapter 4**. Conditionals, loops, and errors: How to change the flow of a program; 19 | - **Chapter 5**. Functions and object-oriented programming: Using abstraction to limit redundancy; 20 | - **Chpater 6**. The file system; 21 | - **Exercises**. Short exercises, answers to the short exerciess, and some longer exercises which might not have a specific "goal" but are more creative. 22 | 23 | This course does not have a large number of exercises. Instead, there are at the end a small number of projects that you might want to complete in order to get a feel for the material and show some of your creativity along the way. This book runs through pretty well-worn territory and despite its inclusion in a social science degree, there is not much social science here. Instead, these are the basic grammar of Python that you would use regardless of your eventual destination. This should cover a lot of the same material as other Introducing Python courses broadly. That said, I hope my pacing, language, and resources bring some value add to this. 24 | 25 | For social science, computational social science, and some data science students, I would then recommend my forthcoming book, "From Social Science to Data Science", which goes through the next set of skills. These include how to wrangle data in DataFrames, collect data using an API, merge data, and look at social data as text, networks, and geographies. It is due out in December 2022. The companion [GitHub archive is here](https://www.github.com/berniehogan/fsstds) [Note Forthcoming prior to December 2022]. 26 | -------------------------------------------------------------------------------- /chapters/Ch.00.Prologue.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Welcome! \n", 8 | "\n", 9 | "Thanks for checking out this book. \n", 10 | "\n", 11 | "The origins of this book started many, many years ago as a series of Python scripts for teaching social scientists how to code in Python. Over the years these grew into ever more extensive lecture notes. During the process of compiling lecture notes for my larger book [\"From Social Science to Data Science\"](https://github.com/berniehogan/fsstds), I thought it might be a good idea to also take my introductory notes and compile them as a book. \n", 12 | "\n", 13 | "It turned out to be a little more work than I expected! Part of the issue is that in reading my notes in a book form I became aware of certain assumptions I made or glossed over because I thought I could talk through such issues during a lecture. Yet, students appreciate resources. I adore using this book as a set of \"living notebooks\" in Jupyter. You can edit this book, run it, change it etc. But not much beats being able to have a printed or at least nicely formatted version of these notes to annotate, flip through and refer back to at a glance. So I hope you appreciate these notes. I further hope they encourage you to consider learning Python and developing your own way of working programmatically. " 14 | ] 15 | }, 16 | { 17 | "cell_type": "markdown", 18 | "metadata": {}, 19 | "source": [ 20 | "# Python as a computer language\n", 21 | "\n", 22 | "Python is a computer language. Most computer langauges have some resemblance to human language but they are very fussy! Every punctuation must be correct, every space has to be in place, every word has to have the correct capitalisation. \n", 23 | "\n", 24 | "Language tends to have a notion of __nouns__ and __verbs__. Nouns are often thought of as objects, like a _pizza_. Verbs are actions like _throw_. You should not throw a pizza. Python has a similar notion of __objects__ and __functions/methods__. Objects contain things. Functions are the ways that we make use of things in Python. They are like the verbs. For example: \n", 25 | "\n", 26 | "~~~ python \n", 27 | "print(\"Hello world!\") \n", 28 | "~~~\n", 29 | "\n", 30 | "In this case:\n", 31 | "\n", 32 | "- `print` is the function; \n", 33 | "- `()` contains what gets done; \n", 34 | "- `\"Hello world!\"` is data to which we do something, in this case, we __print__ the characters between the quotes. This is much safer than throwing pizza.\n", 35 | "\n", 36 | "Most of programming will involve moving around data between these functions in increasing layers of complexity, starting first with step by step instructions, and then subsequently with increasing amounts of abstraction. That is how the programming in this book will proceed. " 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "# An outline\n", 44 | "\n", 45 | "The first thing we will need to do is get you started with an environment for programming. Chapter \\ref{ch:intro} introduces some basics of Python and of an environment called Jupyter Lab. You might already be reading these chapters in Jupyter Lab! But if not, Chapter 1 has some tips on how to install and work with it. \n", 46 | "\n", 47 | "In Chapter \\ref{ch:datatypes}, we are going to start with a discussion of primitive data types. These are the basic building blocks of objects. They correspond to letters and numbers. Then in the second half of this chapter we will show __collections__. Collections include multiple data objects, either of the same type or a different type. That takes us to the end of this chapter just covering the logic of collections. \n", 48 | "\n", 49 | "In Chapter \\ref{ch:collections}, we ask, if we have a collection how can we repeat an action for each element in that collection? Thus, we will learn about __iteration__. Iterating leads quite naturally to the question: what if I want to do something some of the time (of for only some of the elements?) This means we are doing something under some _condition_. Thus, in Python we have an important notion of __conditionals__, the most common of these are `if` and `else` statements. As in:\n", 50 | "\n", 51 | "~~~ python\n", 52 | "if YEAR == 2020: \n", 53 | " buy(\"mask\") \n", 54 | "~~~\n", 55 | "\n", 56 | "The means to assign a bunch of variables, have iterations, and do it under some conditions form the basis of programming in virtually any language. But this can also get very messy. So different languages have ways of organising code, often to _minimise redundancy_ or _maximise reusability or robustness_. One essential concept for organising code in Python is to make use of __functions__, both functions that are pre-built and those that you create yourself. In \\ref{ch:functions} we look at how to build a function, what sort of inputs are possible (and useful), and how to bundle functions together as objects. \n", 57 | "\n", 58 | "Functions can stand alone, or they can be dedicated functions for a specific class of __object__. These dedicated functions are called __methods__. We cover objects in more detail also in Chapter \\ref{ch:functions}. \n", 59 | " \n", 60 | "In Python, if it is a noun and it is not a primitive data type, then it is an object. So you can have a `tweet` object which contains data about a tweet, such as its author, time, URL, hashtags, etc. A simpler object is a `list`, which is just an ordered collection such as `[\"Abba\", \"Toto\", \"Gaga\"]`. The type of object in Python is called its `class`. Classes are also covered in Chapter \\ref{ch:functions}. \n", 61 | "\n", 62 | "Chapter \\ref{ch:files} looks at how to read and write files, both for reading and writing data, but also for running Python programs. This does not really involve more complex programming concepts but starts you along a path towards using Python in Jupyter and beyond. \n", 63 | "\n", 64 | "The book concludes with some ideas and resources for further learning in Chapter \\ref{ch:next}. \n", 65 | "\n", 66 | "This book has a series of appendcies. These are exercises that I have put together based on the material for the different chapters. These tend to work better as Jupyter notebooks, but I also wanted to compile them. I feel that some of the most interesting work I've done is not in telling people _what_ to learn in Python, but inviting them to explore Python themselves. I hope the exercises encourage a level of playfulness with the code. The first, Chapter \\ref{ap:short}, presents a few shorter exercises tied to each chapter of the book. The second, Chapter \\ref{ap:answers}, are some example answers for the prior appendix. I'm sure you won't just copy and paste the answers, but this way removes some of the temptation. Then afterwards in Chapter \\ref{ap:longer} I propose a few longer projects that might be a fun challenge. " 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "# Why this book? \n", 74 | "\n", 75 | "Python is a vast and well supported language. But that can be a problem as well as an advantage. It's easy to get overwhelmed by resources, Stack Exchange pages, endless YouTube videos with ever so slightly different content. And indeed, hundreds of introductory books and blog pages. \n", 76 | "\n", 77 | "This book is based on a decade of experience teaching graduate students Python, often graduate students from a humanities and social science background who never thought they could or would learn a programming language. It is certainly not the only way to learn, but it is the way that I have been able to teach. So in a way, this is a book mainly for me and my classes. But why limit knowledge? So for that reason, I have put this together as a .pdf and set of Jupyter notebooks so maybe it will be of use to you, too! " 78 | ] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "metadata": {}, 83 | "source": [ 84 | "# Dedication \n", 85 | "\n", 86 | "This one is dedicated to the teachers who take risks to keep their learning fresh. \n", 87 | "\n", 88 | "In my undergraduate degree 20 years ago Prof. Ron Byrne had been teaching a class on 'vocational languages' for years. The year I took it, he was using Python for the first time. It was relatively new language then. He figured it was going to replace the scripting language perl. Little did he realise that it was to become _the_ pre-eminent language in data science and machine learning. But it was a gift to me to be engaged with a language so early on. Dozens of my papers have been touched by Python in some way or another. \n", 89 | "\n", 90 | "At my current department, it's impossible to stand still. AI and machine learning are rapidly suffusing every domain of academic life in some way or another. I cannot keep teaching the same material or in the same way year on year. Who knows? In ten years I might not be teaching with Python at all! Even up until 2014 I was just teaching with script files and not Jupyter. It wasn't until around 2015 that I was using pandas! Sometimes these decisions seem a little late and sometimes they seem a little early. But they're always a risk. It's easier to teach what you know. But it's important to teach what students _need to know_ and that's always a risk. More times than I can count I've been asked a question that I felt like I _should_ have known the answer but didn't. Taking these risks is challenging and I've looked to some of my best teachers in the past to see how they navigated unknown and choppy waters. And in the end it's all the same - treat teaching as an opportunity to learn and not just an opportunity to teach. \n", 91 | "\n", 92 | "I wish I could list all my great teachers here, but that list is more important to me than you. So why not take a couple seconds and reflect yourself on those teachers in your life who took a risk to teach you something new? I think these people are all around us if we know where to look and act like we want to learn. So this book goes out to them. " 93 | ] 94 | } 95 | ], 96 | "metadata": { 97 | "kernelspec": { 98 | "display_name": "Python 3 (ipykernel)", 99 | "language": "python", 100 | "name": "python3" 101 | }, 102 | "language_info": { 103 | "codemirror_mode": { 104 | "name": "ipython", 105 | "version": 3 106 | }, 107 | "file_extension": ".py", 108 | "mimetype": "text/x-python", 109 | "name": "python", 110 | "nbconvert_exporter": "python", 111 | "pygments_lexer": "ipython3", 112 | "version": "3.9.7" 113 | } 114 | }, 115 | "nbformat": 4, 116 | "nbformat_minor": 4 117 | } 118 | -------------------------------------------------------------------------------- /chapters/Ch.01.IntroducingPython.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# What is Python?\n", 8 | "\n", 9 | "[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/berniehogan/introducingpython/main?filepath=chapters%2FCh.01.IntroducingPython.ipynb)\n", 10 | "[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/berniehogan/introducingpython/blob/main/chapters/Ch.01.IntroducingPython.ipynb)\n", 11 | "\n", 12 | "Python is a programming language. It is interpreted by the computer and transformed into low level code that can be interpreted by a processor. To make statements in Python, the most direct way is to type commands into a \"Python console\" (for example, by opening the terminal, or on windows the \"anaconda prompt\", then typing \"python\"). If you already have Python installed, on a Mac or Linux computer (and maybe someday Windows PowerShell) you can open up the terminal and type `python`. Then you will see a welcome message and a series of three chevrons, like so: (with what is likely to be some slight difference in the welcome message depending on your setup.)\n", 13 | "\n", 14 | "~~~ python\n", 15 | "Python 3.7.3 (default, Mar 27 2019, 16:54:48) \n", 16 | "[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin\n", 17 | "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n", 18 | ">>>\n", 19 | "~~~\n", 20 | "\n", 21 | "And in here you can enter commands. For more complex work, you will want to turn to Jupyter notebooks and Python script files (`*.py` files). \n", 22 | "\n", 23 | "To exit the Python console, type `exit()` or press control-D. Then you will see the standard prompt, which will likely be either a single chevron (`>`) or a `\\$`. \n", 24 | "\n", 25 | "In this book, I am writing as if we are working in a Jupyter lab environment. You might be reading this on the screen or in a book form. But we will act as if the grey shaded areas are blocks of code that you can run, and the unshaded areas, including code, are just text to read. \n", 26 | "\n", 27 | "Because this book began its life as a Jupyter notebook, it leverages certain features of Jupyter, such as _syntax highlighting_. So you will see different text in a different `font` or colour, such as: " 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "print(\"Hello world\")" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "Instead of typing into a console, we will be typing Python into cells in a Jupyter notebook and running these. This makes it like halfway between running piecemeal in a console or running all-at-once in a single script. " 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "# Working with Anaconda and Jupyter\n", 51 | "\n", 52 | "One of the best things about Python is that it now has an entire ecosystem for scientific computing. In this book we will be using the incredible Anaconda package for Python. This package includes a recent version of the base Python language and a bunch of useful libraries for scientific computing. This book will not make use of most of these libraries, but they do feature in data science work generally. \n", 53 | "\n", 54 | "In addition to installing Python, Anaconda comes with a few ways to code and develop Python programs. For standalone programs there's Spyder. It is a very involved development environment with features to help in developing code that spans multiple script files. Similar to Spyder is PyCharm, which is not presently included in Anaconda. But one program is especially useful, and that's Jupyter. Jupyter is a browser-based tool for viewing Python code alongside text, figures and results. It's like a _Microsoft Word_ document where paragraphs can be run and results can be inserted directly into the document. Jupyter Lab is like a workspace where you can run multiple files in different tabs, like browser windows. It also has a nice and growing set of extensions, such as my personal favorite, the Table of Contents extension.\n", 55 | "\n", 56 | "These documents are called _notebooks_. Their default extension is `.ipynb`, which stands for \"ipython notebook\". Before Jupyter there was a souped up Python console called ipython. You can still run it from the terminal by typing `ipython`. But Jupyter is like a souped up ipython.\n", 57 | "\n", 58 | "Jupyter notebooks can be run on their own in a variety of ways.\n", 59 | "\n", 60 | "1. The Jupyter notebook app, which you can run that from the \"Anaconda Navigator\" application. You can also run it from the terminal by typing `jupyter notebook` (that's the regular terminal `\\$`, not the Python console `>>>`). \n", 61 | "2. If you have a Google account, you can go to [https://colab.google.com](Google Colab) and upload your notebook or start a new one. If you store your notebooks on your Google drive you can open them in Google Colab by right clicking on them and selecting open with → Google Colab. There are similar open source and university run services like [Binder](https://mybinder.org). They tend not to be as polished as Google but might be right for you and do not require you to have a Google account. \n", 62 | "3. You can read a Jupyter notebook if it has been uploaded to **GitHub repository**. Often these notebooks also have little badges in them you can click, like \"Open in Google Colab\". This book does not, yet. But it will render the file even though you cannot run the code there. \n", 63 | "4. Last but definitely not least, Jupyter Lab is the most fully fledged way to run Jupyter notebooks. It is my current Python coding environment of choice. You can run it from the Terminal by typing `jupyter lab`. " 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": {}, 69 | "source": [ 70 | "## How to get Python, Anaconda, and Jupyter?\n", 71 | "\n", 72 | "To get the Anaconda package and all the bells and whistles, you'll need about 2-3 GB space on your computer. It's a big ask on smaller devices, but it's very thorough especially with packages like `pandas` (tables) and `matplotlib` (drawing) which can be a real pain on their own. I personally wish they threw in `geopandas` because as of this writing, it is still a separate install and it is really, really fussy. \n", 73 | "\n", 74 | "When you download and install Anaconda, you will get an application called _Anaconda Navigator_. This is an application hub that allows you to open and run a variety of applications for scientific computing. The first application in the upper left corner is probably Jupyter Lab and the second is Jupyter. If you haven't used the terminal before you might find it easier to run Jupyter from the Navigator application, but I prefer to run it directly from the Terminal (or when using windows, running it from the `Anaconda PowerShell`). " 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "metadata": {}, 80 | "source": [ 81 | "## Which version of Anaconda? \n", 82 | " \n", 83 | "There are many versions of Anaconda. For your computer, you will want to select the one for the right **operating system** (MacOS, Windows, or Linux...but not ChromeOS or iOS, these mobile-oriented operating systems are not ready for data science). \n", 84 | "\n", 85 | "Then you will want to choose your version of Python. Get the latest one. As of this writing that would be the Python 3.8 graphical installer for your preferred OS. It will be the \"individual version\", not enterprise or anything more fancy. You will almost certainly want a 64-bit version. " 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "# Getting started with Jupyter Lab \n", 93 | "\n", 94 | "When you click on the Jupyter Lab icon in the Anaconda Navigator it should open up your default web browser and navigate to a page with the following URL: http://localhost:8888/lab . This URL is a little different from conventional URLs. Instead of a domain name like www.eff.org, it is just the word `localhost`. This is your machine. It turns out Jupyter lab is actually a small server running on your computer that is serving you the application through a browser. The `8888` is a port number. A server communicates using different ports, often for different services. Standard unencrypted web traffic runs through port 80, while email often runs through ports 25 and 587. When I say open Jupyter Lab, I mean navigate to that particular browser tab that is running Jupyter Lab. Remember, however, if Jupyter is not running in the background then `localhost:8888` will just display a blank page. You must launch the server first and then you can use it. \n", 95 | "\n", 96 | "When you open Jupyter Lab for the first time, you'll be greeted with a navigation pane on the left and side and a single tab open labeled 'Launcher'. You can use the Launcher to create a new Jupyter notebook. Create one using the first button (labeled \"Python 3\"). This is the default Python Jupyter notebook. There are a few other types of notebooks that you can create at this point. \n", 97 | "\n", 98 | "Here are some useful details about Jupyter Lab: \n", 99 | "1. _The browser address bar._ This is where you would type a URL. At the moment, it probably shows localhost:8888/lab. This means that you are looking at a webpage that is run from your local computer. 'localhost' is a shorthand for the Internet Protocol (IP) address for one's own computer. \n", 100 | "\n", 101 | "2. _The Jupyter file menu._ This is where you can click on commands for Jupyter such as **File**→**New Launcher** so you can create a new notebook. This is not the browser's file menu (which may be hidden if this window is in full screen). Notice one of the file menu items is called 'Kernel'. This is the term for the instance of Python that runs the code, stores data, and returns a result. Each lab notebook has its own kernel. Sometimes we will need to restart the kernel, for example if we accidentally run a command that has no end, such as \"count every number\". The other important thing to note in kernel is that we can clear output. Sometimes, we will want to start our Jupyter notebooks fresh. Clicking **kernel**→**Restart Kernel and Clear All Outputs...** will make sure that all the cells are treated as if they have never ran. It's good to do this and re-run all your code from start to finish before sharing with other people.\n", 102 | "\n", 103 | "3. _The navigation sidebar._ On the left-hand side is where you can select a file or check to see which files are currently running. The top icon is the file icon, it points to a file browser. The navigation is pretty similar to what you would get with a file browser on your computer such as 'Finder' on Mac or 'Explorer' on Windows. \n", 104 | "\n", 105 | "4. _The tabs panel._ With Jupyter Lab you can have multiple tabs available as different workspaces, each using a different Jupyter notebook or file. These tabs work like browser tabs. You can click on one to start working on that tab, drag the panels to change their order and check whether they have been recently saved by seeing whether there is a circle in the tab name on the right-hand side. You'll notice that there's a new file you just created and a second tab called 'launcher'. \n", 106 | "\n", 107 | "5. _The actions panel_. This small panel has some important and common actions like 'save', 'run' and 'stop'. I tend to use keyboard shortcuts for these actions. You will definitely want to notice on this panel where it says the word 'code'. That's where we assign the 'type' of a cell. You can change the type of a cell by selecting a different type from the drop-down menu that appears when you click where it says 'Code'/'Markdown'. On the right hand side it says 'Python 3' which means that this particular notebook interprets code as Python 3 code. The right most dot is a status meter. When the computer is busy running code the circle is filled in and looks like a spot. When the computer is idle the circle is empty and looks like a ring. \n", 108 | "\n", 109 | "6. _The main panel_. This is where the work gets done. In this panel you'll see that content is organised in cells. Each cell can be either 'code', 'Markdown' or 'raw'. **Raw** text is not highlighted and the computer just ignores special characters and code. **Code** means that the contents of a cell are treated as Python code. **Markdown** is text that has extra characters to denote formatting. For example, Markdown uses two asterisks on either side of a string to indicate it should be bold: When I type \\*\\*this\\*\\* into a Markdown panel the text is rendered like **this**. Markdown is discussed more just below.\n", 110 | "\n", 111 | "7. _A Python cell_. You can tell this is a Python cell on your computer because it has _syntax highlighting_ that indicates Python-oriented words and variables. For example, the word 'print' will show up in green and comments will show up in blue. It also will say 'code' in the cell type in the main panel. To run the cell you can do any of the following: \n", 112 | "\n", 113 | " * The file menu. Click \"Run\"→\"Run Selected Cells\". \n", 114 | " * The right facing triangle in the actions panel. \n", 115 | " * (My favourite) Shift-enter on the keyboard.\n", 116 | "\n", 117 | "8. _Code numbers_. When you run a cell, it will report a number off to the left of the cell. That number represents the order in which cells were run. If there is no number that means the cell has not run yet. If you run a cell a second time, it will increment the number, so the number could actually go much higher than the number of cells in the notebook. You can also see a blue bar to the left of the number. Click that bar and it will collapse the output. This is handy if you have just printed out a lot of output but you want to hide it while you work on the code underneath." 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "## How to add text to a Markdown cell\n", 125 | "A markdown cell is one that has text in it. Markdown is a simple way to add features to text, like _italics_, headers, ~~strikethrough~~, and **bold**. In a Jupyter notebook that is rendered, you can click on a cell to see the Markdown that produced the text. Some of the more common things you will see in Markdown:\n", 126 | "\n", 127 | "1. Use two tildes (the ~ character) for ~~strikethrough~~\n", 128 | "2. Use two asterisks (the * character) for **bold**\n", 129 | "3. Use underscores (the _ character) for _italics_. \n", 130 | "4. Lists are auto generated by having several lines, where each starts with an asterisk and a space.\n", 131 | " * Here is a list item\n", 132 | " * A second item\n", 133 | " * These are indented because we had a space before the asterisk\n", 134 | "5. You can also embed code in a Markdown cell. It won't run but it will have syntax highlighting and a monospaced font. This is using three tildes and then the name of the language like so: \n", 135 | "\n", 136 | " \\~~~ python\n", 137 | " \n", 138 | " print(\"Hello World\")\n", 139 | " \n", 140 | " \\~~~\n", 141 | " \n", 142 | "and it will be formatted on the screen like: \n", 143 | "\n", 144 | "~~~ python \n", 145 | "print(\"Hello World\")\n", 146 | "~~~\n", 147 | "\n", 148 | "6. Use hash (the # symbol) at the beginning of a line to make it a heading. You can use two hashes to make it a subheading (or three for subsubheading, etc...). \n", 149 | "7. Use the dollar symbol on either side of a formula to use maths notation like $e^{{\\pi}i} = -1$ (and I use it for $commands$ ). \n", 150 | "8. Three or more dashes at the beginning of a line create a straight line across the page \n", 151 | "\n", 152 | "---" 153 | ] 154 | }, 155 | { 156 | "cell_type": "markdown", 157 | "metadata": {}, 158 | "source": [ 159 | "## How to create a new cell / navigate with the keyboard\n", 160 | "\n", 161 | "At any given time only one cell might be in focus. To say 'in focus' means that the cell is editable. This is denoted at the bottom of the screen where it says \"Mode: Edit\". It also means keyboard shortcuts and the computer's list of undo actions refer to the text in that specific cell. When a cell is out of focus, it is still indicated with a blue strip on the left-hand side, but keyboard shortcuts and the undo actions refer to the Jupyter file and cells rather than their contents. At the bottom it will say \"Mode: Command\". It is important to be able to navigate into and out of focus for a given cell with the keyboard if you want to be a fluent user of Jupyter. Being able to have cells of different types organised in your notebooks is where Jupyter shines. For example, you can have one cell of code, then graphical output, a well-formatted table of numbers, and your notes just below. Moving around these cells can help you navigate not just the code, but the overall analysis. It also helps you to think about chunking your code and organising your questions. \n", 162 | "\n", 163 | "To change the focus from one cell to another, you can click on a new cell or 'run' the current cell. To run the current cell, press $shift-enter$. \n", 164 | "\n", 165 | "To get out of focus (\"Mode: Command\" ) you can either: \n", 166 | "\n", 167 | "* Run the current cell ($shift-enter$), \n", 168 | "* Escape the cell ($escape key$).\n", 169 | "* $Single-click$ outside of the cell. \n", 170 | "\n", 171 | "To get in focus (\"Mode: Edit\") you can either:\n", 172 | "\n", 173 | "* Press $enter$,\n", 174 | "* $Double-click$ with the mouse.\n", 175 | "\n", 176 | "If the cell is not in focus you can tell because there is no cursor and pressing up or down will move the blue bar on the left hand side up and down. If it is in focus you can tell because pressing up and down will move the cursor within the cell. \n", 177 | "\n", 178 | "To create a new cell, you have to be out of focus. You can do this by pressing $a$ for above and $b$ for below the current highlighted cell. \n", 179 | "\n", 180 | "To delete a cell, you press $d d$, that's $d$ twice. Remember that this only happens when you are not in focus, otherwise you would just be typing the letters dd into the cell. \n", 181 | "\n", 182 | "To change a cell from 'code' to 'Markdown' you can either:\n", 183 | "\n", 184 | "- Use the menu at the top,\n", 185 | "- When the cell is not in focus you can press $c$ for code, $r$ for raw and $m$ for Markdown. " 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "## How to write formulae in a cell \n", 193 | "\n", 194 | "There are lots of times when it helps to show a formula in addition to some code snippets or claims. For example, here is a formula for getting the average (or specifically the 'arithmetic mean'):\n", 195 | "\n", 196 | "$$ \\bar{x} = \\frac{1}{n} \\sum^{n}_{i=1}x_{i} $$\n", 197 | "\n", 198 | "This formula was not written with Markdown but with a special typesetting language called $\\LaTeX$. Technical papers are often drafted in $\\LaTeX$ as are many books in STEM fields. It is less common in social sciences, but it is really handy. I wrote my dissertation in a combination of $\\LaTeX$ and Markdown.\n", 199 | "\n", 200 | "The formula was given its own line because it was enclosed with `$$` characters. Here is what the code looks like: `\\ bar{x} = \\frac{1}{n} \\sum^{n}_{i=1}x_{i}`. If we enclose it with single `$` it will be a formula inline, like so: $\\bar{x} = \\frac{1}{n} \\sum^{n}_{i=1}x_{i}$. I use inline formulae for most numbers.\n", 201 | "\n", 202 | "If you click on this cell, you can see the formatting underneath. Here we are just using MathJax, which is a subset of LaTeX used for formulae. StackExchange have a nice [brisk tutorial of the syntax of MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). Basically, there is syntax for:\n", 203 | "\n", 204 | "* Superscripts , `x^i` $e^i$, subscripts, `x_i` $e_i$, \n", 205 | "* Fractions, with `\\frac{NUMERATOR}{DENOMINATOR}`, as in $\\frac{x^3}{y_i}$\n", 206 | "* Parentheses (using `\\left(` and `\\right)` to scale properly) as in $\\left(\\frac{\\sqrt{(\\bar{x}-x_i)^2}}{n}\\right)$\n", 207 | "* Summation, product, and related symbols. `\\sum` for $\\sum$, and `\\prod` for $\\prod$.\n", 208 | "* Greek symbols. Use their name for the symbol such as `\\alpha` for $\\alpha$ or `\\omega` for $\\omega$.\n", 209 | "* A host of diacritics, maths symbols, and fonts. Check the tutorial above for clear examples." 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "metadata": {}, 215 | "source": [ 216 | "## The big Jupyter Gotcha \n", 217 | "\n", 218 | "There are many advantages to running code in Jupyter but there are a few caveats. One in particular is really important to discuss right up front: You can run cells in any order even if you do not mean to. From this you can run into some pretty common issues. \n", 219 | "\n", 220 | "1. Running code out of sequence. Imagine that in cell one I clean up some text (for example, I remove all the periods and commas). Then in cell two I run some code on that text (for example, make it ALL CAPS). Now imagine I then go back and do something else in cell one, such as change my code to remove apostrophes as well. So I run cell one again, but skip the second cell. Now my data is not in ALL CAPS and subsequent cells will not get the data they expected. \n", 221 | "\n", 222 | "2. The \"I've changed my variables to make them read better\" issue. This one is my number one gotcha. As an example, I might change a variable name once I get my code working but want to make it more readable. But because Jupyter does not have a great 'find and replace' system, I might forget to change _all_ of the instances of a variable. So if the variable was called `tl` but I want it to be `tweet_list`, then I replace the variable name. But what if I do not change it _everywhere_? There might still be a tl left in the code somewhere. Here's the gotcha: **Therefore, the program keeps running (since `tl` was already created)**. But the next time I restart the program or when you, the reader, try to run my Jupyter notebook, `tl` will not be created, `tweet_list` will. So the program will throw an error that any remaining `tl` is an unrecognised variable. \n", 223 | "\n", 224 | "In general,\n", 225 | "\n", 226 | "- Run your Jupyter cells in order, unless absolutely necessary. \n", 227 | "- If you change a variable, be sure to change it __everywhere__. \n", 228 | "- If you change a cell further up in your code, run every line afterwards. \n", 229 | "- If you send notebooks to other people, then from the menu: \"Kernel\"→\"Restart Kernel and Run All Cells...\". If you get an error then debug it before you send the code to people. " 230 | ] 231 | } 232 | ], 233 | "metadata": { 234 | "kernelspec": { 235 | "display_name": "Python 3 (ipykernel)", 236 | "language": "python", 237 | "name": "python3" 238 | }, 239 | "language_info": { 240 | "codemirror_mode": { 241 | "name": "ipython", 242 | "version": 3 243 | }, 244 | "file_extension": ".py", 245 | "mimetype": "text/x-python", 246 | "name": "python", 247 | "nbconvert_exporter": "python", 248 | "pygments_lexer": "ipython3", 249 | "version": "3.9.7" 250 | } 251 | }, 252 | "nbformat": 4, 253 | "nbformat_minor": 4 254 | } 255 | -------------------------------------------------------------------------------- /chapters/Ch.05.FunctionsClasses.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "toc-hr-collapsed": false 7 | }, 8 | "source": [ 9 | "# Functions and object-oriented programming\n", 10 | "\n", 11 | "[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/berniehogan/introducingpython/main?filepath=chapters%2FCh.05.FunctionsClasses.ipynb)\n", 12 | "[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/berniehogan/introducingpython/blob/main/chapters/Ch.05.FunctionsClasses.ipynb)\n", 13 | "\n", 14 | "Functions allow you to group together related operations in such a way that you can abstract away details in your program. Two main use cases of functions come to mind: \n", 15 | "1. Avoiding repetition and the bugs that can come from inconsistent code;\n", 16 | "2. Grouping together operations used elsewhere (like in list comprehensions and equality comparisons)." 17 | ] 18 | }, 19 | { 20 | "cell_type": "markdown", 21 | "metadata": {}, 22 | "source": [ 23 | "## Defining a function \n", 24 | "\n", 25 | "We have already seen a few functions such as `print()` and `len()`. Building your own functions is a crucial part of coding. Without user-defined functions, you are left with code that is literally just one command after another. With functions you can abstract away the common parts, code them once inside the function, and then send the unique or novel parts to the function as __arguments__.\n", 26 | "\n", 27 | "Below is an example of some repetitive code followed by an example of a function that factors out the parts of the repetitive code. A function starts with `def` (for 'define'), followed by a __name__, and an __argument__ on the same line. Then \"inside\" the function (which is also denoted visually with indentation) is the code that is run each time the function is called. This code will use the values sent in (those are the arguments) and then typically `return` some object as output. " 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "# Try to identify the repetition\n", 37 | "list_result = []\n", 38 | "\n", 39 | "x = 5\n", 40 | "if x %2 == 1: list_result.append(x * 2)\n", 41 | "else: list_result.append(x)\n", 42 | "\n", 43 | "x = 7\n", 44 | "if x %2 == 1: list_result.append(x * 2)\n", 45 | "else: list_result.append(x)\n", 46 | "\n", 47 | "x = 12\n", 48 | "if x %2 == 1: list_result.append(x * 2)\n", 49 | "else: list_result.append(x)\n", 50 | "\n", 51 | "print(list_result) " 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "def doubleIfOdd(num):\n", 61 | " if num % 2 == 1: \n", 62 | " return num * 2\n", 63 | " else: \n", 64 | " return num\n", 65 | "\n", 66 | "print([doubleIfOdd(x) for x in [5,7,12]])" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "To build that function we need to do the four things specified above: \n", 74 | "\n", 75 | "- Name\n", 76 | "- Inputs\n", 77 | "- Calculations\n", 78 | "- Outputs\n", 79 | "\n", 80 | "The name was `doubleIfOdd`, the inputs in this case referred to a single variable called `num`, the calculations referred to the `if-else` statement, and the output referred to what we returned, namely `num` or `num*2`. Below we can see a similar function, except it doubles numbers if they are even. " 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "def doubleTheNumberIfEven (input_number): \n", 90 | " if input_number%2==0:\n", 91 | " return input_number * 2\n", 92 | " else:\n", 93 | " return input_number\n", 94 | " \n", 95 | "numbers = [1,4,6,7,9,14,17]\n", 96 | "\n", 97 | "new_numbers = [doubleTheNumberIfEven(i) for i in numbers]\n", 98 | "\n", 99 | "print(new_numbers)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": {}, 105 | "source": [ 106 | "## Variables have a 'scope'\n", 107 | "A variable that is created inside of a function is not the same as the one created outside of that function even if they have the same name. This is because the variable inside the function is a __local__ variable. Variables created in Jupyter are typically treated as __global__ variables if they are created in a cell but not if they are created inside a function. To be global means that they can be used anywhere in the code. Local variables are created and destroyed within their local context. You can watch this behavior with a code snippet. " 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "# Local / Global scope example 1: Variable in the function stays in there.\n", 117 | "\n", 118 | "def multiplyTheValue(input_number):\n", 119 | " x = input_number * 2\n", 120 | " print(\"Value of x inside the function\",x)\n", 121 | " return x \n", 122 | "\n", 123 | "x = 4 \n", 124 | "output_number = multiplyTheValue(x)\n", 125 | "print(\"Result from the function:\",output_number)\n", 126 | "print(\"Value of x after the function:\",x)\n" 127 | ] 128 | }, 129 | { 130 | "cell_type": "markdown", 131 | "metadata": {}, 132 | "source": [ 133 | "But ```x``` wasn't the argument, ```input_number``` was. So what if we change ```input_number``` inside the function? " 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "# Local / Global scope example 2: Argument sent to function doesn't escape the function.\n", 143 | "\n", 144 | "def multiplyTheValue(input_number):\n", 145 | " print(\"Inside the function\",input_number)\n", 146 | " return input_number \n", 147 | "\n", 148 | "x = 4 \n", 149 | "output_number = multiplyTheValue(x)\n", 150 | "print(\"After the function\",input_number)\n", 151 | "print(\"Value of X after the function:\",x)" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "We sent `x` to the function, at which point it became the value for the `input_number` parameter. So we could use `input_number` inside the function, but then when we try to call it outside the function it throws an error. To make it available outside the function is not an advised code pattern, but it is possible by using the `global` flag." 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "metadata": {}, 165 | "outputs": [], 166 | "source": [ 167 | "# Local / Global scope example 3: Casting a variable as global makes it available outside the function.\n", 168 | "\n", 169 | "def multiplyTheValue(input_number):\n", 170 | " global x\n", 171 | " x = input_number * 2\n", 172 | " print(\"Value of x inside the function\",x,id(x))\n", 173 | " return x \n", 174 | "\n", 175 | "x = 4\n", 176 | "print(\"Value of x before the function\",x,id(x))\n", 177 | "output_number = multiplyTheValue(x)\n", 178 | "print(\"Value of x after the function\",x,id(x))\n", 179 | "print(\"After the function\",output_number)" 180 | ] 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "metadata": {}, 185 | "source": [ 186 | "In this third example, we can see that when we declare x is a global variable inside the function, that value then becomes the value outside of the function. We double ```x``` inside the function and then later when we print x it is no longer 4, it retains the value it had inside the function. " 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "## There are all kinds of ways of passing data to a function. \n", 194 | "\n", 195 | "A function usually has some _parameters_. Parameters are like another word for options or settings. When you define a function, it is parameters that you write between the parentheses. But when you are coding you are more interested in the values of these parameters. These are _arguments_. So in the function: " 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "def tinyexample(word):\n", 205 | " print(\"Tiny examples!\", word)\n", 206 | "\n", 207 | "tinyexample(\"Big ideas!\")" 208 | ] 209 | }, 210 | { 211 | "cell_type": "markdown", 212 | "metadata": {}, 213 | "source": [ 214 | "`word` is the parameter, `\"Big Ideas\"` is the argument. That said, most people use these terms interchangably. \n", 215 | "\n", 216 | "There are a number of different kinds of parameters. Some of these allow a function to take in a flexible number of arguments, others define the type of argument that the parameter will permit. Parameters can take default values. If the parameter has a default value, then one does not need to send an argument when running the function. \n", 217 | "\n", 218 | "Note that since a function can have a combination of different parameter types, the ones without defaults come first. Let's see how some different functions take multiple arguments below: " 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": null, 224 | "metadata": {}, 225 | "outputs": [], 226 | "source": [ 227 | "# Example 1. Just a single positional argument\n", 228 | "def example1(just_name):\n", 229 | " print(just_name)\n", 230 | "\n", 231 | "example1(\"example 1 argument\")" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": null, 237 | "metadata": {}, 238 | "outputs": [], 239 | "source": [ 240 | "# Example 2. A positional argument with a default value\n", 241 | "def example2(arg_name, setting1 = True, setting2 = True ):\n", 242 | " if setting1:\n", 243 | " print(arg_name)\n", 244 | " return\n", 245 | " elif setting2:\n", 246 | " print(arg_name.upper())\n", 247 | " return\n", 248 | " else:\n", 249 | " print(f\"{arg_name} You have disabled the settings\")" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "example2(\"Example 2. Take 1.\")\n", 259 | "\n", 260 | "example2(\"Example 2. Take 2a.\", setting2 = False)\n", 261 | "\n", 262 | "example2(\"Example 2. Take 2b.\", True, False)\n", 263 | "\n", 264 | "example2(\"Example 2. Take 3.\", False, False)" 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": null, 270 | "metadata": {}, 271 | "outputs": [], 272 | "source": [ 273 | "# Example 3. Postional arguments passed but not defined ahead of time\n", 274 | "def example3(just_name, *args):\n", 275 | " if len(args) > 0:\n", 276 | " for i in args: print(i)\n", 277 | "\n", 278 | "example3(\"some data\",\"Maybe\",\"more data\")\n", 279 | "\n", 280 | "# Below, why does it not print 'some data'?" 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": null, 286 | "metadata": {}, 287 | "outputs": [], 288 | "source": [ 289 | "# Example 4. Keyword arguments passed but not defined ahead of time\n", 290 | "def example4(just_name,**kwargs):\n", 291 | " if len(kwargs) > 0:\n", 292 | " for i,j in kwargs.items(): \n", 293 | " print(\"var name:\",i,\"\\tvalue:\",j)\n", 294 | "\n", 295 | "example4(\"example\",\n", 296 | " var1=\"some data from v1\",\n", 297 | " var3=\"Maybe it's v3?\",\n", 298 | " var2=\"v2's valuedata\")" 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": null, 304 | "metadata": {}, 305 | "outputs": [], 306 | "source": [ 307 | "# Example 5. Showing the possibilities (and dangers) of fragile code and weakly cast variables.\n", 308 | "\n", 309 | "def MakeDouble(value):\n", 310 | " try: \n", 311 | " output = value*2\n", 312 | " except TypeError:\n", 313 | " output = None\n", 314 | " \n", 315 | " return output\n", 316 | "\n", 317 | "print( MakeDouble(2) )\n", 318 | "print( MakeDouble(\"Double\") )\n", 319 | "print( MakeDouble([\"2\"]))\n", 320 | "print( MakeDouble({1:4}))" 321 | ] 322 | }, 323 | { 324 | "cell_type": "markdown", 325 | "metadata": {}, 326 | "source": [ 327 | "## A function always returns, but it might be nothing at all.\n", 328 | "\n", 329 | "Your function always stops at the return statement. You can have multiple return statements for different conditions (like saying if...return one thing and else...return another). After the return statement, the remaining code will not be evaluated by the program. But if your function does not have a return statement, Python will still return `None` (which if you remember from above evaluates to `False`). Just try it for yourself. " 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "metadata": {}, 336 | "outputs": [], 337 | "source": [ 338 | "def noReturn():\n", 339 | " pass\n", 340 | "\n", 341 | "print(noReturn())\n", 342 | "\n", 343 | "if noReturn(): \n", 344 | " print(\"Did it work?\")\n", 345 | "else:\n", 346 | " print(\"Oh right, None evaluates to false.\")" 347 | ] 348 | }, 349 | { 350 | "cell_type": "markdown", 351 | "metadata": {}, 352 | "source": [ 353 | "# Classes and Objects \n", 354 | "\n", 355 | "Classes are a means of grouping together relevant variables and methods into a single class. Then a class becomes the template for some kind of object. Stated differently, every object is an object of some type of _class_. Object-oriented programming is one of many paradigms of programming. And not all programs need to be object oriented. Regardless, Python is predominantly object-oriented (as is Java, C++, swift, Objective-C, and Ruby, for example). \n", 356 | "\n", 357 | "To say that a program is object-oriented means that it uses `objects` as a part of its processing. An `object` is the generic term for any data structure that can be created by a program. A nice feature of an object is that it can contain other objects unless it is a 'primitive'. So a character is a primitive but a string is a collection of characters. But we can also have a collection of strings (like a list of strings or a dictionary of key:value pairs). Objects have specialised methods. For example, the string object has `.upper()` or `.lower()` methods. \n", 358 | "\n", 359 | "We would say that objects of the same type are _instances_ of the same _class_. So, above, when I said \"the string object has a...\", that was short hand. More specifically, I could have said \"any instantiated objects of the string class can use the...\" \n", 360 | "\n", 361 | "You can create a class from scratch or extend and existing class. " 362 | ] 363 | }, 364 | { 365 | "cell_type": "markdown", 366 | "metadata": {}, 367 | "source": [ 368 | "## Creating classes using `__init__`\n", 369 | "\n", 370 | "To create an object, you need to first define the class name and the provide an internal method called `__init__`. This method will automatically run every time you create (or \"initialise\") a new object of that type. So if you had a class called `Pizza` which you know creates pizza objects, then you would probably initialise it with a few relevant variables such as `toppings = []`, `sauce='tomato'` , and `base = 'classic'`. You can then modify the pizza object. This would be a basic Pizza class:" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": null, 376 | "metadata": {}, 377 | "outputs": [], 378 | "source": [ 379 | "class Pizza: \n", 380 | " def __init__ (self):\n", 381 | " self.toppings = []\n", 382 | " self.base = 'classic'\n", 383 | " self.sauce = 'tomato'\n", 384 | " \n", 385 | "p = Pizza()\n", 386 | "z = Pizza()" 387 | ] 388 | }, 389 | { 390 | "cell_type": "markdown", 391 | "metadata": {}, 392 | "source": [ 393 | "Now we can consider the pizza object as a combination of multiple other objects that all work together. A shopping cart, for example, might be a class that includes a list of items, a discount code, and an identifier for the customer that owns the shopping cart. Admittedly, for something like pizza or a shopping cart we can also get away with just using a dictionary. That is, we could have simply written: \n", 394 | "\n", 395 | "~~~ python\n", 396 | "pizza = {toppings:[], base:\"classic\",sauce:\"tomato\"} \n", 397 | "\n", 398 | "pizza[toppings].append(\"red peppers\")\n", 399 | "pizza[\"base\"] = \"thin and crispy\"\n", 400 | "~~~\n", 401 | "\n", 402 | "So what is the advantage of using a class rather than this structure? It depends on the purpose. For simple data transfer, actually it is nice to just keep it as dictionaries and lists. Later when we look at JSON files from the web we will see how they are essentially just collections of lists and dictionaries. But when programming, it is useful to be able to have a _structure_ to the various objects that are related to each other. This structure can give some sense to the objects as well as ensure that they all work in sync. For example, what if we want to manage two pizza orders? Will we create another variable called `pizza2`? \n", 403 | "\n", 404 | "Below I will show two approaches to printing off a receipt. Compare how I would do it for a dictionary like above, and then for a class: " 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": null, 410 | "metadata": {}, 411 | "outputs": [], 412 | "source": [ 413 | "cart = {\"items\":[], \"code\":None, \"customer\":None} \n", 414 | "\n", 415 | "cart[\"items\"] = [\"Turntable\",\"Microphone\",\"Keyboard\"]\n", 416 | "cart[\"code\"] = \"HAPPY2020\"\n", 417 | "cart[\"customer\"] = \"Tom\"\n", 418 | "\n", 419 | "print(f'Welcome {cart[\"customer\"]}\\n\\nYour items:\\n{\" \".join(cart[\"items\"])}\\nDiscount code:{cart[\"code\"]}')" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": null, 425 | "metadata": {}, 426 | "outputs": [], 427 | "source": [ 428 | "class Cart: \n", 429 | " def __init__(self):\n", 430 | " self.items = []\n", 431 | " self.code = None\n", 432 | " self.customer = None\n", 433 | " \n", 434 | " def receipt(self):\n", 435 | " message = f\"Welcome {self.customer}\\n\\nYour items:\\n\"\n", 436 | " message += \"\\n\".join(self.items) + \"\\n\"\n", 437 | " \n", 438 | " if self.code:\n", 439 | " message += f\"Discount code:{self.code} applied\"\n", 440 | " return message\n", 441 | " " 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "metadata": {}, 447 | "source": [ 448 | "So above is just the class file. From here we can see a couple differences. The first is that the `receipt` function is inside the `Cart` class. The second is that when we are referring to objects that belong to the `Cart` class inside of the class definition we refer to them as `self.`. So `__init__` is never really called directly, you never say `x = Cart.__init__()`, instead you initialise by saying `x = Cart()`, which then will automatically run the `__init__` method. In this case, it will create three internal variables, `self.items`, `self.code`, and `self.customer`, and give them some values. Although this seems a little overkill compared to the nested dictionary, it creates more of a structure to work with. Then we can create multiple cart instances, as can be seen below. " 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": null, 454 | "metadata": {}, 455 | "outputs": [], 456 | "source": [ 457 | "x = Cart()\n", 458 | "\n", 459 | "x.items = [\"Turntable\",\"Microphone\",\"Mixer\"]\n", 460 | "x.code = \"HAPPYSPINNING\"\n", 461 | "x.customer = \"Chuck\"\n", 462 | "\n", 463 | "print(x.receipt())" 464 | ] 465 | }, 466 | { 467 | "cell_type": "markdown", 468 | "metadata": {}, 469 | "source": [ 470 | "Compare how the receipt was printed this time with the code above. We abstracted away the details of printing to the `receipt()` method of the `Cart` class, which we defined elsewhere. We were still able to access the objects in the `Cart` class, but instead of `self.items`, we first instantiated an object called `x`, and then used `x.items`. Some classes can be fussy and expect you to use a dedicated method to get these objects, like `x.get_items()`. Other times classes allow you to access the objects directly. It's a bit of trial and error as well as checking in on the docs for a particular package. \n", 471 | "\n", 472 | "Below I will create a second object just to demonstrate how we can have separate `Cart` objects and use them together in a `print()` statement." 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": null, 478 | "metadata": {}, 479 | "outputs": [], 480 | "source": [ 481 | "y = Cart()\n", 482 | "y.items = [\"808 Drum Machine\", \"Keyboard\", \"Laptop\"]\n", 483 | "y.customer = \"Caterina\"\n", 484 | "\n", 485 | "print(y.receipt(),x.receipt(),sep=\"\\n###########\\n\")" 486 | ] 487 | }, 488 | { 489 | "cell_type": "markdown", 490 | "metadata": {}, 491 | "source": [ 492 | "## Extending classes and inheriting values\n", 493 | "\n", 494 | "There are instances in both data access and machine learning where the task will have a class that's almost fit for purpose but typically there will be a few key functions missing. You could then 'extend' this class with your own version of these methods. \n", 495 | "\n", 496 | "One example concerns Twitter data. So there is a way to get the Python to listen for new tweets based on some criteria, such as when someone tweets `#BLM`. In the `twitter` library this is done using the `StreamListener` class. When you instantiate a stream listener, it will handle many of the details automatically, like connecting to Twitter and receiving data according to your search parameters. However, it simply listens and does not do anything with the data it receives. For you to do something with the data, you need to _extend_ the `StreamListener` class. This extension, perhaps called `CustomStreamListener` will _inherit_ all the methods and objects in the `StreamListener` class, but you can add your own additional methods. One method that it will look for is called `on_data`. This method will be called anytime there is a tweet that appears according to your search terms, and then you get to define what to do with that data. For example, in the `on_data()` method, you could fill it with instructions such as \"check for hate speech\" or \"store in a database\" or \"reply automatically with a messsage\". \n", 497 | "\n", 498 | "Here is a simple example building on the `Cart` above. Notice that in the `Trolley` class (which is what you would often call a cart in the UK), we do not say `self.items` or `self.customer` since they were _inherited_ from the `Cart` class. But now we will add a user `post_code`, since in the UK addresses have post codes. " 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "metadata": {}, 505 | "outputs": [], 506 | "source": [ 507 | "class Trolley(Cart): \n", 508 | " def __init__(self): \n", 509 | " Cart.__init__(self) # observe what happens if you remove this!\n", 510 | " self.post_code = \"OX1 3JS\"\n", 511 | " \n", 512 | " def delivery(self):\n", 513 | " message = \"Your basket currently includes:\\n\"\n", 514 | " message += \"\\n\".join(self.items) + \"\\n\"\n", 515 | " message += \"It will be delivered to \" + self.post_code\n", 516 | "\n", 517 | " return message" 518 | ] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": null, 523 | "metadata": {}, 524 | "outputs": [], 525 | "source": [ 526 | "z = Trolley()\n", 527 | "z.items = [\"Cables\",\"Cassette Player\"]\n", 528 | "\n", 529 | "z.placename = \"OII\"\n", 530 | "\n", 531 | "print(z.receipt())\n", 532 | "\n", 533 | "print(z.delivery()) " 534 | ] 535 | }, 536 | { 537 | "cell_type": "markdown", 538 | "metadata": {}, 539 | "source": [ 540 | "## Reasons to use a class\n", 541 | "\n", 542 | "Part of the reason for showing a class is that it helps us understand the basis of objects, as each object is necessarily an __instance__ of some _class_ of object. Later when we will be working with data, we will be using DataFrames, which are tables that contain data. These `DataFrame` objects have their own methods, but also _inherit_ methods. We will want to know how to create an instance of a `DataFrame` object, what it means to send different arguments, and to query for parts of the `DataFrame`. Observing the code below: \n", 543 | "\n", 544 | "~~~ python\n", 545 | "import pandas as pd \n", 546 | "\n", 547 | "df = pd.DataFrame(columns=[\"name\",\"age\"]) \n", 548 | "~~~\n", 549 | "\n", 550 | "You can already notice that `pandas` is a library. In this library, which we have imported under the name `pd` for short, is a class called a DataFrame. By calling `df = pd.DataFrame()` we are creating an __instance__ of the DataFrame class called `df`. By using `cols=[\"name\",\"age\"]` we are sending these two values to the `DataFrame.__init__` method. Thus, when it initialises the DataFrame object `df`, we will have a table with two columns, `name` and `age`. See below (notice that it will possibly run slow the first time you `import pandas`). " 551 | ] 552 | }, 553 | { 554 | "cell_type": "code", 555 | "execution_count": null, 556 | "metadata": {}, 557 | "outputs": [], 558 | "source": [ 559 | "import pandas as pd \n", 560 | "\n", 561 | "# An empty table with two columns and five rows\n", 562 | "df = pd.DataFrame(columns=[\"name\",\"age\"],index=range(5)) \n", 563 | "df" 564 | ] 565 | }, 566 | { 567 | "cell_type": "markdown", 568 | "metadata": {}, 569 | "source": [ 570 | "The DataFrame in this case is now an empty table. To create a table with data or to manipuate data is outside the scope of this book. Rather it is where we start off in the book \"From Social Science to Data Science\". " 571 | ] 572 | }, 573 | { 574 | "cell_type": "markdown", 575 | "metadata": {}, 576 | "source": [ 577 | "# Conclusion\n", 578 | "\n", 579 | "Now we can see how programming can become pretty complicated, with objects referring to other objects and other functions or methods all over the place. Often times, when I'm trying something new with programming I often have check the documentation or print a lot to get a sense of what methods an object has available or simply to determine what type of object was returned from some method or function. Being able to understand how to query an object or manipulate it will be an important skill moving forward in Python and in giving your scripts some structure. This structure is not merely for its own sake. It helps to create code that is more reusable and robust. By structuring our code we are structuring our ideas about data. That is good if we want to do something repeatedly or consistently across many cases. \n", 580 | "\n", 581 | "The last chapter does not expand our basic programming knowledge much. Instead, the next chapter will focus on how to get out of Jupyter by writing Python scripts as well as by learning the basics of how to read and write files. " 582 | ] 583 | } 584 | ], 585 | "metadata": { 586 | "kernelspec": { 587 | "display_name": "Python 3 (ipykernel)", 588 | "language": "python", 589 | "name": "python3" 590 | }, 591 | "language_info": { 592 | "codemirror_mode": { 593 | "name": "ipython", 594 | "version": 3 595 | }, 596 | "file_extension": ".py", 597 | "mimetype": "text/x-python", 598 | "name": "python", 599 | "nbconvert_exporter": "python", 600 | "pygments_lexer": "ipython3", 601 | "version": "3.9.7" 602 | }, 603 | "toc-autonumbering": true 604 | }, 605 | "nbformat": 4, 606 | "nbformat_minor": 4 607 | } 608 | -------------------------------------------------------------------------------- /chapters/Ch.07.WhereToNext.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Continuning your Python learning \n", 8 | "\n", 9 | "There's a real challenge for people after just learning the basics of a language. And it's endemic to books teaching Python as well. After the basics they tend to fray outwards in a variety of directions, primarily reflecting the interest of the author. One of the books that I enjoyed in this regard was the now a little dated Python Crash Course by Eric Matthes. In that book after the basics (which frankly are pretty similar to what's included here), he presents projects which are considerably different in scope and technique, such as a video game and a data science project. I think that's the right approach. From here I hope you'll consider these skills as helping you consider a programmatic way of thinking. I don't want to say a new way, as we employ programmatic thinking all the time: sorting the laundry, organising a bookshelf, or preparing dinner step-by-step all have vestiges of algorithmic reasoning. \n", 10 | "\n", 11 | "Now as it happens, algorithmic reasoning gets applied to many areas of human behavior, sometimes to the detriment of those whose behavior it shapes. We hear of cold bureacracies with endless forms, unfair job hiring, or police profiling of certain communities based on 'data'. These are very real and very consequential, down to the price of the food you buy and the quality of the air you breathe. It's hard to fully participate in a world governed so heavily be algorithms without a sense of how to create one yourself. In that sense, I see this sort of work as partially a journey of empowerment. You can ask questions at a different scale with programming. But imagination is also part motivation and part inspiration. " 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "metadata": {}, 17 | "source": [ 18 | "The first thing you'll need on this journey will be the standard tools. Often people sidestep these for searching on Stack Exchange or Google first. But I say start with some basics: _read_, read the [documentation](https://docs.python.org/3/library/pydoc.html) particularly. This is not just the specific instructions for a particular module or form of syntax. It includes tutorials and installation guides as well. It's worth being careful, however, that you're mindful of the version for the docs. Python is currently running version 3.10 as of December 2021. Anaconda is running 3.9. It's okay for the version to be a little behind, but since the language does evolve, there are always bound to be some new things. I find that some of the newer things to be really clever solutions to repetitive code issues (like the walrus operator). \n", 19 | "\n", 20 | "One place that's especially useful for understanding how Python evolves are the PEP or Python Enhancement Proposals. One in particular is worth reading whenever you get the chance, [PEP-8](https://www.python.org/dev/peps/pep-0008/), which is the recommended style guide. As it happens I do not 100% follow the guide. Or maybe I do? As it says in the style guide: \"A Foolish Consistency is the Hobgoblin of Little Minds\". It's okay to be a little out of sync with any specific Python style, but it is preferable to be as consistent as possible, particularly within project. In fact, it's interesting to me to read other people's code and understand when they have a 'style' to their programming. To me it really does seem like a voice for some people. \n", 21 | "\n", 22 | "Ok, but these are pretty dry. Read the docs? Seriously? No, seriously. It's kind of like the vegetables of your learning diet. But they're cooked well and pretty seasoned. Beyond that, I've grouped some resources into different categories. And this is a very partial list. " 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "metadata": {}, 28 | "source": [ 29 | "## Websites\n", 30 | "\n", 31 | "Some websites are especially thorough when teaching Python, with pages dedicated to single topics. If you find that the coverage of a topic here (which is often just a paragraph and a single example) is not enough, it's worth having a look at the following sites: \n", 32 | "\n", 33 | "- __w3schools__ (https://www.w3schools.com): They have very extensive examples for many specific Python concepts, but many other web technologies as well. The examples are very sparse though. With Python you are often getting a clear view on a single concept rather than a sense of how this concept fits into a larger whole. \n", 34 | "- __realpython__ (https://realpython.com/): This one is similar to w3schools. It locks away some advanced content for paid subscibers, which is a shame. This tends to be the case for a lot of sites. \n", 35 | "- __Towards Data Science__ (https://towardsdatascience.com/): This is presently a blog on Medium, so it suffers from the same paid content issues. But I think that the blog posts on this site tend to be the right size for me. Digestable and often well-contextualised. It's not painfully slow and repetitive, but is still slow enough to be clear (at least for topics that are just at the cusp of where my own learning is). \n", 36 | "- __Data Carpentry__ (https://datacarpentry.org/): This non-profit community-driven site has some excellent tutorials on all skills levels in Python. It think it's both a great resource for it's content but also of how it's produced. That said, it is not as thorough as w3schools or realpython. It's more practice based and for specific concepts. That being said it is a great place to learn about some things just beyond this book. \n", 37 | "- __Jake Van Der Plas' Python Repositories__. Jake was early out of the gate with a book that doubles as a Jupyter notebook. He's the author of a [Whirlwind Tour of Python](https://github.com/jakevdp/WhirlwindTourOfPython), which is very close in spirit and style as this book, and the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook), both from O'Reilly. I really want to cheer on these two books especially. Similarly written in Jupyter Notebooks and available on GitHub, they are a great complement, though perhaps with a little less social science flair. " 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "## Communities and forums\n", 45 | "\n", 46 | "- __StackExchange__: I suspect this will end up being one of your more regularly visited sites when trying to solve problems in Python. StackOverflow for coding is a vast and useful resources. But be cautious on the site. Read the answer rather than cut-paste-and-hope. Tinker with the example a little before trusting it. It often pays off to know what you're getting into with someone else's code. Notice in the threads that there's sometimes a discussion - this can be worth engaging. People often point out how it works differently on later versions or how it could be simplified. \n", 47 | "- __Reddit__: Reddit has a variety of places for learning new programming skills. I find the [LearnPython](https://www.reddit.com/r/learnpython/) community to be pretty civil and welcoming. Sort the content by top or by top this year to find a lot of walkthroughs, guides, and cheat sheets. The larger /r/Python and /r/DataScience subreddits can show some interesting projects as well, but are often more geared to those with programming experience. See what they are up to as well. \n", 48 | "- __Twitter__: Twitter can often surface some real gems that might be hidden otherwise. Follow those practicing the sort of skills you want to learn. If there's an author of a package out there you find useful, check out their feed. Academics are particularly keen to share code and notebooks on Twitter. \n", 49 | "\n", 50 | "Beyond this, tons of social media sites will have resources, news, and discussion about programming." 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "## Online courses \n", 58 | "\n", 59 | "There are a ton of online courses available. I would recommend any courses that are somewhat goal focused or practice based to get you exploring with some hands on experience. But they all have their place to reinforce your learning. Just know that strictly following someone else's tutorial will not build the creative spark needed to advance your work. Codeacademy, Udemy, and Coursera are all examples of these sorts of sites. Personally, I think the tutorials and help pages for many projects themselves offer a solid foundation for learning a new skill, but there is still some merit to having it structured. \n", 60 | "\n", 61 | "What is most useful to me, however, is having some sort of feedback or results from your work. Thus finding coding communities, hackathons, or user groups might enliven your experience considerably. Not all places are equally welcoming, unfortunately. It pays to shop around if you find a user group or community to be unwelcoming. But don't give up, people of all kinds of attitudes, identities, and ideologies are picking up programming and making it their own. " 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "# Ideas for directions next \n", 69 | "\n", 70 | "Because Python is now so widely diffused, once you get the basics you can go in a huge number of directions. There's full fledged ways in python to make maps ([geopandas](https://geopandas.org/en/stable/) and [pysal](https://pysal.org/)), detect objects in images ([opencv](https://opencv.org/)), do social network analysis ([networkx](https://networkx.org/)), process text ([nltk](https://www.nltk.org/) and [spacy](https://spacy.io/)), produce a blog ([django](https://www.djangoproject.com/)), and more. Some of these approaches emhpasise different parts of Python. For some, it is about creating a listener that will receive input (like mouse movement), for others it is about managing large streams of data, or interacting with complex objects. \n", 71 | "\n", 72 | "Basically, try attaching pretty much any programming task or domain with \"Python\" these days and you are likely to find somebody working on it. Try searching around the internet, and especially [PyPi](https://pypi.org/), which is a huge repository of Python modules. You'd be surprised at not only how far Python can take you, but how far you can get with the skills herein. \n", 73 | "\n", 74 | "Safe travels and many happy `return` statements. " 75 | ] 76 | } 77 | ], 78 | "metadata": { 79 | "kernelspec": { 80 | "display_name": "Python 3 (ipykernel)", 81 | "language": "python", 82 | "name": "python3" 83 | }, 84 | "language_info": { 85 | "codemirror_mode": { 86 | "name": "ipython", 87 | "version": 3 88 | }, 89 | "file_extension": ".py", 90 | "mimetype": "text/x-python", 91 | "name": "python", 92 | "nbconvert_exporter": "python", 93 | "pygments_lexer": "ipython3", 94 | "version": "3.9.7" 95 | } 96 | }, 97 | "nbformat": 4, 98 | "nbformat_minor": 4 99 | } 100 | -------------------------------------------------------------------------------- /exercises/Ch.A01.ShortQuestions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Short questions for practice \n", 8 | "\n", 9 | "[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/berniehogan/introducingpython/main?filepath=exercises%2FCh.A01.ShortQuestions.ipynb)\n", 10 | "[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/berniehogan/introducingpython/blob/main/exercises/Ch.A01.ShortQuestions.ipynb)\n" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "Below are some short exercises to check your knowledge of the topics introduced in each of the chapters. Each section corresponds to one of the prior chapters in the book. After these are two more appendices. Appendix 2 is just this appendix but with some example code for answers for the questions below. Finally, in Appendix 3 is is a series of longer creative exercises that you might want to attempt with skills from this book. They are marked by which skills you would reasonably need to try your hand at the exercise.\n", 18 | "\n", 19 | "In many cases I have provided some starter code and you should finish that code. You'll see where you should finish with an `...` or a similar sort of marker." 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "# Chapter 1. Introducing Python " 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "Just one question here: Is this running in Jupyter lab? " 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "# Chapter 2. Data Types" 41 | ] 42 | }, 43 | { 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | "## Practicing making strings\n", 48 | "\n", 49 | "The first few exercises are just to warm you up to working with strings. " 50 | ] 51 | }, 52 | { 53 | "cell_type": "markdown", 54 | "metadata": {}, 55 | "source": [ 56 | "### Debug one" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "print \"So this is how we start, eh?\"" 66 | ] 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "metadata": {}, 71 | "source": [ 72 | "### Debug two" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "print(\"Well, \"so far so good\", as I like to say\")" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "### Debug three" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": null, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "print(\"This should be line 1.\"\\n\"This should be line 2.\")" 98 | ] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "metadata": {}, 103 | "source": [ 104 | "## Making a greeting\n", 105 | "\n", 106 | "With this exercise, you should learn about string insertions. \n", 107 | "We will do them three ways: \n", 108 | "\n", 109 | "1. Using a + to concatenate the strings\n", 110 | "2. Using `\"{}\".format()`\n", 111 | "3. Using `f\"{! My name is and I'm from . Someday I hope to get to , got any suggestions?`\n", 116 | "\n", 117 | "Remember you can check on https://pyformat.info/ " 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": {}, 124 | "outputs": [], 125 | "source": [ 126 | "greeting = ''\n", 127 | "name = ''\n", 128 | "origin = ''\n", 129 | "destination = '' \n", 130 | "\n", 131 | "# First using a +, as in print(var+var+var...)\n", 132 | "st1 = ...\n", 133 | "\n", 134 | "# Second using .format, as in print(\"{}\".format(vars))\n", 135 | "\n", 136 | "st2 = ...\n", 137 | "# Third using f insertions, as in print(f\"{var}{var}\")\n", 138 | "\n", 139 | "st3 = ...\n", 140 | "\n", 141 | "print(st1 == st2 == st3)\n", 142 | "print(st1)\n" 143 | ] 144 | }, 145 | { 146 | "cell_type": "markdown", 147 | "metadata": {}, 148 | "source": [ 149 | "# Chapter 3. Collections\n", 150 | "\n", 151 | "Below are some exercises for the chapter on collections. " 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "## Building an algorithm to reproduce concrete poetry\n", 159 | "\n", 160 | "There's not much you can do in Python exclusively by printing strings. However, I thought this would be a nice opportunity to produce some concrete poetry. Concrete poetry means the visual arrangement of the words has meaning as do the words. Ian Hamilton Finlay is a Scottish concrete poet. Below I have pasted a version of his poem \"acrobats\" as excerpted from Cockburn K. and Finlay, A (2001) _The Order of Things_. Edinburgh, UK: Pocketbooks." 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "a a a a a\n", 170 | " c c c c\n", 171 | "r r r r r\n", 172 | " o o o o\n", 173 | "b b b b b\n", 174 | " a a a a\n", 175 | "t t t t t\n", 176 | " s s s s" 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "metadata": {}, 182 | "source": [ 183 | "Using only a variable `word = \"acrobats\"`, string insertions, spaces, and lists, try to print a reproduction of the poem. \n", 184 | "\n", 185 | "In this version, the answer below should be done _without_ `for` loops or `if` statements, which means it will likely have some repetition. Your goal is to minimise that repetition even if you can't eliminate it. " 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "# Complete the answer: (I wrote some code to get you started)\n", 195 | "\n", 196 | "word = \"acrobats\"\n", 197 | "print((word[0] + \" \")*5) \n", 198 | "...\n", 199 | "...;" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "metadata": {}, 205 | "source": [ 206 | "## A Table of Muppets \n", 207 | "\n", 208 | "The following questions use a table of values with some details from key Muppet characters in the show \"The Muppet Show\". We have the data in one form which is just raw text, which we will clean up so we can ask questions about it. " 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "### Splitting strings into lists\n", 216 | "\n", 217 | "This data is presented as a string. It is structured as what we call tab-separated values (`.tsv`). Let's change it so that it is a list of lists. Below you can do this without a `for` loop as that is featured in the subsequent chapter. It will be important to think of how you deploy the `.split()` method since you will need to split both by line and then within line. \n", 218 | "\n", 219 | "Doing this without a for loop might involve using nine repetitions of basically the same code. So I will show that and I will also include a `for` loop version. \n", 220 | "\n", 221 | "Your final data structure should have nine elements. Each one will be a row with data. If you have 11 check that you have not included lines for the empty top and bottom lines of the text. " 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | " \n", 231 | "muppet_text = '''\n", 232 | "name\tgender\tspecies\tfirst_appearance\n", 233 | "Fozzie\tMale\tBear\t1976\n", 234 | "Kermit\tMale\tFrog\t1955\n", 235 | "Piggy\tFemale\tPig\t1974\n", 236 | "Gonzo\tMale\tUnknown\t1970\n", 237 | "Rowlf\tMale\tDog\t1962\n", 238 | "Beaker\tMale\tMuppet\t1977\n", 239 | "Janice\tFemale\tMuppet\t1975\n", 240 | "Hilda\tFemale\tMuppet\t1976\n", 241 | "'''\n", 242 | "\n", 243 | "# Complete this answer: \n", 244 | "\n", 245 | "muppet_list = [...]*9 #Replace [...]*9 with your answer\n", 246 | "\n", 247 | "muppet_list[0] = ... \n", 248 | "muppet_list[1] = ...\n", 249 | "\n", 250 | "\n", 251 | "print(muppet_list)" 252 | ] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "metadata": {}, 257 | "source": [ 258 | "### Separating the header from the rest. \n", 259 | "\n", 260 | "Take muppet_list and then slice it so that you have two lists:\n", 261 | "`muppet_header` is only of length one, it's the header. `muppet_data` is the other list and contains the remianing elements. Check that the length of `muppet_data` is `8`. " 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "metadata": {}, 268 | "outputs": [], 269 | "source": [ 270 | "# Answer \n", 271 | "muppet_header = ...\n", 272 | "muppet_data = '...'\n", 273 | "\n", 274 | "print(f\"It is {len(muppet_data) == 8} that the Muppet Data has 8 rows\")" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": {}, 280 | "source": [ 281 | "### Transforming the `muppet_data` into a `muppet_dict`\n", 282 | "\n", 283 | "At this point, we should have 8 lists in a data structure called `muppet_data`. The first element in this list is the name, followed by three data points (`gender`, `species`, `first_appearance`).\n", 284 | "\n", 285 | "Transform each line into a dictionary entry so that the whole dictionary will look something like this: \n", 286 | "\n", 287 | "~~~ python\n", 288 | "muppet_dict = {\"Fozzie\":[\"Male\",\"Bear\",1976], \n", 289 | " \"Kermit\": ..., \n", 290 | " ...}'''\n", 291 | "~~~\n", 292 | "\n", 293 | "To create this dictionary you might need to repeat lines of code while only changing the indices. \n", 294 | "\n", 295 | "This will be the last repetitive code example to complete. I will give fewer instructions here. If you know loops, you can try them here, but I am assuming you have not skipped to chapter 3. In case you have, know that I provide two answers to this in the next appendix. One with and one without loops. " 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "# Answer\n", 305 | "\n", 306 | "m_dict = {} \n", 307 | "\n", 308 | "m_dict[muppet_data[0][0]] = ...\n", 309 | "m_dict[muppet_data[1][0]] = ...\n", 310 | "...\n", 311 | "\n", 312 | "print(m_dict)\n", 313 | "print(f\"It is {len(m_dict.keys())==8} that the muppet_dict has 8 keys.\")" 314 | ] 315 | }, 316 | { 317 | "cell_type": "markdown", 318 | "metadata": {}, 319 | "source": [ 320 | "### Query the muppet data (Tougher bonus challenge)\n", 321 | "\n", 322 | "Use the following code pattern: \n", 323 | "\n", 324 | "~~~ python\n", 325 | "user_input = input(\"Which muppet do you want to profile:\")\n", 326 | "~~~ \n", 327 | " \n", 328 | "Then take the data from `user_input` and print a profile of the muppet in the following form: " 329 | ] 330 | }, 331 | { 332 | "cell_type": "raw", 333 | "metadata": {}, 334 | "source": [ 335 | "Character: \n", 336 | " Fozzie\n", 337 | "Profile: \n", 338 | " Gender: Male\n", 339 | " Species: Bear\n", 340 | " First Appearance: 1976" 341 | ] 342 | }, 343 | { 344 | "cell_type": "markdown", 345 | "metadata": {}, 346 | "source": [ 347 | "Consider printing a list of all muppets (i.e. all keys from the dictionary) before asking for user input so the user can get the correct spelling. You might find other ways to make this robust, especially after reading in the later chapters. " 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": null, 353 | "metadata": {}, 354 | "outputs": [], 355 | "source": [ 356 | "user_input = input(\"Which muppet do you want to profile:\")\n", 357 | "\n", 358 | "print(...)" 359 | ] 360 | }, 361 | { 362 | "cell_type": "markdown", 363 | "metadata": {}, 364 | "source": [ 365 | "# Flow control" 366 | ] 367 | }, 368 | { 369 | "cell_type": "markdown", 370 | "metadata": {}, 371 | "source": [ 372 | "## Fozzie Bear! \n", 373 | "\n", 374 | "This is based on the classic coding challenge, \"Fizz Buzz\". To cheat or compare answers see: https://wiki.c2.com/?FizzBuzzTest. I, like many instructors, like to use FizzBuzz because you cannot simply make it work with one loop and one if statement. Here goes: \n", 375 | "\n", 376 | "Make a program that spits out numbers and the words Fozzie Bear. \n", 377 | "\n", 378 | "- If the line is a multiple of 3 print the line number + Fozzie, like `6. Fozzie\n", 379 | "- If the line is a multiple of 5 print the line number + Bear, like `10. Bear`\n", 380 | "- If the line is a multiple of both, print a line number + both words, like `15. Fozzie Bear` \n", 381 | "- Otherwise do not print anything. \n", 382 | "\n", 383 | "Have the program run in the range 1 to 30 inclusive (so I should read `30. Fozzie Bear` as the final line. " 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": null, 389 | "metadata": {}, 390 | "outputs": [], 391 | "source": [ 392 | "# Answer below here: \n" 393 | ] 394 | }, 395 | { 396 | "cell_type": "markdown", 397 | "metadata": {}, 398 | "source": [ 399 | "## List (and dictionary) comprehension practice" 400 | ] 401 | }, 402 | { 403 | "cell_type": "code", 404 | "execution_count": null, 405 | "metadata": {}, 406 | "outputs": [], 407 | "source": [ 408 | "# 3a. Loop 1. The simplest example.\n", 409 | "\n", 410 | "ex_list = []\n", 411 | "for i in range(1,10): \n", 412 | " ex_list.append(i)\n", 413 | " \n", 414 | "# List comprehension\n", 415 | "\n", 416 | "lc_ex_list = ...\n", 417 | "\n", 418 | "\n", 419 | "# Check yout answer: (should be True)\n", 420 | "print(lc_ex_list == ex_list)" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": null, 426 | "metadata": {}, 427 | "outputs": [], 428 | "source": [ 429 | "# 3b. Loop 2. An example with an if statement (i.e. a 'conditional')\n", 430 | "\n", 431 | "every_second_list = []\n", 432 | "for i in range(1,10): \n", 433 | " if i%2 == 0:\n", 434 | " every_second_list.append(i)\n", 435 | "\n", 436 | "# List comprehension \n", 437 | "\n", 438 | "lc_every_second_list = ... \n", 439 | "\n", 440 | "# Check your answer: (should be True)\n", 441 | "print(lc_every_second_list == every_second_list)" 442 | ] 443 | }, 444 | { 445 | "cell_type": "code", 446 | "execution_count": null, 447 | "metadata": {}, 448 | "outputs": [], 449 | "source": [ 450 | "# 3c. Loop 3. An example with calculation\n", 451 | "\n", 452 | "powers_of_two_list = [] \n", 453 | "for i in range(10):\n", 454 | " powers_of_two_list.append(i**2)\n", 455 | "\n", 456 | "# List comprehension\n", 457 | "\n", 458 | "lc_powers_of_two_list = ...\n", 459 | "\n", 460 | "\n", 461 | "# Check your answer: (Should be True)\n", 462 | "print(lc_powers_of_two_list == powers_of_two_list)" 463 | ] 464 | }, 465 | { 466 | "cell_type": "code", 467 | "execution_count": null, 468 | "metadata": {}, 469 | "outputs": [], 470 | "source": [ 471 | "# 3d. Loop 4. A Dictionary Comprehension\n", 472 | "\n", 473 | "old_list = [\"zeroith\",\"first\",\"what's zeroith?\",\"Am I third or fourth?\"]\n", 474 | "new_dict = {} \n", 475 | "\n", 476 | "for c,i in enumerate(old_list): \n", 477 | " new_dict[c] = i\n", 478 | "\n", 479 | "# Dictionary comprehension\n", 480 | "\n", 481 | "\n", 482 | "dc_new_dict = ...\n", 483 | "\n", 484 | "# Check your answer: (Should be True)\n", 485 | "print(new_dict == dc_new_dict)\n" 486 | ] 487 | }, 488 | { 489 | "cell_type": "markdown", 490 | "metadata": {}, 491 | "source": [ 492 | "## Code refactoring I\n", 493 | "\n", 494 | "In addition to these, just a reminder that all of the exercises in the previous section (for the chapter on collections) that have repetitive code can benefit from loops. Have a look at the answers for these and see if you can refactor them to use loops. The answers with loops are provided below here " 495 | ] 496 | }, 497 | { 498 | "cell_type": "markdown", 499 | "metadata": {}, 500 | "source": [ 501 | "### Concrete poetry with a for loop" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": null, 507 | "metadata": {}, 508 | "outputs": [], 509 | "source": [ 510 | "word = \"acrobats\"\n", 511 | "\n", 512 | "..." 513 | ] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "metadata": {}, 518 | "source": [ 519 | "### The Muppets data cleaning with for loops\n", 520 | "\n", 521 | "Recall this one had several steps. Try doing them all in a single cell to get from `muppet_text` to `muppet_dict`. " 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": null, 527 | "metadata": {}, 528 | "outputs": [], 529 | "source": [ 530 | "muppet_text = '''\n", 531 | "name\tgender\tspecies\tfirst_appearance\n", 532 | "Fozzie\tMale\tBear\t1976\n", 533 | "Kermit\tMale\tFrog\t1955\n", 534 | "Piggy\tFemale\tPig\t1974\n", 535 | "Gonzo\tMale\tUnknown\t1970\n", 536 | "Rowlf\tMale\tDog\t1962\n", 537 | "Beaker\tMale\tMuppet\t1977\n", 538 | "Janice\tFemale\tMuppet\t1975\n", 539 | "Hilda\tFemale\tMuppet\t1976'''" 540 | ] 541 | }, 542 | { 543 | "cell_type": "markdown", 544 | "metadata": {}, 545 | "source": [ 546 | "### Making the profile display more robust\n", 547 | "\n", 548 | "Try then to do the profiling code with a `while` statement for user input. Here you can now use elif statements to do somethings in different cases, such as check for valid input and keep going until the user types `quit` or `x`, etc. " 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": null, 554 | "metadata": {}, 555 | "outputs": [], 556 | "source": [ 557 | "while ...: \n", 558 | " user_input = input(\"Which muppet do you want to profile:(x to quit)\")\n", 559 | " \n", 560 | " ...\n", 561 | " \n", 562 | " break" 563 | ] 564 | }, 565 | { 566 | "cell_type": "markdown", 567 | "metadata": {}, 568 | "source": [ 569 | "# Chapter 5. Functions and classes" 570 | ] 571 | }, 572 | { 573 | "cell_type": "markdown", 574 | "metadata": { 575 | "jupyter": { 576 | "outputs_hidden": false 577 | } 578 | }, 579 | "source": [ 580 | "## Who said programming was better than flipping burgers? \n", 581 | "\n", 582 | "Flipping burgers can be fast-paced and stressful. But poor order tickets can make it harder. Let's build a function to produce clear order tickets. \n", 583 | "\n", 584 | "All hamburgers will have a bun and a patty. \n", 585 | "- The default bun = \"white\"\n", 586 | "- The default patty = \"beef\"\n", 587 | "- Some hamburgers have additional toppings, they will be sent as a list e.g., toppings = [\"cheese\", \"lettuce\"] \n", 588 | "\n", 589 | "HINT: Comment out parts of the code below END ANSWER while you are building your function. Start with the simple default burger and work your way towards to other burgers. " 590 | ] 591 | }, 592 | { 593 | "cell_type": "code", 594 | "execution_count": null, 595 | "metadata": { 596 | "collapsed": false, 597 | "jupyter": { 598 | "outputs_hidden": false 599 | } 600 | }, 601 | "outputs": [], 602 | "source": [ 603 | "# Answer Below here. \n", 604 | "\n", 605 | "def burger_order():\n", 606 | " ...\n", 607 | " return \n", 608 | " \n", 609 | "\n" 610 | ] 611 | }, 612 | { 613 | "cell_type": "code", 614 | "execution_count": null, 615 | "metadata": { 616 | "collapsed": false, 617 | "jupyter": { 618 | "outputs_hidden": false 619 | } 620 | }, 621 | "outputs": [], 622 | "source": [ 623 | "# Testing code. Check the output of this code with the strings provided.\n", 624 | "\n", 625 | "default_burger = burger_order()\n", 626 | "print(default_burger)\n", 627 | "# output should be: \n", 628 | "'''\n", 629 | "***Burger Order***\n", 630 | "\n", 631 | "Bun: white\n", 632 | "Patty: beef\n", 633 | "'''\n", 634 | "\n", 635 | "cheese_burger = burger_order(toppings = [\"chesse\"])\n", 636 | "print(cheese_burger)\n", 637 | "# output should be: \n", 638 | "'''\n", 639 | "***Burger Order***\n", 640 | "\n", 641 | "Bun: white\n", 642 | "Patty: beef\n", 643 | "Extras: \n", 644 | "- cheese\n", 645 | "'''\n", 646 | "\n", 647 | "super_burger = burger_order(bun=\"whole wheat\",toppings =[\"cheese\",\"lettuce\",\"tomato\",\"pickle\"])\n", 648 | "print(super_burger)\n", 649 | "# output should be: \n", 650 | "'''\n", 651 | "***Burger Order***\n", 652 | "\n", 653 | "Bun: whole wheat\n", 654 | "Patty: beef\n", 655 | "Extras: \n", 656 | "- cheese\n", 657 | "- lettuce\n", 658 | "- tomato\n", 659 | "- pickle\n", 660 | "'''\n", 661 | "\n", 662 | "chicken_burger = burger_order(toppings=[\"lettuce\",\"tomato\"],patty = \"chicken\")\n", 663 | "print(chicken_burger)\n", 664 | "# output should be: \n", 665 | "'''\n", 666 | "***Burger Order***\n", 667 | "\n", 668 | "Bun: white\n", 669 | "Patty: chicken\n", 670 | "Extras: \n", 671 | "- lettuce\n", 672 | "- tomato\n", 673 | "'''\n", 674 | "\n", 675 | "health_burger = burger_order(\"gluten-free\",\"veggie\",[\"lettuce\",\"tomato\",\"pickle\"])\n", 676 | "print(health_burger)\n", 677 | "# output should be: \n", 678 | "'''\n", 679 | "***Burger Order***\n", 680 | "\n", 681 | "Bun: gluten-free\n", 682 | "Patty: veggie\n", 683 | "extras:\n", 684 | "- lettuce\n", 685 | "- tomato\n", 686 | "- pickle\n", 687 | "''';" 688 | ] 689 | }, 690 | { 691 | "cell_type": "markdown", 692 | "metadata": { 693 | "jupyter": { 694 | "outputs_hidden": false 695 | } 696 | }, 697 | "source": [ 698 | "### Some extensions to this include:\n", 699 | "- Give each order a number. Try to remember the previous order number.\n", 700 | "- What about using wildcard `kwargs` arguments in order to allow for any topping?\n", 701 | "- What about set burger types? How might these be best expressed? " 702 | ] 703 | } 704 | ], 705 | "metadata": { 706 | "kernelspec": { 707 | "display_name": "Python 3 (ipykernel)", 708 | "language": "python", 709 | "name": "python3" 710 | }, 711 | "language_info": { 712 | "codemirror_mode": { 713 | "name": "ipython", 714 | "version": 3 715 | }, 716 | "file_extension": ".py", 717 | "mimetype": "text/x-python", 718 | "name": "python", 719 | "nbconvert_exporter": "python", 720 | "pygments_lexer": "ipython3", 721 | "version": "3.9.7" 722 | } 723 | }, 724 | "nbformat": 4, 725 | "nbformat_minor": 4 726 | } 727 | -------------------------------------------------------------------------------- /exercises/Ch.A02.ShortAnswers.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Answers to short questions \n", 8 | "\n", 9 | "[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/berniehogan/introducingpython/main?filepath=exercises%2FCh.A02.ShortAnswers.ipynb)\n", 10 | "[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/berniehogan/introducingpython/blob/main/exercises/Ch.A02.ShortAnswers.ipynb)\n", 11 | "\n", 12 | "These are in a different sheet so you can avoid them until you need them." 13 | ] 14 | }, 15 | { 16 | "cell_type": "markdown", 17 | "metadata": {}, 18 | "source": [ 19 | "# Chapter 1. Introducing Python " 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "# Chapter 2. Data Types" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "## Practicing making strings\n", 34 | "\n", 35 | "The first few exercises are just to warm you up to working with strings. " 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "### Debug one" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "print(\"So this is how we start, eh?\")" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "### Debug two" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "print(\"Well, \\\"so far so good\\\", as I like to say\")" 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": {}, 73 | "source": [ 74 | "### Debug three" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [ 83 | "print(\"This should be line 1.\\nThis should be line 2.\")" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "metadata": {}, 89 | "source": [ 90 | "## Making a greeting\n", 91 | "\n", 92 | "With this exercise, you should learn about string insertions. \n", 93 | "We will do them three ways: \n", 94 | "1. Using a + to concatenate the strings\n", 95 | "2. Using `\"{}\".format()`\n", 96 | "3. Using `f\"{! My name is and I'm from . Someday I hope to get to , got any suggestions?`\n", 101 | "\n", 102 | "Remember you can check on https://pyformat.info/ " 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "# Answer\n", 112 | "\n", 113 | "greeting = 'Greetings Earthlings'\n", 114 | "name = 'Lrrr'\n", 115 | "origin = 'Omacron Persei 8'\n", 116 | "destination = 'Earth' \n", 117 | "\n", 118 | "# First using a +, as in print(var+var+var...)\n", 119 | "\n", 120 | "st1 = greeting + \"! My name is \"+ name + \" and I'm from \" + origin + \". Someday I hope to get to \" + destination + \", got any suggestions?\"\n", 121 | "\n", 122 | "# Second using .format, as in print(\"{}\".format(vars))\n", 123 | "\n", 124 | "st2 = \"{}! My name is {} and I'm from {}. Someday I hope to get to {}, got any suggestions?\".format(greeting, name, origin, destination)\n", 125 | "\n", 126 | "# Third using f insertions, as in print(f\"{var}{var}\")\n", 127 | "\n", 128 | "st3 = f\"{greeting}! My name is {name} and I'm from {origin}. Someday I hope to get to {destination}, got any suggestions?\"\n", 129 | "\n", 130 | "print(st1 == st2 == st3)\n", 131 | "print(st1)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "markdown", 136 | "metadata": {}, 137 | "source": [ 138 | "# Chapter 3. Collections\n", 139 | "\n", 140 | "Below are some exercises for the chapter on collections. " 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [ 149 | "a a a a a\n", 150 | " c c c c\n", 151 | "r r r r r\n", 152 | " o o o o\n", 153 | "b b b b b\n", 154 | " a a a a\n", 155 | "t t t t t\n", 156 | " s s s s" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "# Answer using only list lookups\n", 166 | "\n", 167 | "word = \"acrobats\"\n", 168 | "print((word[0] + \" \")*5) \n", 169 | "print(\" \" + (word[1] + \" \")*4) \n", 170 | "print((word[2] + \" \")*5) \n", 171 | "print(\" \" + (word[3] + \" \")*4) \n", 172 | "print((word[4] + \" \")*5) \n", 173 | "print(\" \" + (word[5] + \" \")*4) \n", 174 | "print((word[6] + \" \")*5) \n", 175 | "print(\" \" + (word[7] + \" \")*4) " 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "metadata": {}, 181 | "source": [ 182 | "## A Table of Muppets \n", 183 | "\n", 184 | "The following questions use a table of values with some details from key Muppet characters in the show \"The Muppet Show\". We have the data in one form which is just raw text, which we will clean up so we can ask questions about it. " 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "# Example answer (without for loop)\n", 194 | "muppet_list = muppet_text.strip().split(\"\\n\")\n", 195 | "\n", 196 | "muppet_list[0] = muppet_list[0].split(\"\\t\")\n", 197 | "muppet_list[1] = muppet_list[1].split(\"\\t\")\n", 198 | "muppet_list[2] = muppet_list[2].split(\"\\t\")\n", 199 | "muppet_list[3] = muppet_list[3].split(\"\\t\")\n", 200 | "muppet_list[4] = muppet_list[4].split(\"\\t\")\n", 201 | "muppet_list[5] = muppet_list[5].split(\"\\t\")\n", 202 | "muppet_list[6] = muppet_list[6].split(\"\\t\")\n", 203 | "muppet_list[7] = muppet_list[7].split(\"\\t\")\n", 204 | "muppet_list[8] = muppet_list[8].split(\"\\t\")\n", 205 | "print(muppet_list)" 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "metadata": {}, 211 | "source": [ 212 | "### Separating the header from the rest. \n", 213 | "\n", 214 | "Take muppet_list and then slice it so that you have two lists:\n", 215 | "`muppet_header` is only of length one, it's the header. `muppet_data` is the other list and contains the remianing elements. Check that the length of `muppet_data` is `8`. " 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": null, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "# 2.3 Separating the header from the rest. \n", 225 | "\n", 226 | "# Answer \n", 227 | "muppet_header = muppet_list[0] \n", 228 | "muppet_data = muppet_list[1:]\n", 229 | "\n", 230 | "print(f\"It is {len(muppet_data) == 8} that the Muppet Data has 8 rows\")\n" 231 | ] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "metadata": {}, 236 | "source": [ 237 | "### Transforming the `muppet_data` into a `muppet_dict`" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "metadata": {}, 244 | "outputs": [], 245 | "source": [ 246 | "# Answer\n", 247 | "\n", 248 | "m_dict = {} \n", 249 | "\n", 250 | "m_dict[muppet_data[0][0]] = muppet_data[0][1:]\n", 251 | "m_dict[muppet_data[1][0]] = muppet_data[1][1:]\n", 252 | "m_dict[muppet_data[2][0]] = muppet_data[2][1:]\n", 253 | "m_dict[muppet_data[3][0]] = muppet_data[3][1:]\n", 254 | "m_dict[muppet_data[4][0]] = muppet_data[4][1:]\n", 255 | "m_dict[muppet_data[5][0]] = muppet_data[5][1:]\n", 256 | "m_dict[muppet_data[6][0]] = muppet_data[6][1:]\n", 257 | "m_dict[muppet_data[7][0]] = muppet_data[7][1:]\n", 258 | "\n", 259 | "print(f\"It is {len(m_dict.keys())==8} that the muppet_dict has 8 keys.\")" 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "metadata": {}, 265 | "source": [ 266 | "### Query the muppet data (Tougher bonus challenge)\n" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "metadata": {}, 273 | "outputs": [], 274 | "source": [ 275 | "# Example answer \n", 276 | "\n", 277 | "user_input = input(\"Which muppet do you want to profile:\")\n", 278 | "\n", 279 | "gen = m_dict[user_input][0]\n", 280 | "sp = m_dict[user_input][1]\n", 281 | "fa = m_dict[user_input][2]\n", 282 | "print(f\"Character:\\n\\t{user_input}\\nProfle:\\n\\tGender: {gen}\\n\\tSpecies: {sp}\\n\\tFirst Appearance: {fa}\")" 283 | ] 284 | }, 285 | { 286 | "cell_type": "markdown", 287 | "metadata": {}, 288 | "source": [ 289 | "# Flow control" 290 | ] 291 | }, 292 | { 293 | "cell_type": "markdown", 294 | "metadata": {}, 295 | "source": [ 296 | "## Fozzie Bear! " 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": null, 302 | "metadata": {}, 303 | "outputs": [], 304 | "source": [ 305 | "# Answer below here: \n", 306 | "for i in range(1, 31):\n", 307 | " if not i % 3:\n", 308 | " if not i % 5 :\n", 309 | " print(f'{i}. Fozzie Bear')\n", 310 | " else:\n", 311 | " print(f'{i}. Fozzie')\n", 312 | " elif i % 5 == 0:\n", 313 | " print(f'{i}. Bear')" 314 | ] 315 | }, 316 | { 317 | "cell_type": "markdown", 318 | "metadata": {}, 319 | "source": [ 320 | "## List (and dictionary) comprehension practice" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": null, 326 | "metadata": {}, 327 | "outputs": [], 328 | "source": [ 329 | "# 3a. Loop 1. The simplest example.\n", 330 | "\n", 331 | "ex_list = []\n", 332 | "for i in range(1,10): \n", 333 | " ex_list.append(i)\n", 334 | " \n", 335 | "# List comprehension\n", 336 | "\n", 337 | "lc_ex_list = [i for i in range(1,10)]\n", 338 | "\n", 339 | "\n", 340 | "# Check yout answer: (should be True)\n", 341 | "print(lc_ex_list == ex_list)" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": {}, 348 | "outputs": [], 349 | "source": [ 350 | "# 3b. Loop 2. An example with an if statement (i.e. a 'conditional')\n", 351 | "\n", 352 | "every_second_list = []\n", 353 | "for i in range(1,10): \n", 354 | " if i%2 == 0:\n", 355 | " every_second_list.append(i)\n", 356 | "\n", 357 | "# List comprehension \n", 358 | "lc_every_second_list = [i for i in range(1,10) if i%2 == 0]\n", 359 | "\n", 360 | "# Check your answer: (should be True)\n", 361 | "print(lc_every_second_list == every_second_list)" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "metadata": {}, 368 | "outputs": [], 369 | "source": [ 370 | "# 3c. Loop 3. An example with calculation\n", 371 | "\n", 372 | "powers_of_two_list = [] \n", 373 | "for i in range(10):\n", 374 | " powers_of_two_list.append(i**2)\n", 375 | "\n", 376 | "# List comprehension\n", 377 | "\n", 378 | "lc_powers_of_two_list = [i**2 for i in range(10)]\n", 379 | "\n", 380 | "\n", 381 | "# Check your answer: (Should be True)\n", 382 | "print(lc_powers_of_two_list == powers_of_two_list)" 383 | ] 384 | }, 385 | { 386 | "cell_type": "code", 387 | "execution_count": null, 388 | "metadata": {}, 389 | "outputs": [], 390 | "source": [ 391 | "# 3d. Loop 4. A Dictionary Comprehension\n", 392 | "\n", 393 | "old_list = [\"zeroith\",\"first\",\"what's zeroith?\",\"Am I third or fourth?\"]\n", 394 | "new_dict = {} \n", 395 | "\n", 396 | "for c,i in enumerate(old_list): \n", 397 | " new_dict[c] = i\n", 398 | "\n", 399 | "# Dictionary comprehension\n", 400 | "\n", 401 | "\n", 402 | "dc_new_dict = {c:i for c,i in enumerate(old_list)}\n", 403 | "\n", 404 | "# Check your answer: (Should be True)\n", 405 | "print(new_dict == dc_new_dict)\n" 406 | ] 407 | }, 408 | { 409 | "cell_type": "markdown", 410 | "metadata": {}, 411 | "source": [ 412 | "## Code refactoring I\n", 413 | "\n", 414 | "In addition to these, just a reminder that all of the exercises in the previous section (for the chapter on collections) that have repetitive code can benefit from loops. Have a look at the answers for these and see if you can refactor them to use loops. The answers with loops are provided below here " 415 | ] 416 | }, 417 | { 418 | "cell_type": "markdown", 419 | "metadata": {}, 420 | "source": [ 421 | "### Concrete poetry with a for loop" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": null, 427 | "metadata": {}, 428 | "outputs": [], 429 | "source": [ 430 | "# Answer using for loops \n", 431 | "\n", 432 | "for c,w in enumerate(word):\n", 433 | " if c%2==1: \n", 434 | " print(\" \" + (w + \" \")*4)\n", 435 | " else:\n", 436 | " print((w + \" \")*5) \n" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": {}, 443 | "outputs": [], 444 | "source": [ 445 | "# Here's the densest I can make it. \n", 446 | "for c,i in enumerate(\"acrobats\"):\n", 447 | " print(f\"{i} \"*5 if c%2 == 0 else \" \" + f\"{i} \"*4)" 448 | ] 449 | }, 450 | { 451 | "cell_type": "markdown", 452 | "metadata": {}, 453 | "source": [ 454 | "### The Muppets data cleaning with for loops\n", 455 | "\n", 456 | "Recall this one had several steps. Try doing them all in a single cell to get from `muppet_text` to `muppet_dict`. " 457 | ] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": null, 462 | "metadata": {}, 463 | "outputs": [], 464 | "source": [ 465 | "muppet_text = '''\n", 466 | "name\tgender\tspecies\tfirst_appearance\n", 467 | "Fozzie\tMale\tBear\t1976\n", 468 | "Kermit\tMale\tFrog\t1955\n", 469 | "Piggy\tFemale\tPig\t1974\n", 470 | "Gonzo\tMale\tUnknown\t1970\n", 471 | "Rowlf\tMale\tDog\t1962\n", 472 | "Beaker\tMale\tMuppet\t1977\n", 473 | "Janice\tFemale\tMuppet\t1975\n", 474 | "Hilda\tFemale\tMuppet\t1976'''" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": {}, 481 | "outputs": [], 482 | "source": [ 483 | "# Example answer with some for loops \n", 484 | "\n", 485 | "m_dict = {} \n", 486 | "header_row = True\n", 487 | "\n", 488 | "for row in muppet_text.strip().split(\"\\n\"):\n", 489 | " if header_row: \n", 490 | " muppet_header = row.split(\"\\t\")\n", 491 | " header_row = False\n", 492 | " continue\n", 493 | " row = row.split(\"\\t\")\n", 494 | " m_dict[row[0]] = row[1:]\n", 495 | "\n", 496 | "m_dict" 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": null, 502 | "metadata": {}, 503 | "outputs": [], 504 | "source": [ 505 | "# Example answer (with for dictionary comprehension)\n", 506 | "# Notice with this one you have to do the header row separately. \n", 507 | "# I just excluded that from here. \n", 508 | "\n", 509 | "m_dict = {i.split(\"\\t\")[0]:i.split(\"\\t\")[1:] \n", 510 | " for i in muppet_text.strip().split(\"\\n\")[1:]}\n", 511 | "\n", 512 | "print(m_dict)" 513 | ] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "metadata": {}, 518 | "source": [ 519 | "### Making the profile display more robust\n", 520 | "\n", 521 | "Try then to do the profiling code with a `while` statement for user input. Here you can now use elif statements to do somethings in different cases, such as check for valid input and keep going until the user types `quit` or `x`, etc. " 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": null, 527 | "metadata": {}, 528 | "outputs": [], 529 | "source": [ 530 | "while True: \n", 531 | " user_input = input(\"Which muppet do you want to profile:(x to quit)\")\n", 532 | " \n", 533 | " if user_input.lower() == \"l\":\n", 534 | " print (\"\\n\".join(m_dict.keys()))\n", 535 | " elif user_input.lower() == \"x\":\n", 536 | " break\n", 537 | " elif user_input in m_dict.keys(): \n", 538 | " gen = m_dict[user_input][0]\n", 539 | " sp = m_dict[user_input][1]\n", 540 | " fa = m_dict[user_input][2]\n", 541 | " print(f\"Character:\\n\\t{user_input}\\nProfle:\\n\\tGender: {gen}\\n\\tSpecies {sp}\\n\\tFirst Appearance: {fa}\")\n", 542 | " else: \n", 543 | " print(\"That was not a valid name. Type L to see names of muppets.\")" 544 | ] 545 | }, 546 | { 547 | "cell_type": "markdown", 548 | "metadata": {}, 549 | "source": [ 550 | "# Chapter 5. Functions and classes" 551 | ] 552 | }, 553 | { 554 | "cell_type": "markdown", 555 | "metadata": { 556 | "jupyter": { 557 | "outputs_hidden": false 558 | } 559 | }, 560 | "source": [ 561 | "## Who said programming was better than flipping burgers? " 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": null, 567 | "metadata": { 568 | "collapsed": false, 569 | "jupyter": { 570 | "outputs_hidden": false 571 | } 572 | }, 573 | "outputs": [], 574 | "source": [ 575 | "# Answer Below here. \n", 576 | "\n", 577 | "def burger_order(bun = \"white\", patty = \"beef\", toppings = []):\n", 578 | " receipt = \"\\n***Burger Order***\\n\\n\\n\"\n", 579 | " \n", 580 | " receipt += \"Bun: %s\\n\" % bun\n", 581 | " receipt += \"Patty: %s\\n\" % patty\n", 582 | " if len(toppings) > 0: \n", 583 | " receipt += \"Extras:\\n\"\n", 584 | " for i in toppings: \n", 585 | " receipt += \"- %s\\n\" % i\n", 586 | " \n", 587 | " return receipt\n", 588 | " \n", 589 | "\n", 590 | "#********** END ANSWER ************" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": null, 596 | "metadata": { 597 | "collapsed": false, 598 | "jupyter": { 599 | "outputs_hidden": false 600 | } 601 | }, 602 | "outputs": [], 603 | "source": [ 604 | "# Testing code. Check the output of this code with the strings provided.\n", 605 | "\n", 606 | "default_burger = burger_order()\n", 607 | "print(default_burger)\n", 608 | "# output should be: \n", 609 | "'''\n", 610 | "***Burger Order***\n", 611 | "\n", 612 | "Bun: white\n", 613 | "Patty: beef\n", 614 | "'''\n", 615 | "\n", 616 | "cheese_burger = burger_order(toppings = [\"chesse\"])\n", 617 | "print(cheese_burger)\n", 618 | "# output should be: \n", 619 | "'''\n", 620 | "***Burger Order***\n", 621 | "\n", 622 | "Bun: white\n", 623 | "Patty: beef\n", 624 | "Extras: \n", 625 | "- cheese\n", 626 | "'''\n", 627 | "\n", 628 | "super_burger = burger_order(bun=\"whole wheat\",toppings =[\"cheese\",\"lettuce\",\"tomato\",\"pickle\"])\n", 629 | "print(super_burger)\n", 630 | "# output should be: \n", 631 | "'''\n", 632 | "***Burger Order***\n", 633 | "\n", 634 | "Bun: whole wheat\n", 635 | "Patty: beef\n", 636 | "Extras: \n", 637 | "- cheese\n", 638 | "- lettuce\n", 639 | "- tomato\n", 640 | "- pickle\n", 641 | "'''\n", 642 | "\n", 643 | "chicken_burger = burger_order(toppings=[\"lettuce\",\"tomato\"],patty = \"chicken\")\n", 644 | "print(chicken_burger)\n", 645 | "# output should be: \n", 646 | "'''\n", 647 | "***Burger Order***\n", 648 | "\n", 649 | "Bun: white\n", 650 | "Patty: chicken\n", 651 | "Extras: \n", 652 | "- lettuce\n", 653 | "- tomato\n", 654 | "'''\n", 655 | "\n", 656 | "health_burger = burger_order(\"gluten-free\",\"veggie\",[\"lettuce\",\"tomato\",\"pickle\"])\n", 657 | "print(health_burger)\n", 658 | "# output should be: \n", 659 | "'''\n", 660 | "***Burger Order***\n", 661 | "\n", 662 | "Bun: gluten-free\n", 663 | "Patty: veggie\n", 664 | "extras:\n", 665 | "- lettuce\n", 666 | "- tomato\n", 667 | "- pickle\n", 668 | "''';" 669 | ] 670 | } 671 | ], 672 | "metadata": { 673 | "kernelspec": { 674 | "display_name": "Python 3 (ipykernel)", 675 | "language": "python", 676 | "name": "python3" 677 | }, 678 | "language_info": { 679 | "codemirror_mode": { 680 | "name": "ipython", 681 | "version": 3 682 | }, 683 | "file_extension": ".py", 684 | "mimetype": "text/x-python", 685 | "name": "python", 686 | "nbconvert_exporter": "python", 687 | "pygments_lexer": "ipython3", 688 | "version": "3.9.7" 689 | } 690 | }, 691 | "nbformat": 4, 692 | "nbformat_minor": 4 693 | } 694 | -------------------------------------------------------------------------------- /exercises/Ch.A03.LongerIdeas.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Longer Question Ideas \n", 8 | "\n", 9 | "[![Binder](https://mybinder.org/badge.svg)](https://mybinder.org/v2/gh/berniehogan/introducingpython/main?filepath=exercises%2FCh.A03.LongerIdeas.ipynb)\n", 10 | "[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/berniehogan/introducingpython/blob/main/exercises/Ch.A03.LongerIdeas.ipynb)" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "These are some of the longer creative questions that I have used in classes in the past. These normally involve combining multiple ideas from the book in creative ways as well as perhaps drawing upon some knowledge beyond the book. I don't have specific answers to these questions available, they are for you to explore on your own. " 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "# Mad Libs \n", 25 | "\n", 26 | "The game Mad Libs involves first coming up with random words based on parts-of-speech tagging (verbs, nouns, pronouns, adverbs, etc...) and then putting them into a pre-given sentence. Such as: \n", 27 | "\n", 28 | "~~~\n", 29 | "{Proper noun} was so surprised when they saw the {noun} {verb continuous} in town square, \n", 30 | "they immediately packed their bags full of {plural noun} and left for {Geographic location}. \n", 31 | "~~~\n", 32 | "\n", 33 | "Your goal is to make a mad libs game. You should use loops to ask for user input five times, each representing a different class of word. It need not be formal grammar; it could be \"restaurant\", \"Movie\", etc. but it certainly is more fun when you expand beyond nouns. Then print the sentence for the user. Try to make the order that you ask for the five words is _not_ the same as the order in which they are presented. " 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "## Comparing Pseudocode to the real thing\n", 41 | "\n", 42 | "For this one, here is a pseudocode version of my answer to get you started: \n", 43 | "\n", 44 | "~~~ \n", 45 | "get a dictionary for the \"libs\". \n", 46 | "The key is the type of word and the value will come from the user.\n", 47 | "We will set the value as none for now. \n", 48 | "Since dictionary keys need to be unique and we might want two nouns or two places:\n", 49 | "label them noun1 and noun2\n", 50 | "\n", 51 | "Figure out a way to iterate through a shuffled dictionary. \n", 52 | "Since we cannot shuffle a dictionary directly:\n", 53 | " First get the keys from the dictionary, \n", 54 | " Shuffle the keys, and then iterate through those keys. \n", 55 | "\n", 56 | "On each iteration, assign a value to the dictionary by asking for user input.\n", 57 | "The user input should use the key in the prompt like \n", 58 | " \"Please suggest a noun for the story\"\n", 59 | "\n", 60 | "Then use f-insertions to paste the answers in the story. \n", 61 | "~~~" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "# Example answer \n", 71 | "\n", 72 | "import random \n", 73 | "\n", 74 | "answer_dict = {\"plural noun1\": None,\n", 75 | " \"verb continuous1\": None,\n", 76 | " \"noun1\": None,\n", 77 | " \"place1\": None,\n", 78 | " \"place2\": None,\n", 79 | " \"proper noun1\": None\n", 80 | " }\n", 81 | "\n", 82 | "libs = list(answer_dict.keys())\n", 83 | "random.shuffle(libs)\n", 84 | "\n", 85 | "for i in libs: \n", 86 | " answer_dict[i] = input(f\"Please suggest a {i[:-1]} for the story:\")\n", 87 | "\n", 88 | "ad = answer_dict\n", 89 | "\n", 90 | "story = f'{ad[\"proper noun1\"]} was so surprised when they saw the {ad[\"noun1\"]} {ad[\"verb continuous1\"]} in {ad[\"place1\"]}, they immediately packed their bags full of {ad[\"plural noun1\"]} and left for {ad[\"place2\"]}.'\n", 91 | "\n", 92 | "print(story)" 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "## Making it more robust or more general \n", 100 | "\n", 101 | "Ok so that was pretty simple. And you didn't have to do much other than run my code. But what about the following extensions:\n", 102 | "- Creating a general way to insert some text and then create the madlib. Here we created a dictionary and then linked that to the string. What about a way to do it so the dictionary is not hard coded somehow? \n", 103 | "- Try feeding it text from a text file that you have marked up with the madlibs in a form like: `Hello ##Proper noun##, did I see you at ##Place name##.` And then auto-generating the madlib from this. \n", 104 | "- Learning about parts-of-speech taggers in programs like `nltk` and spacy. Then feed in any paragraph of text and automatically remove some of the words and generate a madlib that way. " 105 | ] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "metadata": {}, 110 | "source": [ 111 | "# Creating a word waterfall" 112 | ] 113 | }, 114 | { 115 | "cell_type": "markdown", 116 | "metadata": {}, 117 | "source": [ 118 | "Just past the title page of this book is a word waterfall (my own idea) with \"Introducing Python\". In this idea, each iteration a letter is replaced with a space.\n", 119 | "\n", 120 | "Below I have written two different ways to create a word waterfall algorithmically. \n", 121 | "\n", 122 | "Read them both, edit and play with them as you like. \n", 123 | "\n", 124 | "Then below write the following: \n", 125 | "1. A pseudocode explanation of algorithm 1. \n", 126 | "2. A pseudocode explanation of algorothm 2. \n", 127 | "3. An evaluation of algorithms 1 and 2: What is common about them and what is different? " 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 1, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "import random \n", 137 | "\n", 138 | "WORD = \"waterfall\"" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": 2, 144 | "metadata": {}, 145 | "outputs": [ 146 | { 147 | "name": "stdout", 148 | "output_type": "stream", 149 | "text": [ 150 | "waterfall\n", 151 | " aterfall\n", 152 | " aterfal \n", 153 | " a erfal \n", 154 | " a er al \n", 155 | " a er l \n", 156 | " er l \n", 157 | " er \n", 158 | " r \n" 159 | ] 160 | } 161 | ], 162 | "source": [ 163 | "word = list(WORD)\n", 164 | "\n", 165 | "wordmap = list(range(len(word)))\n", 166 | "random.shuffle(wordmap)\n", 167 | "for i in wordmap: \n", 168 | " print(\"\".join(word))\n", 169 | " word[i] = \" \"\n" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 3, 175 | "metadata": {}, 176 | "outputs": [ 177 | { 178 | "name": "stdout", 179 | "output_type": "stream", 180 | "text": [ 181 | "waterfall\n", 182 | "waterfal \n", 183 | "wat rfal \n", 184 | "wat rf l \n", 185 | "wat rf \n", 186 | " at rf \n", 187 | " t rf \n", 188 | " t r \n", 189 | " r \n", 190 | "\n" 191 | ] 192 | } 193 | ], 194 | "source": [ 195 | "word = list(WORD)\n", 196 | "\n", 197 | "while word != (len(word) * [\" \"]):\n", 198 | " to_del = random.randint(0,len(word)-1)\n", 199 | " if word[to_del].isalpha():\n", 200 | " print(\"\".join(word))\n", 201 | " word[to_del] = \" \" \n", 202 | "\n", 203 | "print()" 204 | ] 205 | }, 206 | { 207 | "cell_type": "markdown", 208 | "metadata": {}, 209 | "source": [ 210 | "## Pseudocode, similarities, and differences\n", 211 | "\n", 212 | "For the `for` loop waterfall: \n", 213 | "\n", 214 | "~~~\n", 215 | "insert pseduocode here\n", 216 | "~~~\n", 217 | "\n", 218 | "For the `while` loop waterfall\n", 219 | "\n", 220 | "~~~\n", 221 | "insert pseudocode here \n", 222 | "~~~\n", 223 | "\n", 224 | "Discuss the differences and advantages below:" 225 | ] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "metadata": {}, 230 | "source": [ 231 | "## Create a `waterfall.py` script\n", 232 | "\n", 233 | "Create a script in python called `waterfall.py` which can be run from the terminal. \n", 234 | "\n", 235 | "The script will take an argument and then print the argument as a waterfall:\n", 236 | "\n", 237 | "~~~ bash\n", 238 | "% python waterfall.py avalanche \n", 239 | "~~~\n", 240 | "\n", 241 | "Should print something like: \n", 242 | "\n", 243 | "~~~ \n", 244 | "avalanche\n", 245 | "avala che\n", 246 | "a ala che\n", 247 | "a la che\n", 248 | "a l che\n", 249 | " l che\n", 250 | " che\n", 251 | " ch \n", 252 | " h \n", 253 | "~~~\n" 254 | ] 255 | }, 256 | { 257 | "cell_type": "markdown", 258 | "metadata": {}, 259 | "source": [ 260 | "## Create your own waterfalls in a script.\n", 261 | "\n", 262 | "Extend the script above with 'interactive mode'. This means that if your argument is `-i` instead of a word then it will ask a series of questions:\n", 263 | "\n", 264 | "1. `What word or phrase would you like to waterfall?`:\n", 265 | " - This will then print the waterfall from `input()`\n", 266 | "2. `Would you like to save the waterfall as a file? (y/n)`:\n", 267 | " - If the user enters `y` this will then save `.txt` as a file.\n", 268 | " - This means you have to save the waterfall as a string just in case you need it here to be written to file.\n", 269 | " - `print(f\"{} has been written\")`" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "metadata": { 275 | "id": "okdz31rKKZ9x" 276 | }, 277 | "source": [ 278 | "# Your very own restaurant on YummyNet\n", 279 | "\n", 280 | "After the fall of Deliveroo, Uber Eats, and JustEats for questionable labour standards in the near future, YummyNet emerged as a more considerate albeit more expensive platform for restaurants. Having had limited success with your chatbots for pets app, you've decided to switch careers and open a restaurant. \n", 281 | "\n", 282 | "For this exercise, you have to make a standalone Python program (a `*.py` script) that will simulate the store front for this resutaurant. But times are tough and goods are scarce, so this is going to be a bit of an unpridctable menu. \n", 283 | "\n", 284 | "We expect the following steps: \n", 285 | "\n", 286 | "1. Create a welcome message and ask for the user's post code. \n", 287 | "2. List the items on the menu for delivery and their prices. \n", 288 | "3. Have the user select an order for delivery from the items on the menu.\n", 289 | " - There should be at least five mains and three sides. The mains should be made of multiple ingredients. \n", 290 | " - when the program starts, randomly select one ingredient to be 'sold out due to those panic buyers' (or a similarly plausible reason for an ingredient to be sold out). If the user selects an item with that ingredient mention that it is sold out and offer an alternative. \n", 291 | "4. When finished, print the order, an order number, the total price, and the delivery time. \n", 292 | "5. Ask them to confirm by giving their mobile phone number. \n", 293 | "\n", 294 | "Note: \n", 295 | "\n", 296 | "- Consider what would be the maximum stock available. We will test by making a ridiculously large order. \n", 297 | "- Items contain multiple (often overlapping) ingredients. So if cheese is sold out, then cheeseburgers and lasagna would not be available, but meatballs would still be available). \n", 298 | "- Ensure that you can recommend at least one meal to the customer. \n", 299 | "- You can make a larger menu but remember to test it for legibility and usability. \n", 300 | "\n", 301 | "**Challenge** Store the order in a file before the program exits and give the user an 'order number'. Then if they run the program again and present the correct order number (and the correct telephone number) it will print a duplicate receipt. \n", 302 | "\n", 303 | "Some things you'll want to consider about your data structure: \n", 304 | "\n", 305 | "- How are you storing the order? As a list? As an object of the Order class? \n", 306 | "- What will you do with bad input and how will you make the text input as easy as possible? \n", 307 | "- How will you manage the inventory so that you will know which goods include which ingredients? \n", 308 | "- What if you had to expand the list of menu items. How hard would that be with your program? \n", 309 | "- Does the program end gracefully? \n", 310 | "- Will your printing of output be attractive and easy to read?" 311 | ] 312 | } 313 | ], 314 | "metadata": { 315 | "kernelspec": { 316 | "display_name": "Python 3 (ipykernel)", 317 | "language": "python", 318 | "name": "python3" 319 | }, 320 | "language_info": { 321 | "codemirror_mode": { 322 | "name": "ipython", 323 | "version": 3 324 | }, 325 | "file_extension": ".py", 326 | "mimetype": "text/x-python", 327 | "name": "python", 328 | "nbconvert_exporter": "python", 329 | "pygments_lexer": "ipython3", 330 | "version": "3.9.7" 331 | } 332 | }, 333 | "nbformat": 4, 334 | "nbformat_minor": 4 335 | } 336 | -------------------------------------------------------------------------------- /exercises/MASTER_Ch.A.ShortQuestions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "Below are some short exercises to check your knowledge of the topics introduced in each of the chapters. Each section corresponds to one of the prior chapters in the book. After these are two more appendices. Appendix 2 is just this appendix but with some example code for answers for the questions below. Finally, in Appendix 3 is is a series of longer creative exercises that you might want to attempt with skills from this book. They are marked by which skills you would reasonably need to try your hand at the exercise.\n", 8 | "\n", 9 | "In many cases I have provided some starter code and you should finish that code. You'll see where you should finish with an `...` or a similar sort of marker." 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# Chapter 1. Introducing Python " 17 | ] 18 | }, 19 | { 20 | "cell_type": "markdown", 21 | "metadata": {}, 22 | "source": [ 23 | "# Chapter 2. Data Types" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": {}, 29 | "source": [ 30 | "## Practicing making strings\n", 31 | "\n", 32 | "The first few exercises are just to warm you up to working with strings. " 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "metadata": {}, 38 | "source": [ 39 | "### Debug one" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "print \"So this is how we start, eh?\"" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "# Answer\n", 58 | "\n", 59 | "print(\"So this is how we start, eh?\")\n" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "### Debug two" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "print(\"Well, \"so far so good\", as I like to say\")" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "print(\"Well, \\\"so far so good\\\", as I like to say\")" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "### Debug three" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": 3, 97 | "metadata": {}, 98 | "outputs": [ 99 | { 100 | "ename": "SyntaxError", 101 | "evalue": "unexpected character after line continuation character (, line 1)", 102 | "output_type": "error", 103 | "traceback": [ 104 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m print(\"This should be line 1.\"\\n\"This should be line 2.\")\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unexpected character after line continuation character\n" 105 | ] 106 | } 107 | ], 108 | "source": [ 109 | "print(\"This should be line 1.\"\\n\"This should be line 2.\")" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": {}, 115 | "source": [ 116 | "## Making a greeting\n", 117 | "\n", 118 | "With this exercise, you should learn about string insertions. \n", 119 | "We will do them three ways: \n", 120 | "1. Using a + to concatenate the strings\n", 121 | "2. Using `\"{}\".format()`\n", 122 | "3. Using `f\"{! My name is and I'm from . Someday I hope to get to , got any suggestions?`\n", 127 | "\n", 128 | "Remember you can check on https://pyformat.info/ " 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "greeting = ''\n", 138 | "name = ''\n", 139 | "origin = ''\n", 140 | "destination = '' \n", 141 | "\n", 142 | "# First using a +, as in print(var+var+var...)\n", 143 | "st1 = ...\n", 144 | "\n", 145 | "# Second using .format, as in print(\"{}\".format(vars))\n", 146 | "\n", 147 | "st2 = ...\n", 148 | "# Third using f insertions, as in print(f\"{var}{var}\")\n", 149 | "\n", 150 | "st3 = ...\n", 151 | "\n", 152 | "print(st1 == st2 == st3)\n", 153 | "print(st1)\n" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "# Answer\n", 163 | "\n", 164 | "greeting = 'Greetings Earthlings'\n", 165 | "name = 'Lrrr'\n", 166 | "origin = 'Omacron Persei 8'\n", 167 | "destination = 'Earth' \n", 168 | "\n", 169 | "# First using a +, as in print(var+var+var...)\n", 170 | "\n", 171 | "st1 = greeting + \"! My name is \"+ name + \" and I'm from \" + origin + \". Someday I hope to get to \" + destination + \", got any suggestions?\"\n", 172 | "\n", 173 | "# Second using .format, as in print(\"{}\".format(vars))\n", 174 | "\n", 175 | "st2 = \"{}! My name is {} and I'm from {}. Someday I hope to get to {}, got any suggestions?\".format(greeting, name, origin, destination)\n", 176 | "\n", 177 | "# Third using f insertions, as in print(f\"{var}{var}\")\n", 178 | "\n", 179 | "st3 = f\"{greeting}! My name is {name} and I'm from {origin}. Someday I hope to get to {destination}, got any suggestions?\"\n", 180 | "\n", 181 | "print(st1 == st2 == st3)\n", 182 | "print(st1)" 183 | ] 184 | }, 185 | { 186 | "cell_type": "markdown", 187 | "metadata": {}, 188 | "source": [ 189 | "# Chapter 3. Collections\n", 190 | "\n", 191 | "Below are some exercises for the chapter on collections. " 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "## Building an algorithm to reproduce concrete poetry\n", 199 | "\n", 200 | "There's not much you can do in Python exclusively by printing strings. However, I thought this would be a nice opportunity to produce some concrete poetry. Concrete poetry means the visual arrangement of the words has meaning as do the words. Ian Hamilton Finlay is a Scottish concrete poet. Below I have pasted a version of his poem \"acrobats\" as excerpted from Cockburn K. and Finlay, A (2001) _The Order of Things_. Edinburgh, UK: Pocketbooks." 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "a a a a a\n", 210 | " c c c c\n", 211 | "r r r r r\n", 212 | " o o o o\n", 213 | "b b b b b\n", 214 | " a a a a\n", 215 | "t t t t t\n", 216 | " s s s s" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "Using only a variable `word = \"acrobats\"`, string insertions, spaces, and lists, try to print a reproduction of the poem. \n", 224 | "\n", 225 | "In this version, the answer below should be done _without_ `for` loops or `if` statements, which means it will likely have some repetition. Your goal is to minimise that repetition even if you can't eliminate it. " 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": null, 231 | "metadata": {}, 232 | "outputs": [], 233 | "source": [ 234 | "# Complete the answer: (I wrote some code to get you started)\n", 235 | "\n", 236 | "word = \"acrobats\"\n", 237 | "print((word[0] + \" \")*5) \n", 238 | "...\n", 239 | "...;" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "# Answer using only list lookups\n", 249 | "\n", 250 | "word = \"acrobats\"\n", 251 | "print((word[0] + \" \")*5) \n", 252 | "print(\" \" + (word[1] + \" \")*4) \n", 253 | "print((word[2] + \" \")*5) \n", 254 | "print(\" \" + (word[3] + \" \")*4) \n", 255 | "print((word[4] + \" \")*5) \n", 256 | "print(\" \" + (word[5] + \" \")*4) \n", 257 | "print((word[6] + \" \")*5) \n", 258 | "print(\" \" + (word[7] + \" \")*4) " 259 | ] 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "metadata": {}, 264 | "source": [ 265 | "## A Table of Muppets \n", 266 | "\n", 267 | "The following questions use a table of values with some details from key Muppet characters in the show \"The Muppet Show\". We have the data in one form which is just raw text, which we will clean up so we can ask questions about it. " 268 | ] 269 | }, 270 | { 271 | "cell_type": "markdown", 272 | "metadata": {}, 273 | "source": [ 274 | "### Splitting strings into lists\n", 275 | "\n", 276 | "This data is presented as a string. It is structured as what we call tab-separated values (`.tsv`). Let's change it so that it is a list of lists. Below you can do this without a `for` loop as that is featured in the subsequent chapter. It will be important to think of how you deploy the `.split()` method since you will need to split both by line and then within line. \n", 277 | "\n", 278 | "Doing this without a for loop might involve using nine repetitions of basically the same code. So I will show that and I will also include a `for` loop version. \n", 279 | "\n", 280 | "Your final data structure should have nine elements. Each one will be a row with data. If you have 11 check that you have not included lines for the empty top and bottom lines of the text. " 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": null, 286 | "metadata": {}, 287 | "outputs": [], 288 | "source": [ 289 | " \n", 290 | "muppet_text = '''\n", 291 | "name\tgender\tspecies\tfirst_appearance\n", 292 | "Fozzie\tMale\tBear\t1976\n", 293 | "Kermit\tMale\tFrog\t1955\n", 294 | "Piggy\tFemale\tPig\t1974\n", 295 | "Gonzo\tMale\tUnknown\t1970\n", 296 | "Rowlf\tMale\tDog\t1962\n", 297 | "Beaker\tMale\tMuppet\t1977\n", 298 | "Janice\tFemale\tMuppet\t1975\n", 299 | "Hilda\tFemale\tMuppet\t1976\n", 300 | "'''\n", 301 | "\n", 302 | "# Complete this answer: \n", 303 | "\n", 304 | "muppet_list = [...]*9 #Replace [...]*9 with your answer\n", 305 | "\n", 306 | "muppet_list[0] = ... \n", 307 | "muppet_list[1] = ...\n", 308 | "\n", 309 | "\n", 310 | "print(muppet_list)" 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": null, 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [ 319 | "# Example answer (without for loop)\n", 320 | "muppet_list = muppet_text.strip().split(\"\\n\")\n", 321 | "\n", 322 | "muppet_list[0] = muppet_list[0].split(\"\\t\")\n", 323 | "muppet_list[1] = muppet_list[1].split(\"\\t\")\n", 324 | "muppet_list[2] = muppet_list[2].split(\"\\t\")\n", 325 | "muppet_list[3] = muppet_list[3].split(\"\\t\")\n", 326 | "muppet_list[4] = muppet_list[4].split(\"\\t\")\n", 327 | "muppet_list[5] = muppet_list[5].split(\"\\t\")\n", 328 | "muppet_list[6] = muppet_list[6].split(\"\\t\")\n", 329 | "muppet_list[7] = muppet_list[7].split(\"\\t\")\n", 330 | "muppet_list[8] = muppet_list[8].split(\"\\t\")\n", 331 | "print(muppet_list)" 332 | ] 333 | }, 334 | { 335 | "cell_type": "markdown", 336 | "metadata": {}, 337 | "source": [ 338 | "### Separating the header from the rest. \n", 339 | "\n", 340 | "Take muppet_list and then slice it so that you have two lists:\n", 341 | "`muppet_header` is only of length one, it's the header. `muppet_data` is the other list and contains the remianing elements. Check that the length of `muppet_data` is `8`. " 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": {}, 348 | "outputs": [], 349 | "source": [ 350 | "# Answer \n", 351 | "muppet_header = ...\n", 352 | "muppet_data = '...'\n", 353 | "\n", 354 | "print(f\"It is {len(muppet_data) == 8} that the Muppet Data has 8 rows\")" 355 | ] 356 | }, 357 | { 358 | "cell_type": "code", 359 | "execution_count": null, 360 | "metadata": {}, 361 | "outputs": [], 362 | "source": [ 363 | "# 2.3 Separating the header from the rest. \n", 364 | "\n", 365 | "# Answer \n", 366 | "muppet_header = muppet_list[0] \n", 367 | "muppet_data = muppet_list[1:]\n", 368 | "\n", 369 | "print(f\"It is {len(muppet_data) == 8} that the Muppet Data has 8 rows\")\n" 370 | ] 371 | }, 372 | { 373 | "cell_type": "markdown", 374 | "metadata": {}, 375 | "source": [ 376 | "### Transforming the `muppet_data` into a `muppet_dict`\n", 377 | "\n", 378 | "At this point, we should have 8 lists in a data structure called `muppet_data`. The first element in this list is the name, followed by three data points (`gender`, `species`, `first_appearance`).\n", 379 | "\n", 380 | "Transform each line into a dictionary entry so that the whole dictionary will look something like this: \n", 381 | "\n", 382 | "~~~ python\n", 383 | "muppet_dict = {\"Fozzie\":[\"Male\",\"Bear\",1976], \n", 384 | " \"Kermit\": ..., \n", 385 | " ...}'''\n", 386 | "~~~\n", 387 | "\n", 388 | "To create this dictionary you might need to repeat lines of code while only changing the indices. \n", 389 | "\n", 390 | "This will be the last repetitive code example to complete. I will give fewer instructions here. If you know loops, you can try them here, but I am assuming you have not skipped to chapter 3. In case you have, know that I provide two answers to this in the next appendix. One with and one without loops. " 391 | ] 392 | }, 393 | { 394 | "cell_type": "code", 395 | "execution_count": null, 396 | "metadata": {}, 397 | "outputs": [], 398 | "source": [ 399 | "# Answer\n", 400 | "\n", 401 | "m_dict = {} \n", 402 | "\n", 403 | "m_dict[muppet_data[0][0]] = ...\n", 404 | "m_dict[muppet_data[1][0]] = ...\n", 405 | "...\n", 406 | "\n", 407 | "print(m_dict)\n", 408 | "print(f\"It is {len(m_dict.keys())==8} that the muppet_dict has 8 keys.\")" 409 | ] 410 | }, 411 | { 412 | "cell_type": "code", 413 | "execution_count": null, 414 | "metadata": {}, 415 | "outputs": [], 416 | "source": [ 417 | "# Answer\n", 418 | "\n", 419 | "m_dict = {} \n", 420 | "\n", 421 | "m_dict[muppet_data[0][0]] = muppet_data[0][1:]\n", 422 | "m_dict[muppet_data[1][0]] = muppet_data[1][1:]\n", 423 | "m_dict[muppet_data[2][0]] = muppet_data[2][1:]\n", 424 | "m_dict[muppet_data[3][0]] = muppet_data[3][1:]\n", 425 | "m_dict[muppet_data[4][0]] = muppet_data[4][1:]\n", 426 | "m_dict[muppet_data[5][0]] = muppet_data[5][1:]\n", 427 | "m_dict[muppet_data[6][0]] = muppet_data[6][1:]\n", 428 | "m_dict[muppet_data[7][0]] = muppet_data[7][1:]\n", 429 | "\n", 430 | "print(f\"It is {len(m_dict.keys())==8} that the muppet_dict has 8 keys.\")" 431 | ] 432 | }, 433 | { 434 | "cell_type": "markdown", 435 | "metadata": {}, 436 | "source": [ 437 | "### Query the muppet data (Tougher bonus challenge)\n", 438 | "\n", 439 | "Use the following code pattern: \n", 440 | "\n", 441 | "~~~ python\n", 442 | "user_input = input(\"Which muppet do you want to profile:\")\n", 443 | "~~~ \n", 444 | " \n", 445 | "Then take the data from `user_input` and print a profile of the muppet in the following form: " 446 | ] 447 | }, 448 | { 449 | "cell_type": "raw", 450 | "metadata": {}, 451 | "source": [ 452 | "Character: \n", 453 | " Fozzie\n", 454 | "Profile: \n", 455 | " Gender: Male\n", 456 | " Species: Bear\n", 457 | " First Appearance: 1976" 458 | ] 459 | }, 460 | { 461 | "cell_type": "markdown", 462 | "metadata": {}, 463 | "source": [ 464 | "Consider printing a list of all muppets (i.e. all keys from the dictionary) before asking for user input so the user can get the correct spelling. You might find other ways to make this robust, especially after reading in the later chapters. " 465 | ] 466 | }, 467 | { 468 | "cell_type": "code", 469 | "execution_count": null, 470 | "metadata": {}, 471 | "outputs": [], 472 | "source": [ 473 | "user_input = input(\"Which muppet do you want to profile:\")\n", 474 | "\n", 475 | "print(...)" 476 | ] 477 | }, 478 | { 479 | "cell_type": "code", 480 | "execution_count": null, 481 | "metadata": {}, 482 | "outputs": [], 483 | "source": [ 484 | "# Example answer \n", 485 | "\n", 486 | "user_input = input(\"Which muppet do you want to profile:\")\n", 487 | "\n", 488 | "gen = m_dict[user_input][0]\n", 489 | "sp = m_dict[user_input][1]\n", 490 | "fa = m_dict[user_input][2]\n", 491 | "print(f\"Character:\\n\\t{user_input}\\nProfle:\\n\\tGender: {gen}\\n\\tSpecies: {sp}\\n\\tFirst Appearance: {fa}\")" 492 | ] 493 | }, 494 | { 495 | "cell_type": "markdown", 496 | "metadata": {}, 497 | "source": [ 498 | "# Flow control" 499 | ] 500 | }, 501 | { 502 | "cell_type": "markdown", 503 | "metadata": {}, 504 | "source": [ 505 | "## Fozzie Bear! \n", 506 | "\n", 507 | "This is based on the classic coding challenge, \"Fizz Buzz\". To cheat or compare answers see: https://wiki.c2.com/?FizzBuzzTest. I, like many instructors, like to use FizzBuzz because you cannot simply make it work with one loop and one if statement. Here goes: \n", 508 | "\n", 509 | "Make a program that spits out numbers and the words Fozzie Bear. \n", 510 | "\n", 511 | "- If the line is a multiple of 3 print the line number + Fozzie, like `6. Fozzie\n", 512 | "- If the line is a multiple of 5 print the line number + Bear, like `10. Bear`\n", 513 | "- If the line is a multiple of both, print a line number + both words, like `15. Fozzie Bear` \n", 514 | "- Otherwise do not print anything. \n", 515 | "\n", 516 | "Have the program run in the range 1 to 30 inclusive (so I should read `30. Fozzie Bear` as the final line. " 517 | ] 518 | }, 519 | { 520 | "cell_type": "code", 521 | "execution_count": null, 522 | "metadata": {}, 523 | "outputs": [], 524 | "source": [ 525 | "# Answer below here: \n" 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "execution_count": null, 531 | "metadata": {}, 532 | "outputs": [], 533 | "source": [ 534 | "# Answer below here: \n", 535 | "for i in range(1, 31):\n", 536 | " if not i % 3:\n", 537 | " if not i % 5 :\n", 538 | " print(f'{i}. Fozzie Bear')\n", 539 | " else:\n", 540 | " print(f'{i}. Fozzie')\n", 541 | " elif i % 5 == 0:\n", 542 | " print(f'{i}. Bear')" 543 | ] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "execution_count": null, 548 | "metadata": {}, 549 | "outputs": [], 550 | "source": [] 551 | }, 552 | { 553 | "cell_type": "markdown", 554 | "metadata": {}, 555 | "source": [ 556 | "## List (and dictionary) comprehension practice" 557 | ] 558 | }, 559 | { 560 | "cell_type": "code", 561 | "execution_count": null, 562 | "metadata": {}, 563 | "outputs": [], 564 | "source": [ 565 | "# 3a. Loop 1. The simplest example.\n", 566 | "\n", 567 | "ex_list = []\n", 568 | "for i in range(1,10): \n", 569 | " ex_list.append(i)\n", 570 | " \n", 571 | "# List comprehension\n", 572 | "\n", 573 | "lc_ex_list = ...\n", 574 | "\n", 575 | "\n", 576 | "# Check yout answer: (should be True)\n", 577 | "print(lc_ex_list == ex_list)" 578 | ] 579 | }, 580 | { 581 | "cell_type": "code", 582 | "execution_count": null, 583 | "metadata": {}, 584 | "outputs": [], 585 | "source": [ 586 | "# 3a. Loop 1. The simplest example.\n", 587 | "\n", 588 | "ex_list = []\n", 589 | "for i in range(1,10): \n", 590 | " ex_list.append(i)\n", 591 | " \n", 592 | "# List comprehension\n", 593 | "\n", 594 | "lc_ex_list = [i for i in range(1,10)]\n", 595 | "\n", 596 | "\n", 597 | "# Check yout answer: (should be True)\n", 598 | "print(lc_ex_list == ex_list)" 599 | ] 600 | }, 601 | { 602 | "cell_type": "code", 603 | "execution_count": null, 604 | "metadata": {}, 605 | "outputs": [], 606 | "source": [ 607 | "# 3b. Loop 2. An example with an if statement (i.e. a 'conditional')\n", 608 | "\n", 609 | "every_second_list = []\n", 610 | "for i in range(1,10): \n", 611 | " if i%2 == 0:\n", 612 | " every_second_list.append(i)\n", 613 | "\n", 614 | "# List comprehension \n", 615 | "\n", 616 | "lc_every_second_list = ... \n", 617 | "\n", 618 | "# Check your answer: (should be True)\n", 619 | "print(lc_every_second_list == every_second_list)" 620 | ] 621 | }, 622 | { 623 | "cell_type": "code", 624 | "execution_count": null, 625 | "metadata": {}, 626 | "outputs": [], 627 | "source": [ 628 | "# 3b. Loop 2. An example with an if statement (i.e. a 'conditional')\n", 629 | "\n", 630 | "every_second_list = []\n", 631 | "for i in range(1,10): \n", 632 | " if i%2 == 0:\n", 633 | " every_second_list.append(i)\n", 634 | "\n", 635 | "# List comprehension \n", 636 | "lc_every_second_list = [i for i in range(1,10) if i%2 == 0]\n", 637 | "\n", 638 | "# Check your answer: (should be True)\n", 639 | "print(lc_every_second_list == every_second_list)" 640 | ] 641 | }, 642 | { 643 | "cell_type": "code", 644 | "execution_count": null, 645 | "metadata": {}, 646 | "outputs": [], 647 | "source": [ 648 | "# 3c. Loop 3. An example with calculation\n", 649 | "\n", 650 | "powers_of_two_list = [] \n", 651 | "for i in range(10):\n", 652 | " powers_of_two_list.append(i**2)\n", 653 | "\n", 654 | "# List comprehension\n", 655 | "\n", 656 | "lc_powers_of_two_list = ...\n", 657 | "\n", 658 | "\n", 659 | "# Check your answer: (Should be True)\n", 660 | "print(lc_powers_of_two_list == powers_of_two_list)" 661 | ] 662 | }, 663 | { 664 | "cell_type": "code", 665 | "execution_count": null, 666 | "metadata": {}, 667 | "outputs": [], 668 | "source": [ 669 | "# 3c. Loop 3. An example with calculation\n", 670 | "\n", 671 | "powers_of_two_list = [] \n", 672 | "for i in range(10):\n", 673 | " powers_of_two_list.append(i**2)\n", 674 | "\n", 675 | "# List comprehension\n", 676 | "\n", 677 | "lc_powers_of_two_list = [i**2 for i in range(10)]\n", 678 | "\n", 679 | "\n", 680 | "# Check your answer: (Should be True)\n", 681 | "print(lc_powers_of_two_list == powers_of_two_list)" 682 | ] 683 | }, 684 | { 685 | "cell_type": "code", 686 | "execution_count": null, 687 | "metadata": {}, 688 | "outputs": [], 689 | "source": [ 690 | "# 3d. Loop 4. A Dictionary Comprehension\n", 691 | "\n", 692 | "old_list = [\"zeroith\",\"first\",\"what's zeroith?\",\"Am I third or fourth?\"]\n", 693 | "new_dict = {} \n", 694 | "\n", 695 | "for c,i in enumerate(old_list): \n", 696 | " new_dict[c] = i\n", 697 | "\n", 698 | "# Dictionary comprehension\n", 699 | "\n", 700 | "\n", 701 | "dc_new_dict = ...\n", 702 | "\n", 703 | "# Check your answer: (Should be True)\n", 704 | "print(new_dict == dc_new_dict)\n" 705 | ] 706 | }, 707 | { 708 | "cell_type": "code", 709 | "execution_count": null, 710 | "metadata": {}, 711 | "outputs": [], 712 | "source": [ 713 | "# 3d. Loop 4. A Dictionary Comprehension\n", 714 | "\n", 715 | "old_list = [\"zeroith\",\"first\",\"what's zeroith?\",\"Am I third or fourth?\"]\n", 716 | "new_dict = {} \n", 717 | "\n", 718 | "for c,i in enumerate(old_list): \n", 719 | " new_dict[c] = i\n", 720 | "\n", 721 | "# Dictionary comprehension\n", 722 | "\n", 723 | "\n", 724 | "dc_new_dict = {c:i for c,i in enumerate(old_list)}\n", 725 | "\n", 726 | "# Check your answer: (Should be True)\n", 727 | "print(new_dict == dc_new_dict)\n" 728 | ] 729 | }, 730 | { 731 | "cell_type": "markdown", 732 | "metadata": {}, 733 | "source": [ 734 | "## Code refactoring I\n", 735 | "\n", 736 | "In addition to these, just a reminder that all of the exercises in the previous section (for the chapter on collections) that have repetitive code can benefit from loops. Have a look at the answers for these and see if you can refactor them to use loops. The answers with loops are provided below here " 737 | ] 738 | }, 739 | { 740 | "cell_type": "markdown", 741 | "metadata": {}, 742 | "source": [ 743 | "### Concrete poetry with a for loop" 744 | ] 745 | }, 746 | { 747 | "cell_type": "code", 748 | "execution_count": null, 749 | "metadata": {}, 750 | "outputs": [], 751 | "source": [ 752 | "word = \"acrobats\"\n", 753 | "\n", 754 | "..." 755 | ] 756 | }, 757 | { 758 | "cell_type": "code", 759 | "execution_count": null, 760 | "metadata": {}, 761 | "outputs": [], 762 | "source": [ 763 | "# Answer using for loops \n", 764 | "\n", 765 | "for c,w in enumerate(word):\n", 766 | " if c%2==1: \n", 767 | " print(\" \" + (w + \" \")*4)\n", 768 | " else:\n", 769 | " print((w + \" \")*5) \n" 770 | ] 771 | }, 772 | { 773 | "cell_type": "code", 774 | "execution_count": null, 775 | "metadata": {}, 776 | "outputs": [], 777 | "source": [ 778 | "# Here's the densest I can make it. \n", 779 | "for c,i in enumerate(\"acrobats\"):\n", 780 | " print(f\"{i} \"*5 if c%2 == 0 else \" \" + f\"{i} \"*4)" 781 | ] 782 | }, 783 | { 784 | "cell_type": "markdown", 785 | "metadata": {}, 786 | "source": [ 787 | "### The Muppets data cleaning with for loops\n", 788 | "\n", 789 | "Recall this one had several steps. Try doing them all in a single cell to get from `muppet_text` to `muppet_dict`. " 790 | ] 791 | }, 792 | { 793 | "cell_type": "code", 794 | "execution_count": null, 795 | "metadata": {}, 796 | "outputs": [], 797 | "source": [ 798 | "muppet_text = '''\n", 799 | "name\tgender\tspecies\tfirst_appearance\n", 800 | "Fozzie\tMale\tBear\t1976\n", 801 | "Kermit\tMale\tFrog\t1955\n", 802 | "Piggy\tFemale\tPig\t1974\n", 803 | "Gonzo\tMale\tUnknown\t1970\n", 804 | "Rowlf\tMale\tDog\t1962\n", 805 | "Beaker\tMale\tMuppet\t1977\n", 806 | "Janice\tFemale\tMuppet\t1975\n", 807 | "Hilda\tFemale\tMuppet\t1976'''" 808 | ] 809 | }, 810 | { 811 | "cell_type": "code", 812 | "execution_count": null, 813 | "metadata": {}, 814 | "outputs": [], 815 | "source": [ 816 | "# Example answer with some for loops \n", 817 | "\n", 818 | "m_dict = {} \n", 819 | "header_row = True\n", 820 | "\n", 821 | "for row in muppet_text.strip().split(\"\\n\"):\n", 822 | " if header_row: \n", 823 | " muppet_header = row.split(\"\\t\")\n", 824 | " header_row = False\n", 825 | " continue\n", 826 | " row = row.split(\"\\t\")\n", 827 | " m_dict[row[0]] = row[1:]\n", 828 | "\n", 829 | "m_dict" 830 | ] 831 | }, 832 | { 833 | "cell_type": "code", 834 | "execution_count": null, 835 | "metadata": {}, 836 | "outputs": [], 837 | "source": [ 838 | "# Example answer (with for dictionary comprehension)\n", 839 | "# Notice with this one you have to do the header row separately. \n", 840 | "# I just excluded that from here. \n", 841 | "\n", 842 | "m_dict = {i.split(\"\\t\")[0]:i.split(\"\\t\")[1:] \n", 843 | " for i in muppet_text.strip().split(\"\\n\")[1:]}\n", 844 | "\n", 845 | "print(m_dict)" 846 | ] 847 | }, 848 | { 849 | "cell_type": "markdown", 850 | "metadata": {}, 851 | "source": [ 852 | "### Making the profile display more robust\n", 853 | "\n", 854 | "Try then to do the profiling code with a `while` statement for user input. Here you can now use elif statements to do somethings in different cases, such as check for valid input and keep going until the user types `quit` or `x`, etc. " 855 | ] 856 | }, 857 | { 858 | "cell_type": "code", 859 | "execution_count": 5, 860 | "metadata": {}, 861 | "outputs": [ 862 | { 863 | "name": "stdin", 864 | "output_type": "stream", 865 | "text": [ 866 | "Which muppet do you want to profile:(x to quit) Fozzie\n" 867 | ] 868 | } 869 | ], 870 | "source": [ 871 | "while ...: \n", 872 | " user_input = input(\"Which muppet do you want to profile:(x to quit)\")\n", 873 | " \n", 874 | " ...\n", 875 | " \n", 876 | " break" 877 | ] 878 | }, 879 | { 880 | "cell_type": "code", 881 | "execution_count": null, 882 | "metadata": {}, 883 | "outputs": [], 884 | "source": [ 885 | "while True: \n", 886 | " user_input = input(\"Which muppet do you want to profile:(x to quit)\")\n", 887 | " \n", 888 | " if user_input.lower() == \"l\":\n", 889 | " print (\"\\n\".join(m_dict.keys()))\n", 890 | " elif user_input.lower() == \"x\":\n", 891 | " break\n", 892 | " elif user_input in m_dict.keys(): \n", 893 | " gen = m_dict[user_input][0]\n", 894 | " sp = m_dict[user_input][1]\n", 895 | " fa = m_dict[user_input][2]\n", 896 | " print(f\"Character:\\n\\t{user_input}\\nProfle:\\n\\tGender: {gen}\\n\\tSpecies {sp}\\n\\tFirst Appearance: {fa}\")\n", 897 | " else: \n", 898 | " print(\"That was not a valid name. Type L to see names of muppets.\")" 899 | ] 900 | }, 901 | { 902 | "cell_type": "markdown", 903 | "metadata": {}, 904 | "source": [ 905 | "# Chapter 5. Functions and classes" 906 | ] 907 | }, 908 | { 909 | "cell_type": "markdown", 910 | "metadata": { 911 | "jupyter": { 912 | "outputs_hidden": false 913 | } 914 | }, 915 | "source": [ 916 | "## Who said programming was better than flipping burgers? \n", 917 | "\n", 918 | "Flipping burgers can be fast-paced and stressful. But poor order tickets can make it harder. Let's build a function to produce clear order tickets. \n", 919 | "\n", 920 | "All hamburgers will have a bun and a patty. \n", 921 | "- The default bun = \"white\"\n", 922 | "- The default patty = \"beef\"\n", 923 | "- Some hamburgers have additional toppings, they will be sent as a list e.g., toppings = [\"cheese\", \"lettuce\"] \n", 924 | "\n", 925 | "HINT: Comment out parts of the code below END ANSWER while you are building your function. Start with the simple default burger and work your way towards to other burgers. " 926 | ] 927 | }, 928 | { 929 | "cell_type": "code", 930 | "execution_count": 15, 931 | "metadata": { 932 | "collapsed": false, 933 | "jupyter": { 934 | "outputs_hidden": false 935 | } 936 | }, 937 | "outputs": [], 938 | "source": [ 939 | "# Answer Below here. \n", 940 | "\n", 941 | "def burger_order():\n", 942 | " ...\n", 943 | " return \n", 944 | " \n", 945 | "\n" 946 | ] 947 | }, 948 | { 949 | "cell_type": "code", 950 | "execution_count": 13, 951 | "metadata": { 952 | "collapsed": false, 953 | "jupyter": { 954 | "outputs_hidden": false 955 | } 956 | }, 957 | "outputs": [], 958 | "source": [ 959 | "# Answer Below here. \n", 960 | "#*********************************\n", 961 | "\n", 962 | "def burger_order(bun = \"white\", patty = \"beef\", toppings = []):\n", 963 | " receipt = \"\\n***Burger Order***\\n\\n\\n\"\n", 964 | " \n", 965 | " receipt += \"Bun: %s\\n\" % bun\n", 966 | " receipt += \"Patty: %s\\n\" % patty\n", 967 | " if len(toppings) > 0: \n", 968 | " receipt += \"Extras:\\n\"\n", 969 | " for i in toppings: \n", 970 | " receipt += \"- %s\\n\" % i\n", 971 | " \n", 972 | " return receipt\n", 973 | " \n", 974 | "\n", 975 | "#********** END ANSWER ************" 976 | ] 977 | }, 978 | { 979 | "cell_type": "code", 980 | "execution_count": null, 981 | "metadata": { 982 | "collapsed": false, 983 | "jupyter": { 984 | "outputs_hidden": false 985 | } 986 | }, 987 | "outputs": [], 988 | "source": [ 989 | "# Testing code. Check the output of this code with the strings provided.\n", 990 | "\n", 991 | "default_burger = burger_order()\n", 992 | "print(default_burger)\n", 993 | "# output should be: \n", 994 | "'''\n", 995 | "***Burger Order***\n", 996 | "\n", 997 | "Bun: white\n", 998 | "Patty: beef\n", 999 | "'''\n", 1000 | "\n", 1001 | "cheese_burger = burger_order(toppings = [\"chesse\"])\n", 1002 | "print(cheese_burger)\n", 1003 | "# output should be: \n", 1004 | "'''\n", 1005 | "***Burger Order***\n", 1006 | "\n", 1007 | "Bun: white\n", 1008 | "Patty: beef\n", 1009 | "Extras: \n", 1010 | "- cheese\n", 1011 | "'''\n", 1012 | "\n", 1013 | "super_burger = burger_order(bun=\"whole wheat\",toppings =[\"cheese\",\"lettuce\",\"tomato\",\"pickle\"])\n", 1014 | "print(super_burger)\n", 1015 | "# output should be: \n", 1016 | "'''\n", 1017 | "***Burger Order***\n", 1018 | "\n", 1019 | "Bun: whole wheat\n", 1020 | "Patty: beef\n", 1021 | "Extras: \n", 1022 | "- cheese\n", 1023 | "- lettuce\n", 1024 | "- tomato\n", 1025 | "- pickle\n", 1026 | "'''\n", 1027 | "\n", 1028 | "chicken_burger = burger_order(toppings=[\"lettuce\",\"tomato\"],patty = \"chicken\")\n", 1029 | "print(chicken_burger)\n", 1030 | "# output should be: \n", 1031 | "'''\n", 1032 | "***Burger Order***\n", 1033 | "\n", 1034 | "Bun: white\n", 1035 | "Patty: chicken\n", 1036 | "Extras: \n", 1037 | "- lettuce\n", 1038 | "- tomato\n", 1039 | "'''\n", 1040 | "\n", 1041 | "health_burger = burger_order(\"gluten-free\",\"veggie\",[\"lettuce\",\"tomato\",\"pickle\"])\n", 1042 | "print(health_burger)\n", 1043 | "# output should be: \n", 1044 | "'''\n", 1045 | "***Burger Order***\n", 1046 | "\n", 1047 | "Bun: gluten-free\n", 1048 | "Patty: veggie\n", 1049 | "extras:\n", 1050 | "- lettuce\n", 1051 | "- tomato\n", 1052 | "- pickle\n", 1053 | "''';" 1054 | ] 1055 | }, 1056 | { 1057 | "cell_type": "markdown", 1058 | "metadata": { 1059 | "jupyter": { 1060 | "outputs_hidden": false 1061 | } 1062 | }, 1063 | "source": [ 1064 | "### Some extensions to this include:\n", 1065 | "- Give each order a number. Try to remember the previous order number.\n", 1066 | "- What about using wildcard `kwargs` arguments in order to allow for any topping?\n", 1067 | "- What about set burger types? How might these be best expressed? " 1068 | ] 1069 | } 1070 | ], 1071 | "metadata": { 1072 | "kernelspec": { 1073 | "display_name": "Python 3", 1074 | "language": "python", 1075 | "name": "python3" 1076 | }, 1077 | "language_info": { 1078 | "codemirror_mode": { 1079 | "name": "ipython", 1080 | "version": 3 1081 | }, 1082 | "file_extension": ".py", 1083 | "mimetype": "text/x-python", 1084 | "name": "python", 1085 | "nbconvert_exporter": "python", 1086 | "pygments_lexer": "ipython3", 1087 | "version": "3.8.5" 1088 | } 1089 | }, 1090 | "nbformat": 4, 1091 | "nbformat_minor": 4 1092 | } 1093 | -------------------------------------------------------------------------------- /latex/build_book.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | from pathlib import Path 4 | from os import sep as ossep 5 | 6 | def ignore_colab(text): 7 | 8 | return text 9 | 10 | def convert_notebooks(pattern="*",output_dir="."): 11 | 12 | for file in glob.glob(pattern): 13 | os.system(f'jupyter nbconvert --to latex {file} --no-prompt --output-dir {output_dir} ') 14 | 15 | return 16 | 17 | 18 | def main(nbconvert=True,texclean=True,makelatex=True,jobname="book"): 19 | 20 | if nbconvert: 21 | print("NBCONVERT - Started.") 22 | convert_notebooks("../chapters/Ch.*.ipynb","tex/") 23 | convert_notebooks("../exercises/Ch.*.ipynb","tex/") 24 | 25 | print("NBCONVERT - Done.") 26 | 27 | if texclean: 28 | 29 | for file in glob.glob("tex/Ch.*.tex"): 30 | blob = open(file).read() 31 | 32 | blob_split = blob.split("maketitle",1) 33 | if len(blob_split) > 1: 34 | blob = blob_split[1].split("% Add a bibliography")[0] 35 | 36 | with open(file,'w') as fileout: 37 | fileout.write(blob) 38 | 39 | print("Tex files cleaned") 40 | 41 | 42 | if makelatex: 43 | os.chdir("tex/") 44 | os.system(f'xelatex -jobname {jobname} book.tex') 45 | os.system(f'biber -jobname {jobname} book.tex') 46 | os.system(f'xelatex -jobname {jobname} book.tex') 47 | os.system(f'xelatex -jobname {jobname} book.tex') 48 | 49 | if __name__ == "__main__": 50 | main(nbconvert=True, 51 | texclean=True, 52 | https://github.com/berniehogan/fsstds makelatex=True, 53 | jobname = "IntroducingPython") 54 | -------------------------------------------------------------------------------- /pdf/IntroducingPython.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/berniehogan/IntroducingPython/86c69be0dc0af21e1c88f419b68bcc40642fb8b2/pdf/IntroducingPython.pdf --------------------------------------------------------------------------------