├── .gitattributes ├── 9781484253540.jpg ├── AB_NYC_2019.csv ├── Contributing.md ├── LICENSE.txt ├── README.md ├── Week_01.ipynb ├── Week_02.ipynb ├── Week_03.ipynb ├── Week_04.ipynb ├── Week_07.ipynb ├── Week_08.ipynb ├── Week_09.ipynb ├── Week_10.ipynb ├── calculation.py ├── data.csv ├── errata.md ├── favorite_food.csv ├── microsoft.png ├── microsoft_analysis.png ├── numbers.txt ├── population.jpg ├── site_data └── microsoft_frequent_words.csv ├── test.csv ├── test.py ├── test.txt ├── users.csv ├── week_05.ipynb └── week_06.ipynb /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /9781484253540.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/python-projects-for-beginners/73b734b311e18f6f15b7685e0f04b81e441d2ae1/9781484253540.jpg -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Freeware License, some rights reserved 2 | 3 | Copyright (c) 2020 Connor Milliken 4 | 5 | Permission is hereby granted, free of charge, to anyone obtaining a copy 6 | of this software and associated documentation files (the "Software"), 7 | to work with the Software within the limits of freeware distribution and fair use. 8 | This includes the rights to use, copy, and modify the Software for personal use. 9 | Users are also allowed and encouraged to submit corrections and modifications 10 | to the Software for the benefit of other users. 11 | 12 | It is not allowed to reuse, modify, or redistribute the Software for 13 | commercial use in any way, or for a user’s educational materials such as books 14 | or blog articles without prior permission from the copyright holder. 15 | 16 | The above copyright notice and this permission notice need to be included 17 | in all copies or substantial portions of the software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | 27 | 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Python Projects for Beginners*](https://www.apress.com/9781484253540) by Connor Milliken (Apress, 2020). 4 | 5 | [comment]: #cover 6 | ![Cover image](9781484253540.jpg) 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. -------------------------------------------------------------------------------- /Week_01.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "collapsed": true 7 | }, 8 | "source": [ 9 | "# Week 01" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [ 17 | { 18 | "name": "stdout", 19 | "output_type": "stream", 20 | "text": [ 21 | "Hello, buddy!\n" 22 | ] 23 | } 24 | ], 25 | "source": [ 26 | "# this is python\n", 27 | "\n", 28 | "print('Hello, buddy!')" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": { 35 | "collapsed": true 36 | }, 37 | "outputs": [], 38 | "source": [ 39 | "# guessing game\n", 40 | "from random import randint\n", 41 | "from IPython.display import clear_output\n", 42 | "\n", 43 | "guessed = False\n", 44 | "number = randint(0, 100)\n", 45 | "guesses = 0\n", 46 | "\n", 47 | "while not guessed: \n", 48 | " ans = input('Try to guess the number I am thinking of! ')\n", 49 | " \n", 50 | " guesses += 1\n", 51 | " \n", 52 | " clear_output()\n", 53 | " \n", 54 | " if int(ans) == number:\n", 55 | " print('Congrats! You guessed it correctly.')\n", 56 | " print('It took you {} guesses!'.format(guesses))\n", 57 | " break\n", 58 | " elif int(ans) > number:\n", 59 | " print('The number is lower than what you guessed.')\n", 60 | " elif int(ans) < number:\n", 61 | " print('The number is greater than what you guessed.')" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "# End of Week Exercises - Answers" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "

\n", 76 | "2. Writing Markdown: Within the file from exercise 1, create a cell with markdown in it that says \"Challenge 1\". Try several different header sizes. Pick the one you like best.\n", 77 | "

" 78 | ] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "metadata": {}, 83 | "source": [ 84 | "#### Challenge 1" 85 | ] 86 | } 87 | ], 88 | "metadata": { 89 | "kernelspec": { 90 | "display_name": "Python 3", 91 | "language": "python", 92 | "name": "python3" 93 | }, 94 | "language_info": { 95 | "codemirror_mode": { 96 | "name": "ipython", 97 | "version": 3 98 | }, 99 | "file_extension": ".py", 100 | "mimetype": "text/x-python", 101 | "name": "python", 102 | "nbconvert_exporter": "python", 103 | "pygments_lexer": "ipython3", 104 | "version": "3.6.5" 105 | } 106 | }, 107 | "nbformat": 4, 108 | "nbformat_minor": 2 109 | } 110 | -------------------------------------------------------------------------------- /Week_02.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Comments & Data Types" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 5, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "Hello\n" 20 | ] 21 | } 22 | ], 23 | "source": [ 24 | "# this is a comment\n", 25 | "\n", 26 | "\"\"\"\n", 27 | " this is a\n", 28 | " multi-line\n", 29 | " comment\n", 30 | "\"\"\"\n", 31 | "\n", 32 | "print('Hello') # this is also a comment" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 1, 38 | "metadata": { 39 | "scrolled": true 40 | }, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "2\n", 47 | "10\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "# the following are all integers\n", 53 | "\n", 54 | "print(2)\n", 55 | "\n", 56 | "print(10)" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 3, 62 | "metadata": {}, 63 | "outputs": [ 64 | { 65 | "name": "stdout", 66 | "output_type": "stream", 67 | "text": [ 68 | "10.953\n", 69 | "8.0\n" 70 | ] 71 | } 72 | ], 73 | "source": [ 74 | "# the following are all floats\n", 75 | "\n", 76 | "print(10.953)\n", 77 | "\n", 78 | "print(8.0) # even this number is a float" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 6, 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "name": "stdout", 88 | "output_type": "stream", 89 | "text": [ 90 | "True\n", 91 | "False\n" 92 | ] 93 | } 94 | ], 95 | "source": [ 96 | "# the following are booleans\n", 97 | "\n", 98 | "print(True)\n", 99 | "\n", 100 | "print(False)" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 2, 106 | "metadata": {}, 107 | "outputs": [ 108 | { 109 | "name": "stdout", 110 | "output_type": "stream", 111 | "text": [ 112 | "\n", 113 | "There's a snake in my boot!\n", 114 | "True\n" 115 | ] 116 | } 117 | ], 118 | "source": [ 119 | "# the following are strings\n", 120 | "\n", 121 | "print('')\n", 122 | "\n", 123 | "print(\"There's a snake in my boot!\")\n", 124 | "\n", 125 | "print('True')" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": {}, 131 | "source": [ 132 | "# Variables" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": 2, 138 | "metadata": { 139 | "scrolled": true 140 | }, 141 | "outputs": [ 142 | { 143 | "ename": "NameError", 144 | "evalue": "name 'sport' is not defined", 145 | "output_type": "error", 146 | "traceback": [ 147 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 148 | "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", 149 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0mSport\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'baseball'\u001b[0m \u001b[1;31m# capital 'S'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0msport\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# lowercase 's'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 150 | "\u001b[1;31mNameError\u001b[0m: name 'sport' is not defined" 151 | ] 152 | } 153 | ], 154 | "source": [ 155 | "Sport = 'baseball' # capital 'S'\n", 156 | "print(sport) # lowercase 's'" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 3, 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "5 8.4\n" 169 | ] 170 | } 171 | ], 172 | "source": [ 173 | "num1 = 5 # storing an integer into a variable\n", 174 | "\n", 175 | "num2 = 8.4 # storing a float into a variable\n", 176 | "\n", 177 | "print(num1, num2) # you can print multiple items using commas" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": 5, 183 | "metadata": {}, 184 | "outputs": [ 185 | { 186 | "name": "stdout", 187 | "output_type": "stream", 188 | "text": [ 189 | "True\n" 190 | ] 191 | } 192 | ], 193 | "source": [ 194 | "# storing a boolean into a variable\n", 195 | "\n", 196 | "switch = True\n", 197 | "\n", 198 | "print(switch)" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 5, 204 | "metadata": {}, 205 | "outputs": [ 206 | { 207 | "name": "stdout", 208 | "output_type": "stream", 209 | "text": [ 210 | "John Smith 9\n" 211 | ] 212 | } 213 | ], 214 | "source": [ 215 | "# storing strings into a variable\n", 216 | "\n", 217 | "name = 'John Smith'\n", 218 | "\n", 219 | "fav_number = '9'\n", 220 | "\n", 221 | "print(name, fav_number) # will print 9 next to the name" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": 5, 227 | "metadata": {}, 228 | "outputs": [ 229 | { 230 | "name": "stdout", 231 | "output_type": "stream", 232 | "text": [ 233 | "13.4\n" 234 | ] 235 | } 236 | ], 237 | "source": [ 238 | "# using two variables to create another variable\n", 239 | "\n", 240 | "result = num1 + num2\n", 241 | "\n", 242 | "print(result)" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 6, 248 | "metadata": {}, 249 | "outputs": [ 250 | { 251 | "name": "stdout", 252 | "output_type": "stream", 253 | "text": [ 254 | "14.4\n", 255 | "72.0\n" 256 | ] 257 | } 258 | ], 259 | "source": [ 260 | "# adding, deleting, multiplying, dividing from a variable\n", 261 | "\n", 262 | "result += 1 # same as saying result = result + 1\n", 263 | "print(result)\n", 264 | "\n", 265 | "result *= num1 # same as saying result = result * num1\n", 266 | "print(result)" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": 7, 272 | "metadata": {}, 273 | "outputs": [ 274 | { 275 | "name": "stdout", 276 | "output_type": "stream", 277 | "text": [ 278 | "John\n", 279 | "Sam\n" 280 | ] 281 | } 282 | ], 283 | "source": [ 284 | "# defining a variable and overwriting it's value\n", 285 | "\n", 286 | "name = 'John'\n", 287 | "print(name)\n", 288 | "\n", 289 | "name = 'Sam'\n", 290 | "print(name)" 291 | ] 292 | }, 293 | { 294 | "cell_type": "markdown", 295 | "metadata": {}, 296 | "source": [ 297 | "# Working with Strings" 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": 8, 303 | "metadata": {}, 304 | "outputs": [ 305 | { 306 | "name": "stdout", 307 | "output_type": "stream", 308 | "text": [ 309 | "John Smith\n" 310 | ] 311 | } 312 | ], 313 | "source": [ 314 | "# using the addition operator without variables\n", 315 | "\n", 316 | "name = 'John' + ' ' + 'Smith'\n", 317 | "\n", 318 | "print(name)" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": 9, 324 | "metadata": {}, 325 | "outputs": [ 326 | { 327 | "name": "stdout", 328 | "output_type": "stream", 329 | "text": [ 330 | "John Smith\n" 331 | ] 332 | } 333 | ], 334 | "source": [ 335 | "# using the addition operator with variables\n", 336 | "\n", 337 | "first_name = 'John'\n", 338 | "last_name = 'Smith'\n", 339 | "\n", 340 | "full_name = first_name + ' ' + last_name\n", 341 | "\n", 342 | "print(full_name)" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 10, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "name": "stdout", 352 | "output_type": "stream", 353 | "text": [ 354 | "Hello John\n", 355 | "Hello John, you are 28 years old!\n" 356 | ] 357 | } 358 | ], 359 | "source": [ 360 | "# injecting variables using the format method\n", 361 | "\n", 362 | "name = 'John'\n", 363 | "\n", 364 | "print('Hello {}'.format(name))\n", 365 | "\n", 366 | "print('Hello {}, you are {} years old!'.format(name, 28))" 367 | ] 368 | }, 369 | { 370 | "cell_type": "code", 371 | "execution_count": 11, 372 | "metadata": {}, 373 | "outputs": [ 374 | { 375 | "name": "stdout", 376 | "output_type": "stream", 377 | "text": [ 378 | "Hello John\n" 379 | ] 380 | } 381 | ], 382 | "source": [ 383 | "# using the new f strings\n", 384 | "\n", 385 | "name = 'John'\n", 386 | "\n", 387 | "print(f'Hello {name}')" 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": 12, 393 | "metadata": {}, 394 | "outputs": [ 395 | { 396 | "name": "stdout", 397 | "output_type": "stream", 398 | "text": [ 399 | "Hello, John\n" 400 | ] 401 | } 402 | ], 403 | "source": [ 404 | "# one major difference between versions 2 & 3\n", 405 | "\n", 406 | "name = 'John'\n", 407 | "\n", 408 | "print('Hello, %s' % name)" 409 | ] 410 | }, 411 | { 412 | "cell_type": "code", 413 | "execution_count": 6, 414 | "metadata": {}, 415 | "outputs": [ 416 | { 417 | "name": "stdout", 418 | "output_type": "stream", 419 | "text": [ 420 | "Hello, John Smith\n" 421 | ] 422 | } 423 | ], 424 | "source": [ 425 | "# python 2 multiple variable formatting\n", 426 | "\n", 427 | "first_name = \"John\"\n", 428 | "last_name = \"Smith\"\n", 429 | "\n", 430 | "print(\"Hello, %s %s\" % (first_name, last_name))" 431 | ] 432 | }, 433 | { 434 | "cell_type": "code", 435 | "execution_count": 8, 436 | "metadata": {}, 437 | "outputs": [ 438 | { 439 | "name": "stdout", 440 | "output_type": "stream", 441 | "text": [ 442 | "H\n", 443 | "e\n", 444 | "o\n" 445 | ] 446 | } 447 | ], 448 | "source": [ 449 | "# using indexes to print each element\n", 450 | "\n", 451 | "word = 'Hello'\n", 452 | "\n", 453 | "print(word[0]) # will output 'H'\n", 454 | "print(word[1]) # will output 'e'\n", 455 | "print(word[-1]) # will output 'o'" 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": 14, 461 | "metadata": {}, 462 | "outputs": [ 463 | { 464 | "name": "stdout", 465 | "output_type": "stream", 466 | "text": [ 467 | "He\n" 468 | ] 469 | } 470 | ], 471 | "source": [ 472 | "print(word[0:2]) # will output 'He'" 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": 9, 478 | "metadata": {}, 479 | "outputs": [ 480 | { 481 | "name": "stdout", 482 | "output_type": "stream", 483 | "text": [ 484 | "Hlo\n" 485 | ] 486 | } 487 | ], 488 | "source": [ 489 | "print( word[ 0 : 5 : 2 ] )" 490 | ] 491 | }, 492 | { 493 | "cell_type": "markdown", 494 | "metadata": {}, 495 | "source": [ 496 | "# Manipulating Strings" 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": 15, 502 | "metadata": {}, 503 | "outputs": [ 504 | { 505 | "name": "stdout", 506 | "output_type": "stream", 507 | "text": [ 508 | "John Smith\n" 509 | ] 510 | } 511 | ], 512 | "source": [ 513 | "# using the title method to capitalize a string\n", 514 | "\n", 515 | "name = 'john smith'\n", 516 | "\n", 517 | "print(name.title())" 518 | ] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": 16, 523 | "metadata": {}, 524 | "outputs": [ 525 | { 526 | "name": "stdout", 527 | "output_type": "stream", 528 | "text": [ 529 | "Hello there.\n" 530 | ] 531 | } 532 | ], 533 | "source": [ 534 | "# replacing an exclamation point with a period\n", 535 | "\n", 536 | "words = 'Hello there!'\n", 537 | "\n", 538 | "print(words.replace('!', '.'))" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": 17, 544 | "metadata": {}, 545 | "outputs": [ 546 | { 547 | "name": "stdout", 548 | "output_type": "stream", 549 | "text": [ 550 | "5\n" 551 | ] 552 | } 553 | ], 554 | "source": [ 555 | "# finding the starting index of our searched term\n", 556 | "\n", 557 | "s = 'Look over that way'\n", 558 | "\n", 559 | "print(s.find('over'))" 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": 12, 565 | "metadata": {}, 566 | "outputs": [ 567 | { 568 | "name": "stdout", 569 | "output_type": "stream", 570 | "text": [ 571 | "john\n" 572 | ] 573 | } 574 | ], 575 | "source": [ 576 | "# removing white space with strip\n", 577 | "\n", 578 | "name = ' john '\n", 579 | "\n", 580 | "print(name.strip( ))" 581 | ] 582 | }, 583 | { 584 | "cell_type": "code", 585 | "execution_count": 19, 586 | "metadata": {}, 587 | "outputs": [ 588 | { 589 | "name": "stdout", 590 | "output_type": "stream", 591 | "text": [ 592 | "['These', 'words', 'are', 'separated', 'by', 'spaces']\n" 593 | ] 594 | } 595 | ], 596 | "source": [ 597 | "# converting a string into a list of words\n", 598 | "\n", 599 | "s = 'These words are separated by spaces'\n", 600 | "\n", 601 | "print(s.split(' '))" 602 | ] 603 | }, 604 | { 605 | "cell_type": "markdown", 606 | "metadata": {}, 607 | "source": [ 608 | "# Friday Project: Printing Receipts" 609 | ] 610 | }, 611 | { 612 | "cell_type": "code", 613 | "execution_count": 68, 614 | "metadata": { 615 | "scrolled": true 616 | }, 617 | "outputs": [ 618 | { 619 | "name": "stdout", 620 | "output_type": "stream", 621 | "text": [ 622 | "**************************************************\n", 623 | "\t\tCoding Temple, Inc.\n", 624 | "\t\t283 Franklin St.\n", 625 | "\t\tBoston, Ma\n", 626 | "==================================================\n", 627 | "\tProduct Name\tProduct Price\n", 628 | "\tBooks\t\t$49.95\n", 629 | "\tComputer\t$579.99\n", 630 | "\tMonitor\t\t$124.89\n", 631 | "==================================================\n", 632 | "\t\t\tTotal\n", 633 | "\t\t\t$754.83\n", 634 | "==================================================\n", 635 | "\n", 636 | "\tThanks for shopping with us today!\n", 637 | "\n", 638 | "**************************************************\n" 639 | ] 640 | } 641 | ], 642 | "source": [ 643 | "# create a product and price for three items\n", 644 | "p1_name, p1_price = 'Books', 49.95\n", 645 | "p2_name, p2_price = 'Computer', 579.99\n", 646 | "p3_name, p3_price = 'Monitor', 124.89\n", 647 | "\n", 648 | "# create a company name and information\n", 649 | "company_name = 'coding temple, inc.'\n", 650 | "company_address = '283 Franklin St.'\n", 651 | "company_city = 'Boston, MA'\n", 652 | "\n", 653 | "# declare ending message\n", 654 | "message = 'Thanks for shopping with us today!'\n", 655 | "\n", 656 | "# create a top border\n", 657 | "print('*' * 50)\n", 658 | "\n", 659 | "# print company information first using format\n", 660 | "print('\\t\\t{}'.format(company_name.title()))\n", 661 | "print('\\t\\t{}'.format(company_address.title()))\n", 662 | "print('\\t\\t{}'.format(company_city.title()))\n", 663 | "\n", 664 | "# print a line between sections\n", 665 | "print('=' * 50)\n", 666 | "\n", 667 | "# print out header for section of items\n", 668 | "print('\\tProduct Name\\tProduct Price')\n", 669 | "\n", 670 | "# create a print statement for each item\n", 671 | "print('\\t{}\\t\\t${}'.format(p1_name.title(), p1_price))\n", 672 | "print('\\t{}\\t${}'.format(p2_name.title(), p2_price))\n", 673 | "print('\\t{}\\t\\t${}'.format(p3_name.title(), p3_price))\n", 674 | "\n", 675 | "# print a line between sections\n", 676 | "print('=' * 50)\n", 677 | "\n", 678 | "# print out header for section of total\n", 679 | "print('\\t\\t\\tTotal')\n", 680 | "\n", 681 | "# calculate total price and print out\n", 682 | "total = p1_price + p2_price + p3_price\n", 683 | "print('\\t\\t\\t${}'.format(total))\n", 684 | "\n", 685 | "# print a line between sections\n", 686 | "print('=' * 50)\n", 687 | "\n", 688 | "# output thank you message\n", 689 | "print('\\n\\t{}\\n'.format(message))\n", 690 | "\n", 691 | "# create a bottom border\n", 692 | "print('*' * 50)" 693 | ] 694 | }, 695 | { 696 | "cell_type": "markdown", 697 | "metadata": {}, 698 | "source": [ 699 | "# Monday Exercises - Answers" 700 | ] 701 | }, 702 | { 703 | "cell_type": "markdown", 704 | "metadata": {}, 705 | "source": [ 706 | "

\n", 707 | "1. Output: Print our your name.\n", 708 | "

" 709 | ] 710 | }, 711 | { 712 | "cell_type": "code", 713 | "execution_count": 1, 714 | "metadata": {}, 715 | "outputs": [ 716 | { 717 | "name": "stdout", 718 | "output_type": "stream", 719 | "text": [ 720 | "Connor P. Milliken\n" 721 | ] 722 | } 723 | ], 724 | "source": [ 725 | "print(\"Connor P. Milliken\")" 726 | ] 727 | }, 728 | { 729 | "cell_type": "markdown", 730 | "metadata": {}, 731 | "source": [ 732 | "

\n", 733 | "2. Type Checking: Try checking the type of a value by using the type() method. This will always print out what kind of data type you're checking. This is useful to check data types when you're unsure. As an example:\n", 734 | "

\n", 735 | "\n", 736 | "

\n", 737 | ">>> type(int) # will output \n", 738 | "

" 739 | ] 740 | }, 741 | { 742 | "cell_type": "code", 743 | "execution_count": 4, 744 | "metadata": {}, 745 | "outputs": [ 746 | { 747 | "data": { 748 | "text/plain": [ 749 | "int" 750 | ] 751 | }, 752 | "execution_count": 4, 753 | "metadata": {}, 754 | "output_type": "execute_result" 755 | } 756 | ], 757 | "source": [ 758 | "type(5)" 759 | ] 760 | }, 761 | { 762 | "cell_type": "markdown", 763 | "metadata": {}, 764 | "source": [ 765 | "# Tuesday Exercises - Answers" 766 | ] 767 | }, 768 | { 769 | "cell_type": "markdown", 770 | "metadata": {}, 771 | "source": [ 772 | "

\n", 773 | "1. Variable Output: Store the value 3 in a variable called \"x\" and the value 10 in a variable called \"y\". Save the result of x * y into a separate variabled called \"result\". Finally, output the information so it shows like the following:\n", 774 | "

\n", 775 | "\n", 776 | "

\n", 777 | ">>> 3 + 10 = 13\n", 778 | "

" 779 | ] 780 | }, 781 | { 782 | "cell_type": "code", 783 | "execution_count": 7, 784 | "metadata": {}, 785 | "outputs": [ 786 | { 787 | "name": "stdout", 788 | "output_type": "stream", 789 | "text": [ 790 | "3 * 10 = 30\n" 791 | ] 792 | } 793 | ], 794 | "source": [ 795 | "x = 3\n", 796 | "y = 10\n", 797 | "\n", 798 | "result = x * y\n", 799 | "\n", 800 | "print(x, '*', y, '=', result)" 801 | ] 802 | }, 803 | { 804 | "cell_type": "markdown", 805 | "metadata": {}, 806 | "source": [ 807 | "

\n", 808 | "2. Area Calculation: Calculate the area of a 245.54\" x 13.66\" rectangle. Print out the result. HINT: Area is width multiplied by height.\n", 809 | "

" 810 | ] 811 | }, 812 | { 813 | "cell_type": "code", 814 | "execution_count": 9, 815 | "metadata": {}, 816 | "outputs": [ 817 | { 818 | "name": "stdout", 819 | "output_type": "stream", 820 | "text": [ 821 | "The area is 3354.0764\n" 822 | ] 823 | } 824 | ], 825 | "source": [ 826 | "width = 245.54\n", 827 | "height = 13.66\n", 828 | "\n", 829 | "area = width * height\n", 830 | "\n", 831 | "print('The area is', area)" 832 | ] 833 | }, 834 | { 835 | "cell_type": "markdown", 836 | "metadata": {}, 837 | "source": [ 838 | "# Wednesday Exercises - Answers" 839 | ] 840 | }, 841 | { 842 | "cell_type": "markdown", 843 | "metadata": {}, 844 | "source": [ 845 | "

\n", 846 | "1. Variable Injection: Create a print statement that injects an integer, float, boolean, and string all into one line. The output should look like \"23 4.5 False John\".\n", 847 | "

" 848 | ] 849 | }, 850 | { 851 | "cell_type": "code", 852 | "execution_count": 10, 853 | "metadata": {}, 854 | "outputs": [ 855 | { 856 | "name": "stdout", 857 | "output_type": "stream", 858 | "text": [ 859 | "23 4.5 False John\n" 860 | ] 861 | } 862 | ], 863 | "source": [ 864 | "print(\"{} {} {} {}\".format(23, 4.5, False, \"John\"))" 865 | ] 866 | }, 867 | { 868 | "cell_type": "markdown", 869 | "metadata": {}, 870 | "source": [ 871 | "

\n", 872 | "2. Fill in the Blanks: Using the format method, fill in the blanks below by assinging your name and favorite activities into variables:\n", 873 | "

\n", 874 | "\n", 875 | "

\n", 876 | "\"{}'s favorite sport is {}.\"\n", 877 | "

\n", 878 | "\n", 879 | "

\n", 880 | "\"{} is working on {} programming!\"\n", 881 | "

" 882 | ] 883 | }, 884 | { 885 | "cell_type": "code", 886 | "execution_count": 11, 887 | "metadata": {}, 888 | "outputs": [ 889 | { 890 | "name": "stdout", 891 | "output_type": "stream", 892 | "text": [ 893 | "Connor's favorite sport is Baseball\n", 894 | "Connor is working on Python programming!\n" 895 | ] 896 | } 897 | ], 898 | "source": [ 899 | "print(\"{}'s favorite sport is {}\".format(\"Connor\", \"Baseball\"))\n", 900 | "print(\"{} is working on {} programming!\".format(\"Connor\", \"Python\"))" 901 | ] 902 | }, 903 | { 904 | "cell_type": "markdown", 905 | "metadata": {}, 906 | "source": [ 907 | "# Thursday Exercises - Answers" 908 | ] 909 | }, 910 | { 911 | "cell_type": "markdown", 912 | "metadata": {}, 913 | "source": [ 914 | "

\n", 915 | "1. Uppercasing: Try manipulating the string 'uppercase' so it prints out as all uppercase letters. You'll need to lookup a new method.\n", 916 | "

" 917 | ] 918 | }, 919 | { 920 | "cell_type": "code", 921 | "execution_count": 13, 922 | "metadata": {}, 923 | "outputs": [ 924 | { 925 | "name": "stdout", 926 | "output_type": "stream", 927 | "text": [ 928 | "UPPERCASE\n" 929 | ] 930 | } 931 | ], 932 | "source": [ 933 | "s = 'uppercase'\n", 934 | "\n", 935 | "print(s.upper())" 936 | ] 937 | }, 938 | { 939 | "cell_type": "markdown", 940 | "metadata": {}, 941 | "source": [ 942 | "

\n", 943 | "2. Strip Symbols: Strip all dollar signs from the left side of this string \"$$John Smith\". Try it with .lstrip() and .strip(). To see a description of how to use the strip method further, try using the help function by typing the following:\n", 944 | "

\n", 945 | "\n", 946 | "

\n", 947 | ">>> help(\"\".strip)\n", 948 | "

" 949 | ] 950 | }, 951 | { 952 | "cell_type": "code", 953 | "execution_count": 15, 954 | "metadata": {}, 955 | "outputs": [ 956 | { 957 | "name": "stdout", 958 | "output_type": "stream", 959 | "text": [ 960 | "John Smith\n" 961 | ] 962 | } 963 | ], 964 | "source": [ 965 | "# help(\"\".strip)\n", 966 | "\n", 967 | "s = \"$$John Smith\"\n", 968 | "\n", 969 | "print(s.lstrip('$'))" 970 | ] 971 | }, 972 | { 973 | "cell_type": "markdown", 974 | "metadata": {}, 975 | "source": [ 976 | "# End of Week Exercises - Answers" 977 | ] 978 | }, 979 | { 980 | "cell_type": "markdown", 981 | "metadata": {}, 982 | "source": [ 983 | "

\n", 984 | "1. Side Borders: In the Friday project, we ended up creating borders above and below the information printed out. Try adding a star border on the sides as well now.\n", 985 | "

" 986 | ] 987 | }, 988 | { 989 | "cell_type": "code", 990 | "execution_count": 35, 991 | "metadata": {}, 992 | "outputs": [ 993 | { 994 | "name": "stdout", 995 | "output_type": "stream", 996 | "text": [ 997 | "**************************************************\n", 998 | "*\t\tCoding Temple, Inc.\t\t *\n", 999 | "*\t\t283 Franklin St.\t\t *\n", 1000 | "*\t\tBoston, Ma\t\t\t *\n", 1001 | "*================================================*\n", 1002 | "*\tProduct Name\tProduct Price\t\t *\n", 1003 | "*\tBooks\t\t$49.95\t\t\t *\n", 1004 | "*\tComputer\t$579.99\t\t\t *\n", 1005 | "*\tMonitor\t\t$124.89\t\t\t *\n", 1006 | "*================================================*\n", 1007 | "*\t\t\tTotal\t\t\t *\n", 1008 | "*\t\t\t$754.83\t\t\t *\n", 1009 | "*================================================*\n", 1010 | "*\t\t\t\t\t\t *\n", 1011 | "*\tThanks for shopping with us today!\t *\n", 1012 | "*\t\t\t\t\t\t *\n", 1013 | "**************************************************\n" 1014 | ] 1015 | } 1016 | ], 1017 | "source": [ 1018 | "# create a product and price for three items\n", 1019 | "p1_name, p1_price = 'Books', 49.95\n", 1020 | "p2_name, p2_price = 'Computer', 579.99\n", 1021 | "p3_name, p3_price = 'Monitor', 124.89\n", 1022 | "\n", 1023 | "# create a company name and information\n", 1024 | "company_name = 'coding temple, inc.'\n", 1025 | "company_address = '283 Franklin St.'\n", 1026 | "company_city = 'Boston, MA'\n", 1027 | "\n", 1028 | "# declare ending message\n", 1029 | "message = 'Thanks for shopping with us today!'\n", 1030 | "\n", 1031 | "# create a top border\n", 1032 | "print('*' * 50)\n", 1033 | "\n", 1034 | "# print company information first using format\n", 1035 | "print('*\\t\\t{}\\t\\t *'.format(company_name.title()))\n", 1036 | "print('*\\t\\t{}\\t\\t *'.format(company_address.title()))\n", 1037 | "print('*\\t\\t{}\\t\\t\\t *'.format(company_city.title()))\n", 1038 | "\n", 1039 | "# print a line between sections\n", 1040 | "print('*' + '=' * 48 + '*')\n", 1041 | "\n", 1042 | "# print out header for section of items\n", 1043 | "print('*\\tProduct Name\\tProduct Price\\t\\t *')\n", 1044 | "\n", 1045 | "# create a print statement for each item\n", 1046 | "print('*\\t{}\\t\\t${}\\t\\t\\t *'.format(p1_name.title(), p1_price))\n", 1047 | "print('*\\t{}\\t${}\\t\\t\\t *'.format(p2_name.title(), p2_price))\n", 1048 | "print('*\\t{}\\t\\t${}\\t\\t\\t *'.format(p3_name.title(), p3_price))\n", 1049 | "\n", 1050 | "# print a line between sections\n", 1051 | "print('*' + '=' * 48 + '*')\n", 1052 | "\n", 1053 | "# print out header for section of total\n", 1054 | "print('*\\t\\t\\tTotal\\t\\t\\t *')\n", 1055 | "\n", 1056 | "# calculate total price and print out\n", 1057 | "total = p1_price + p2_price + p3_price\n", 1058 | "print('*\\t\\t\\t${}\\t\\t\\t *'.format(total))\n", 1059 | "\n", 1060 | "# print a line between sections\n", 1061 | "print('*' + '=' * 48 + '*')\n", 1062 | "\n", 1063 | "# output thank you message\n", 1064 | "print('*\\t\\t\\t\\t\\t\\t *\\n*\\t{}\\t *\\n*\\t\\t\\t\\t\\t\\t *'.format(message))\n", 1065 | "\n", 1066 | "# create a bottom border\n", 1067 | "print('*' * 50)" 1068 | ] 1069 | }, 1070 | { 1071 | "cell_type": "markdown", 1072 | "metadata": {}, 1073 | "source": [ 1074 | "

\n", 1075 | "2. Researching Methods: We've gone over a few of the string manipulation methods that are widely used; however, there's many more, try looking up some and implementing them.\n", 1076 | "

" 1077 | ] 1078 | }, 1079 | { 1080 | "cell_type": "markdown", 1081 | "metadata": {}, 1082 | "source": [ 1083 | "

\n", 1084 | "3. Reverse: Declare a variable equal to \"Hello\". Reverse the string using slicing. Try looking it up if you struggle. Tip: You can define a start, stop, and step when slicing.\n", 1085 | "

" 1086 | ] 1087 | }, 1088 | { 1089 | "cell_type": "code", 1090 | "execution_count": 16, 1091 | "metadata": {}, 1092 | "outputs": [ 1093 | { 1094 | "name": "stdout", 1095 | "output_type": "stream", 1096 | "text": [ 1097 | "olleH\n" 1098 | ] 1099 | } 1100 | ], 1101 | "source": [ 1102 | "s = \"Hello\"\n", 1103 | "\n", 1104 | "print(s[::-1])" 1105 | ] 1106 | } 1107 | ], 1108 | "metadata": { 1109 | "kernelspec": { 1110 | "display_name": "Python 3", 1111 | "language": "python", 1112 | "name": "python3" 1113 | }, 1114 | "language_info": { 1115 | "codemirror_mode": { 1116 | "name": "ipython", 1117 | "version": 3 1118 | }, 1119 | "file_extension": ".py", 1120 | "mimetype": "text/x-python", 1121 | "name": "python", 1122 | "nbconvert_exporter": "python", 1123 | "pygments_lexer": "ipython3", 1124 | "version": "3.6.5" 1125 | } 1126 | }, 1127 | "nbformat": 4, 1128 | "nbformat_minor": 2 1129 | } 1130 | -------------------------------------------------------------------------------- /Week_04.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Lists" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "[5, 10, 15.2, 20]\n" 20 | ] 21 | } 22 | ], 23 | "source": [ 24 | "# declaring a list of numbers\n", 25 | "\n", 26 | "nums = [5, 10, 15.2, 20]\n", 27 | "\n", 28 | "print(nums)" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 3, 34 | "metadata": {}, 35 | "outputs": [ 36 | { 37 | "name": "stdout", 38 | "output_type": "stream", 39 | "text": [ 40 | "10\n", 41 | "15.2\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "# accessing elements within a list\n", 47 | "\n", 48 | "print(nums[1]) # will output the value at index 1 = 10\n", 49 | "\n", 50 | "num = nums[2] # saves index value 2 into num\n", 51 | "\n", 52 | "print(num) # prints value assigned to num" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 5, 58 | "metadata": {}, 59 | "outputs": [ 60 | { 61 | "name": "stdout", 62 | "output_type": "stream", 63 | "text": [ 64 | "[4.3, 'word', True]\n" 65 | ] 66 | } 67 | ], 68 | "source": [ 69 | "# declaring a list of mixed data types\n", 70 | "\n", 71 | "num = 4.3\n", 72 | "\n", 73 | "data = [num, 'word', True] # the power of data collection\n", 74 | "\n", 75 | "print(data)" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 6, 81 | "metadata": {}, 82 | "outputs": [ 83 | { 84 | "name": "stdout", 85 | "output_type": "stream", 86 | "text": [ 87 | "[5, 'book', [34, 'hello'], True]\n", 88 | "[34, 'hello']\n" 89 | ] 90 | } 91 | ], 92 | "source": [ 93 | "# understanding lists within lists\n", 94 | "\n", 95 | "data = [5, 'book', [34, 'hello'], True] # lists can hold any type\n", 96 | "\n", 97 | "print(data)\n", 98 | "\n", 99 | "print(data[2])" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 7, 105 | "metadata": {}, 106 | "outputs": [ 107 | { 108 | "name": "stdout", 109 | "output_type": "stream", 110 | "text": [ 111 | "34\n", 112 | "hello\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "# using double bracket notation to access lists within lists\n", 118 | "\n", 119 | "print(data[2][0]) # will output 34\n", 120 | "\n", 121 | "inner_list = data[2] # inner list will equal [34, 'hello']\n", 122 | "\n", 123 | "print(inner_list[1]) # will output 'hello'" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 8, 129 | "metadata": {}, 130 | "outputs": [ 131 | { 132 | "name": "stdout", 133 | "output_type": "stream", 134 | "text": [ 135 | "[5, 10, 15, 20]\n", 136 | "[100, 10, 15, 20]\n" 137 | ] 138 | } 139 | ], 140 | "source": [ 141 | "# changing values in a list through index\n", 142 | "\n", 143 | "data = [5, 10, 15, 20]\n", 144 | "\n", 145 | "print(data)\n", 146 | "\n", 147 | "data[0] = 100 # change the value at index 0 - (5 to 100)\n", 148 | "\n", 149 | "print(data)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": 9, 155 | "metadata": {}, 156 | "outputs": [ 157 | { 158 | "name": "stdout", 159 | "output_type": "stream", 160 | "text": [ 161 | "a: [5, 10]\t b: [5, 10]\n", 162 | "Location a[0]: 1977642176\t Location b[0]: 1977642176\n", 163 | "a: [20, 10]\t b: [20, 10]\n" 164 | ] 165 | } 166 | ], 167 | "source": [ 168 | "# understanding how lists are stored\n", 169 | "\n", 170 | "a = [5, 10]\n", 171 | "\n", 172 | "b = a\n", 173 | "\n", 174 | "print('a: {}\\t b: {}'.format(a, b))\n", 175 | "\n", 176 | "print('Location a[0]: {}\\t Location b[0]: {}'.format(id(a[0]), id(b[0])))\n", 177 | "\n", 178 | "a[0] = 20 # re-declaring the value of a[0] also changes b[0]\n", 179 | "\n", 180 | "print('a: {}\\t b: {}'.format(a, b))" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": 10, 186 | "metadata": {}, 187 | "outputs": [ 188 | { 189 | "name": "stdout", 190 | "output_type": "stream", 191 | "text": [ 192 | "data: [50, 10, 15, 20]\t data_copy: [5, 10, 15, 20]\n" 193 | ] 194 | } 195 | ], 196 | "source": [ 197 | "# using [:] to copy a list\n", 198 | "\n", 199 | "data = [5, 10, 15, 20]\n", 200 | "\n", 201 | "data_copy = data[:] # a single colon copies the list\n", 202 | "\n", 203 | "data[0] = 50\n", 204 | "\n", 205 | "print('data: {}\\t data_copy: {}'.format(data, data_copy))" 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "metadata": {}, 211 | "source": [ 212 | "# For Loops" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": 1, 218 | "metadata": {}, 219 | "outputs": [ 220 | { 221 | "name": "stdout", 222 | "output_type": "stream", 223 | "text": [ 224 | "Value: 0\n", 225 | "Value: 1\n", 226 | "Value: 2\n", 227 | "Value: 3\n", 228 | "Value: 4\n" 229 | ] 230 | } 231 | ], 232 | "source": [ 233 | "# writing your first for loop using range\n", 234 | "\n", 235 | "for num in range(5):\n", 236 | " print('Value: {}'.format(num))" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": 2, 242 | "metadata": {}, 243 | "outputs": [ 244 | { 245 | "name": "stdout", 246 | "output_type": "stream", 247 | "text": [ 248 | "Value: 2\n", 249 | "Value: 4\n", 250 | "Value: 6\n", 251 | "Value: 8\n" 252 | ] 253 | } 254 | ], 255 | "source": [ 256 | "# providing the start, stop, and step for the range function\n", 257 | "\n", 258 | "for num in range(2, 10, 2):\n", 259 | " print('Value: {}'.format(num)) # will print all evens between 2 and 10" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": 3, 265 | "metadata": {}, 266 | "outputs": [ 267 | { 268 | "name": "stdout", 269 | "output_type": "stream", 270 | "text": [ 271 | "Value: J\n", 272 | "Value: o\n", 273 | "Value: h\n", 274 | "Value: n\n", 275 | "Value: \n", 276 | "Value: S\n", 277 | "Value: m\n", 278 | "Value: i\n", 279 | "Value: t\n", 280 | "Value: h\n" 281 | ] 282 | } 283 | ], 284 | "source": [ 285 | "# printing all characters in a name using the 'in' keyword\n", 286 | "\n", 287 | "name = 'John Smith'\n", 288 | "\n", 289 | "for letter in name:\n", 290 | " print('Value: {}'.format(letter))" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": 4, 296 | "metadata": {}, 297 | "outputs": [ 298 | { 299 | "name": "stdout", 300 | "output_type": "stream", 301 | "text": [ 302 | "0\n", 303 | "1\n", 304 | "2\n", 305 | "4\n" 306 | ] 307 | } 308 | ], 309 | "source": [ 310 | "# using the continue statement within a for loop\n", 311 | "\n", 312 | "for num in range(5):\n", 313 | " if num == 3:\n", 314 | " continue\n", 315 | " print(num)" 316 | ] 317 | }, 318 | { 319 | "cell_type": "code", 320 | "execution_count": 5, 321 | "metadata": {}, 322 | "outputs": [ 323 | { 324 | "name": "stdout", 325 | "output_type": "stream", 326 | "text": [ 327 | "0\n", 328 | "1\n", 329 | "2\n" 330 | ] 331 | } 332 | ], 333 | "source": [ 334 | "# breaking out of a loop using the 'break' keyword\n", 335 | "\n", 336 | "for num in range(5):\n", 337 | " if num == 3:\n", 338 | " break\n", 339 | " print(num)" 340 | ] 341 | }, 342 | { 343 | "cell_type": "code", 344 | "execution_count": 6, 345 | "metadata": { 346 | "collapsed": true 347 | }, 348 | "outputs": [], 349 | "source": [ 350 | "# setting a placeholder using the 'pass' keyword\n", 351 | "\n", 352 | "for i in range(5):\n", 353 | " # TODO: add code to print number\n", 354 | " pass" 355 | ] 356 | }, 357 | { 358 | "cell_type": "markdown", 359 | "metadata": {}, 360 | "source": [ 361 | "# While Loops" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": 7, 367 | "metadata": {}, 368 | "outputs": [ 369 | { 370 | "name": "stdout", 371 | "output_type": "stream", 372 | "text": [ 373 | "10\n", 374 | "9\n", 375 | "8\n", 376 | "7\n", 377 | "6\n", 378 | "5\n", 379 | "4\n", 380 | "3\n", 381 | "2\n", 382 | "1\n" 383 | ] 384 | } 385 | ], 386 | "source": [ 387 | "# writing your first while loop\n", 388 | "\n", 389 | "health = 10\n", 390 | "\n", 391 | "while health > 0:\n", 392 | " print(health)\n", 393 | " health -= 1 # forgetting this line will result in infinite loop" 394 | ] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "execution_count": 8, 399 | "metadata": {}, 400 | "outputs": [ 401 | { 402 | "name": "stdout", 403 | "output_type": "stream", 404 | "text": [ 405 | "0 0\n", 406 | "0 1\n", 407 | "0 2\n", 408 | "1 0\n", 409 | "1 1\n", 410 | "1 2\n" 411 | ] 412 | } 413 | ], 414 | "source": [ 415 | "# using two or more loops together is called a nested loop\n", 416 | "\n", 417 | "for i in range(2): # outside loop\n", 418 | " for j in range(3): # inside loop\n", 419 | " print(i, j)" 420 | ] 421 | }, 422 | { 423 | "cell_type": "markdown", 424 | "metadata": {}, 425 | "source": [ 426 | "# Working with Lists" 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": 9, 432 | "metadata": {}, 433 | "outputs": [ 434 | { 435 | "name": "stdout", 436 | "output_type": "stream", 437 | "text": [ 438 | "3\n" 439 | ] 440 | } 441 | ], 442 | "source": [ 443 | "# checking the number of items within a list\n", 444 | "\n", 445 | "nums = [5, 10, 15]\n", 446 | "\n", 447 | "length = len(nums) # len() returns an integer\n", 448 | "\n", 449 | "print(length)" 450 | ] 451 | }, 452 | { 453 | "cell_type": "code", 454 | "execution_count": 11, 455 | "metadata": {}, 456 | "outputs": [ 457 | { 458 | "name": "stdout", 459 | "output_type": "stream", 460 | "text": [ 461 | "[10, 15]\n", 462 | "[5, 10]\n", 463 | "[5, 15]\n", 464 | "[10, 15]\n" 465 | ] 466 | } 467 | ], 468 | "source": [ 469 | "# accessing specific items of a list with slices\n", 470 | "\n", 471 | "print(nums[1:3]) # will output items in index 1 and 2\n", 472 | "\n", 473 | "print(nums[:2]) # will output items in index 0 and 1\n", 474 | "\n", 475 | "print(nums[::2]) # will print every other index - 0, 2, 4, etc.\n", 476 | "\n", 477 | "print(nums[-2:]) # will output the last two items in list" 478 | ] 479 | }, 480 | { 481 | "cell_type": "code", 482 | "execution_count": 12, 483 | "metadata": {}, 484 | "outputs": [ 485 | { 486 | "name": "stdout", 487 | "output_type": "stream", 488 | "text": [ 489 | "[10, 20, 5]\n" 490 | ] 491 | } 492 | ], 493 | "source": [ 494 | "# adding an item to the back of a list using append\n", 495 | "\n", 496 | "nums = [10, 20]\n", 497 | "\n", 498 | "nums.append(5)\n", 499 | "\n", 500 | "print(nums) # outputs [10, 20, 5]" 501 | ] 502 | }, 503 | { 504 | "cell_type": "code", 505 | "execution_count": 13, 506 | "metadata": { 507 | "collapsed": true 508 | }, 509 | "outputs": [], 510 | "source": [ 511 | "# adding a value to the beginning of the list\n", 512 | "\n", 513 | "words = ['ball', 'base']\n", 514 | "\n", 515 | "nums.insert(0, 'glove') # first number is the index, second is the value" 516 | ] 517 | }, 518 | { 519 | "cell_type": "code", 520 | "execution_count": 14, 521 | "metadata": {}, 522 | "outputs": [ 523 | { 524 | "name": "stdout", 525 | "output_type": "stream", 526 | "text": [ 527 | "5 \n", 528 | " ['ball']\n" 529 | ] 530 | } 531 | ], 532 | "source": [ 533 | "# using pop to remove items and saving to a variable to use later\n", 534 | "\n", 535 | "items = [5, 'ball', True]\n", 536 | "\n", 537 | "items.pop() # by default removes the last item\n", 538 | "\n", 539 | "removed_item = items.pop(0) # removes 5 and saves it into the variable\n", 540 | "\n", 541 | "print(removed_item, '\\n', items)" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": 15, 547 | "metadata": {}, 548 | "outputs": [ 549 | { 550 | "name": "stdout", 551 | "output_type": "stream", 552 | "text": [ 553 | "['baseball', 'football', 'hockey']\n" 554 | ] 555 | } 556 | ], 557 | "source": [ 558 | "# using the remove method with a try and except\n", 559 | "\n", 560 | "sports = ['baseball', 'soccer', 'football', 'hockey']\n", 561 | "\n", 562 | "try:\n", 563 | " sports.remove('soccer')\n", 564 | "except:\n", 565 | " print('That item does not exist in the list.')\n", 566 | " \n", 567 | "print(sports)" 568 | ] 569 | }, 570 | { 571 | "cell_type": "code", 572 | "execution_count": 16, 573 | "metadata": {}, 574 | "outputs": [ 575 | { 576 | "name": "stdout", 577 | "output_type": "stream", 578 | "text": [ 579 | "3\n", 580 | "9\n", 581 | "17\n" 582 | ] 583 | } 584 | ], 585 | "source": [ 586 | "# using min, max, and sum\n", 587 | "\n", 588 | "nums = [5, 3, 9]\n", 589 | "\n", 590 | "print(min(nums)) # will find the lowest number in the list\n", 591 | "print(max(nums)) # will find the highest number in the list\n", 592 | "print(sum(nums)) # will add all numbers in the list and return the sum" 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": 17, 598 | "metadata": {}, 599 | "outputs": [ 600 | { 601 | "name": "stdout", 602 | "output_type": "stream", 603 | "text": [ 604 | "[5, 8, 0, 2] [0, 2, 5, 8]\n" 605 | ] 606 | } 607 | ], 608 | "source": [ 609 | "# using sorted on lists for numerical and alphabetical data\n", 610 | "\n", 611 | "nums = [5, 8, 0, 2]\n", 612 | "\n", 613 | "sorted_nums = sorted(nums) # save to a new variable to use later\n", 614 | "\n", 615 | "print(nums, sorted_nums) # the original list is in tact" 616 | ] 617 | }, 618 | { 619 | "cell_type": "code", 620 | "execution_count": 18, 621 | "metadata": {}, 622 | "outputs": [ 623 | { 624 | "name": "stdout", 625 | "output_type": "stream", 626 | "text": [ 627 | "[0, 3, 5, 8]\n" 628 | ] 629 | } 630 | ], 631 | "source": [ 632 | "# sorting a list with .sort() in-place\n", 633 | "\n", 634 | "nums = [5, 0, 8, 3]\n", 635 | "\n", 636 | "nums.sort() # alters the original variable directly\n", 637 | "\n", 638 | "print(nums)" 639 | ] 640 | }, 641 | { 642 | "cell_type": "code", 643 | "execution_count": 19, 644 | "metadata": {}, 645 | "outputs": [ 646 | { 647 | "name": "stdout", 648 | "output_type": "stream", 649 | "text": [ 650 | "found\n", 651 | "not found\n" 652 | ] 653 | } 654 | ], 655 | "source": [ 656 | "# using conditional statements on a list\n", 657 | "\n", 658 | "names = ['Jack', 'Robert', 'Mary']\n", 659 | "\n", 660 | "if 'Mary' in names:\n", 661 | " print('found') # will run since Mary is in the list\n", 662 | " \n", 663 | "if 'Jimmy' not in names:\n", 664 | " print('not found') # will run since Jimmy is not in the list" 665 | ] 666 | }, 667 | { 668 | "cell_type": "code", 669 | "execution_count": 20, 670 | "metadata": {}, 671 | "outputs": [ 672 | { 673 | "name": "stdout", 674 | "output_type": "stream", 675 | "text": [ 676 | "empty\n" 677 | ] 678 | } 679 | ], 680 | "source": [ 681 | "# using conditionals to see if a list is empty\n", 682 | "\n", 683 | "nums = []\n", 684 | "\n", 685 | "if not nums: # could also say 'if nums == []'\n", 686 | " print('empty')" 687 | ] 688 | }, 689 | { 690 | "cell_type": "code", 691 | "execution_count": 21, 692 | "metadata": {}, 693 | "outputs": [ 694 | { 695 | "name": "stdout", 696 | "output_type": "stream", 697 | "text": [ 698 | "Baseball\n", 699 | "Hockey\n", 700 | "Football\n", 701 | "Basketball\n" 702 | ] 703 | } 704 | ], 705 | "source": [ 706 | "# using a for loop to print all items in a list\n", 707 | "\n", 708 | "sports = ['Baseball', 'Hockey', 'Football', 'Basketball']\n", 709 | "\n", 710 | "for sport in sports:\n", 711 | " print(sport)" 712 | ] 713 | }, 714 | { 715 | "cell_type": "code", 716 | "execution_count": 22, 717 | "metadata": {}, 718 | "outputs": [ 719 | { 720 | "name": "stdout", 721 | "output_type": "stream", 722 | "text": [ 723 | "['Jack', 'Rob', 'Robert']\n" 724 | ] 725 | } 726 | ], 727 | "source": [ 728 | "# using the while loop to remove a certain value\n", 729 | "\n", 730 | "names = ['Bob', 'Jack', 'Rob', 'Bob', 'Robert']\n", 731 | "\n", 732 | "while 'Bob' in names:\n", 733 | " names.remove('Bob') # removes all instances of 'Bob'\n", 734 | " \n", 735 | "print(names)" 736 | ] 737 | }, 738 | { 739 | "cell_type": "markdown", 740 | "metadata": {}, 741 | "source": [ 742 | "# Friday Project: Creating Hangman" 743 | ] 744 | }, 745 | { 746 | "cell_type": "code", 747 | "execution_count": 25, 748 | "metadata": {}, 749 | "outputs": [ 750 | { 751 | "name": "stdout", 752 | "output_type": "stream", 753 | "text": [ 754 | "Thanks for playing.\n" 755 | ] 756 | } 757 | ], 758 | "source": [ 759 | "# import additional functions\n", 760 | "from random import choice\n", 761 | "from IPython.display import clear_output\n", 762 | "\n", 763 | "# declare game variables\n", 764 | "words = ['tree', 'basket', 'chair', 'paper', 'python']\n", 765 | "word = choice(words)\n", 766 | "guessed, lives, game_over = [], 7, False\n", 767 | "\n", 768 | "# create a list of underscores to the length of the word\n", 769 | "guesses = ['_ '] * len(word)\n", 770 | "\n", 771 | "# create main game loop\n", 772 | "while not game_over:\n", 773 | " # output game information\n", 774 | " hidden_word = ''.join(guesses)\n", 775 | " print('Your guessed letters: {}'.format(guessed))\n", 776 | " print('Word to guess: {}'.format(hidden_word))\n", 777 | " print('Lives: {}'.format(lives))\n", 778 | " \n", 779 | " ans = input('Type quit or guess a letter: ').lower()\n", 780 | " \n", 781 | " clear_output() # clear all previous output\n", 782 | " \n", 783 | " if ans == 'quit':\n", 784 | " print('Thanks for playing.')\n", 785 | " game_over = True\n", 786 | " elif ans in word and ans not in guessed:\n", 787 | " print('You guessed correctly!')\n", 788 | " \n", 789 | " # create a loop to change underscore to proper letter\n", 790 | " for i in range(len(word)):\n", 791 | " if word[i] == ans:\n", 792 | " guesses[i] = ans\n", 793 | " elif ans in guessed:\n", 794 | " print('You already guessed that. Try again.')\n", 795 | " else: # otherwise lose life\n", 796 | " lives -= 1\n", 797 | " print('Incorrect, you lost a life.')\n", 798 | " \n", 799 | " if ans not in guessed:\n", 800 | " guessed.append(ans) # add guess to guessed list\n", 801 | " \n", 802 | " if lives <= 0:\n", 803 | " print('You lost all your lives, you lost!')\n", 804 | " game_over = True\n", 805 | " elif word == ''.join(guesses):\n", 806 | " print('Congratulations, you guessed it correctly!')\n", 807 | " game_over = True" 808 | ] 809 | }, 810 | { 811 | "cell_type": "markdown", 812 | "metadata": {}, 813 | "source": [ 814 | "# Monday Exercises - Answers" 815 | ] 816 | }, 817 | { 818 | "cell_type": "markdown", 819 | "metadata": {}, 820 | "source": [ 821 | "

\n", 822 | "1. Sports: Define a list of strings, where each string is a sport. Then output each sport with the following line \"I like to play {}\"...\n", 823 | "

" 824 | ] 825 | }, 826 | { 827 | "cell_type": "code", 828 | "execution_count": 1, 829 | "metadata": {}, 830 | "outputs": [ 831 | { 832 | "name": "stdout", 833 | "output_type": "stream", 834 | "text": [ 835 | "I like to play baseball.\n", 836 | "I like to play soccer.\n", 837 | "I like to play football.\n" 838 | ] 839 | } 840 | ], 841 | "source": [ 842 | "sports = [ \"baseball\", 'soccer', 'football']\n", 843 | "\n", 844 | "print(\"I like to play {}.\".format(sports[0]))\n", 845 | "print(\"I like to play {}.\".format(sports[1]))\n", 846 | "print(\"I like to play {}.\".format(sports[2]))" 847 | ] 848 | }, 849 | { 850 | "cell_type": "markdown", 851 | "metadata": {}, 852 | "source": [ 853 | "

\n", 854 | "2. First Character: For the following list, print out each item's first letter. (output should be 'J', 'A', 'S', 'K')\n", 855 | "

\n", 856 | "

     names = ['John', 'Abraham', 'Sam', 'Kelly']

" 857 | ] 858 | }, 859 | { 860 | "cell_type": "code", 861 | "execution_count": 4, 862 | "metadata": {}, 863 | "outputs": [ 864 | { 865 | "name": "stdout", 866 | "output_type": "stream", 867 | "text": [ 868 | "J\n", 869 | "A\n", 870 | "S\n", 871 | "K\n" 872 | ] 873 | } 874 | ], 875 | "source": [ 876 | "names = [ 'John', 'Abraham', 'Sam', 'Kelly' ]\n", 877 | "\n", 878 | "print(names[0][0])\n", 879 | "print(names[1][0])\n", 880 | "print(names[2][0])\n", 881 | "print(names[3][0])" 882 | ] 883 | }, 884 | { 885 | "cell_type": "markdown", 886 | "metadata": {}, 887 | "source": [ 888 | "# Tuesday Exercises - Answers" 889 | ] 890 | }, 891 | { 892 | "cell_type": "markdown", 893 | "metadata": {}, 894 | "source": [ 895 | "

\n", 896 | "1. Divisble by Three: Write a for loop that prints out all numbers from 1 to 100 that are divisble by three.\n", 897 | "

" 898 | ] 899 | }, 900 | { 901 | "cell_type": "code", 902 | "execution_count": 6, 903 | "metadata": {}, 904 | "outputs": [ 905 | { 906 | "name": "stdout", 907 | "output_type": "stream", 908 | "text": [ 909 | "3\n", 910 | "6\n", 911 | "9\n", 912 | "12\n", 913 | "15\n", 914 | "18\n", 915 | "21\n", 916 | "24\n", 917 | "27\n", 918 | "30\n", 919 | "33\n", 920 | "36\n", 921 | "39\n", 922 | "42\n", 923 | "45\n", 924 | "48\n", 925 | "51\n", 926 | "54\n", 927 | "57\n", 928 | "60\n", 929 | "63\n", 930 | "66\n", 931 | "69\n", 932 | "72\n", 933 | "75\n", 934 | "78\n", 935 | "81\n", 936 | "84\n", 937 | "87\n", 938 | "90\n", 939 | "93\n", 940 | "96\n", 941 | "99\n" 942 | ] 943 | } 944 | ], 945 | "source": [ 946 | "for i in range(1, 100):\n", 947 | " if i % 3 == 0:\n", 948 | " print(i)" 949 | ] 950 | }, 951 | { 952 | "cell_type": "markdown", 953 | "metadata": {}, 954 | "source": [ 955 | "

\n", 956 | "2. Only Vowels: Ask for user input and write a for loop that will output all the vowels within it. For example:\n", 957 | "

\n", 958 | "\n", 959 | "

\n", 960 | ">>> \"Hello\" --> \"eo\"\n", 961 | "

" 962 | ] 963 | }, 964 | { 965 | "cell_type": "code", 966 | "execution_count": 7, 967 | "metadata": {}, 968 | "outputs": [ 969 | { 970 | "name": "stdout", 971 | "output_type": "stream", 972 | "text": [ 973 | "Enter a word: Hello\n", 974 | "e\n", 975 | "o\n" 976 | ] 977 | } 978 | ], 979 | "source": [ 980 | "ans = input(\"Enter a word: \")\n", 981 | "\n", 982 | "for letter in ans:\n", 983 | " if letter in ['a', 'e', 'i', 'o', 'u']:\n", 984 | " print(letter)" 985 | ] 986 | }, 987 | { 988 | "cell_type": "markdown", 989 | "metadata": {}, 990 | "source": [ 991 | "# Wednesday Exercises - Answers" 992 | ] 993 | }, 994 | { 995 | "cell_type": "markdown", 996 | "metadata": {}, 997 | "source": [ 998 | "

\n", 999 | "1. User Input: Write a while loop that continues to ask for user input and runs until they type 'quit'.\n", 1000 | "

" 1001 | ] 1002 | }, 1003 | { 1004 | "cell_type": "code", 1005 | "execution_count": 9, 1006 | "metadata": {}, 1007 | "outputs": [ 1008 | { 1009 | "name": "stdout", 1010 | "output_type": "stream", 1011 | "text": [ 1012 | "Enter something: asd\n", 1013 | "Enter something: asdf\n", 1014 | "Enter something: adsf\n", 1015 | "Enter something: quit\n" 1016 | ] 1017 | } 1018 | ], 1019 | "source": [ 1020 | "while input('Enter something: ').lower() != 'quit':\n", 1021 | " pass" 1022 | ] 1023 | }, 1024 | { 1025 | "cell_type": "markdown", 1026 | "metadata": {}, 1027 | "source": [ 1028 | "

\n", 1029 | "2. Double Loop: Write a for loop within a while loop that will count from 0 to 5, but when it reaches 3 it sets a game_over variable to True and breaks out of the loop. The while loop should continue to loop until game_over is True. The output should only be 0, 1, 2.\n", 1030 | "

" 1031 | ] 1032 | }, 1033 | { 1034 | "cell_type": "code", 1035 | "execution_count": 10, 1036 | "metadata": {}, 1037 | "outputs": [ 1038 | { 1039 | "name": "stdout", 1040 | "output_type": "stream", 1041 | "text": [ 1042 | "0\n", 1043 | "1\n", 1044 | "2\n" 1045 | ] 1046 | } 1047 | ], 1048 | "source": [ 1049 | "game_over = False\n", 1050 | "\n", 1051 | "while game_over == False:\n", 1052 | " for i in range(5):\n", 1053 | " if i == 3:\n", 1054 | " game_over = True\n", 1055 | " break\n", 1056 | " else:\n", 1057 | " print(i)" 1058 | ] 1059 | }, 1060 | { 1061 | "cell_type": "markdown", 1062 | "metadata": {}, 1063 | "source": [ 1064 | "# Thursday Exercises - Answers" 1065 | ] 1066 | }, 1067 | { 1068 | "cell_type": "markdown", 1069 | "metadata": {}, 1070 | "source": [ 1071 | "

\n", 1072 | "1. Remove Duplicates: Remove all duplicates from the list below. Hint: Use the .count() method. The output should be [\"Bob\", \"Kenny\", \"Amanda\"]\n", 1073 | "

\n", 1074 | "\n", 1075 | "

\n", 1076 | ">>> names = [\"Bob\", \"Kenny\", \"Amanda\", \"Bob\", \"Kenny\"]\n", 1077 | "

" 1078 | ] 1079 | }, 1080 | { 1081 | "cell_type": "code", 1082 | "execution_count": 12, 1083 | "metadata": {}, 1084 | "outputs": [ 1085 | { 1086 | "name": "stdout", 1087 | "output_type": "stream", 1088 | "text": [ 1089 | "['Amanda', 'Bob', 'Kenny']\n" 1090 | ] 1091 | } 1092 | ], 1093 | "source": [ 1094 | "names = [\"Bob\", \"Kenny\", \"Amanda\", \"Bob\", \"Kenny\"]\n", 1095 | "\n", 1096 | "for name in names:\n", 1097 | " while names.count(name) > 1:\n", 1098 | " names.remove(name)\n", 1099 | " \n", 1100 | "print(names)" 1101 | ] 1102 | }, 1103 | { 1104 | "cell_type": "markdown", 1105 | "metadata": {}, 1106 | "source": [ 1107 | "

\n", 1108 | "2. User Input: Use a while loop to continually ask the user to input a word, until they type 'quit'. Once they type a word in, add it to a list. Once they quit the loop, use a for loop to output all items within the list.\n", 1109 | "

" 1110 | ] 1111 | }, 1112 | { 1113 | "cell_type": "code", 1114 | "execution_count": 13, 1115 | "metadata": {}, 1116 | "outputs": [ 1117 | { 1118 | "name": "stdout", 1119 | "output_type": "stream", 1120 | "text": [ 1121 | "Enter a word: hello\n", 1122 | "Enter a word: yes\n", 1123 | "Enter a word: quit\n", 1124 | "hello\n", 1125 | "yes\n" 1126 | ] 1127 | } 1128 | ], 1129 | "source": [ 1130 | "done = False\n", 1131 | "words = []\n", 1132 | "\n", 1133 | "while done == False:\n", 1134 | " ans = input('Enter a word: ')\n", 1135 | " \n", 1136 | " if ans.lower() == 'quit':\n", 1137 | " done = True\n", 1138 | " else:\n", 1139 | " words.append(ans)\n", 1140 | " \n", 1141 | "for word in words:\n", 1142 | " print(word)" 1143 | ] 1144 | }, 1145 | { 1146 | "cell_type": "markdown", 1147 | "metadata": {}, 1148 | "source": [ 1149 | "# End of Week Exercises - Answers" 1150 | ] 1151 | }, 1152 | { 1153 | "cell_type": "markdown", 1154 | "metadata": {}, 1155 | "source": [ 1156 | "

\n", 1157 | "1. Pyramids: Use a for loop to build a pyramid of x's. It should be modular so that if you loop to 5 or 50, it still creates evenly spaced rows. Hint: Multiply the string 'x' by the row. For example, if you loop to the range of 4, it should produce the following result:\n", 1158 | "

\n", 1159 | "\n", 1160 | "

\n", 1161 | ">>>     x
\n", 1162 | ">>>    x x
\n", 1163 | ">>>   x x x\n", 1164 | "

" 1165 | ] 1166 | }, 1167 | { 1168 | "cell_type": "code", 1169 | "execution_count": 15, 1170 | "metadata": {}, 1171 | "outputs": [ 1172 | { 1173 | "name": "stdout", 1174 | "output_type": "stream", 1175 | "text": [ 1176 | " \n", 1177 | " x\n", 1178 | " x x\n", 1179 | " x x x\n", 1180 | " x x x x\n" 1181 | ] 1182 | } 1183 | ], 1184 | "source": [ 1185 | "row = 5\n", 1186 | "\n", 1187 | "for i in range(row):\n", 1188 | " print(' ' * (row - i) + ' x' * i)" 1189 | ] 1190 | }, 1191 | { 1192 | "cell_type": "markdown", 1193 | "metadata": {}, 1194 | "source": [ 1195 | "

\n", 1196 | "2. Output Names: Write a loop that will iterate over a list of items and only output items which have letters inside of a string. Take the following list for example, only \"John\" and \"Amanda\" should be output:\n", 1197 | "

\n", 1198 | "\n", 1199 | "

\n", 1200 | ">>> names = [ \"John\", \" \", \"Amanda\", 5]\n", 1201 | "

" 1202 | ] 1203 | }, 1204 | { 1205 | "cell_type": "code", 1206 | "execution_count": 18, 1207 | "metadata": {}, 1208 | "outputs": [ 1209 | { 1210 | "name": "stdout", 1211 | "output_type": "stream", 1212 | "text": [ 1213 | "John\n", 1214 | "Amanda\n" 1215 | ] 1216 | } 1217 | ], 1218 | "source": [ 1219 | "names = [ \"John\", \" \", \"Amanda\", 5]\n", 1220 | "\n", 1221 | "for name in names:\n", 1222 | " if type(name) == str:\n", 1223 | " if name.strip() != '':\n", 1224 | " print(name)" 1225 | ] 1226 | }, 1227 | { 1228 | "cell_type": "markdown", 1229 | "metadata": {}, 1230 | "source": [ 1231 | "

\n", 1232 | "3. Convert Celsius: Given a list of temperatures that are in Celsius, write a loop that iterates over the list and outputs the temperature converted into Fahrenheit. Hint: The conversion is \"F = (9/5) * C + 32\".\n", 1233 | "

\n", 1234 | "\n", 1235 | "

\n", 1236 | ">>> temps = [32, 12, 44, 29]
\n", 1237 | "Output would be [89.6, 53.6, 111.2, 84.2]\n", 1238 | "

" 1239 | ] 1240 | }, 1241 | { 1242 | "cell_type": "code", 1243 | "execution_count": 19, 1244 | "metadata": {}, 1245 | "outputs": [ 1246 | { 1247 | "name": "stdout", 1248 | "output_type": "stream", 1249 | "text": [ 1250 | "[89.6, 53.6, 111.2, 84.2]\n" 1251 | ] 1252 | } 1253 | ], 1254 | "source": [ 1255 | "temps = [32, 12, 44, 29]\n", 1256 | "\n", 1257 | "for i in range(len(temps)):\n", 1258 | " temps[i] = (9/5) * temps[i] + 32\n", 1259 | " \n", 1260 | "print(temps)" 1261 | ] 1262 | } 1263 | ], 1264 | "metadata": { 1265 | "kernelspec": { 1266 | "display_name": "Python 3", 1267 | "language": "python", 1268 | "name": "python3" 1269 | }, 1270 | "language_info": { 1271 | "codemirror_mode": { 1272 | "name": "ipython", 1273 | "version": 3 1274 | }, 1275 | "file_extension": ".py", 1276 | "mimetype": "text/x-python", 1277 | "name": "python", 1278 | "nbconvert_exporter": "python", 1279 | "pygments_lexer": "ipython3", 1280 | "version": "3.6.5" 1281 | } 1282 | }, 1283 | "nbformat": 4, 1284 | "nbformat_minor": 2 1285 | } 1286 | -------------------------------------------------------------------------------- /Week_08.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# List Comprehension" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 3, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]\n" 20 | ] 21 | } 22 | ], 23 | "source": [ 24 | "# create a list of ten numbers using list comprehension\n", 25 | "\n", 26 | "nums = [ x for x in range(100) ] # generates a list from 0 up to 100\n", 27 | "\n", 28 | "print(nums)" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 4, 34 | "metadata": {}, 35 | "outputs": [ 36 | { 37 | "name": "stdout", 38 | "output_type": "stream", 39 | "text": [ 40 | "[0, 2, 4, 6, 8]\n" 41 | ] 42 | } 43 | ], 44 | "source": [ 45 | "# using if statements within list comprehension\n", 46 | "\n", 47 | "nums = [ x for x in range(10) if x % 2 == 0 ] # generates a list of even numbers up to 10\n", 48 | "\n", 49 | "print(nums)" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 5, 55 | "metadata": {}, 56 | "outputs": [ 57 | { 58 | "name": "stdout", 59 | "output_type": "stream", 60 | "text": [ 61 | "['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']\n" 62 | ] 63 | } 64 | ], 65 | "source": [ 66 | "# using if/else statements within list comprehension\n", 67 | "\n", 68 | "nums = [ \"Even\" if x % 2 == 0 else \"Odd\" for x in range(10) ] # generates a list of even/odd strings\n", 69 | "\n", 70 | "print(nums)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 6, 76 | "metadata": {}, 77 | "outputs": [ 78 | { 79 | "name": "stdout", 80 | "output_type": "stream", 81 | "text": [ 82 | "[2, 4, 6, 8]\n" 83 | ] 84 | } 85 | ], 86 | "source": [ 87 | "# creating a list of squared numbers from another list of numbers using list comprehension\n", 88 | "\n", 89 | "nums = [2, 4, 6, 8]\n", 90 | "\n", 91 | "squared_nums = [ num**2 for num in nums ] # creates a new list of squared numbers based on nums\n", 92 | "\n", 93 | "print(nums)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 7, 99 | "metadata": {}, 100 | "outputs": [ 101 | { 102 | "name": "stdout", 103 | "output_type": "stream", 104 | "text": [ 105 | "{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}\n" 106 | ] 107 | } 108 | ], 109 | "source": [ 110 | "# creating a dictionary of even numbers and square values using comprehension\n", 111 | "\n", 112 | "numbers = [ x for x in range(10) ]\n", 113 | "\n", 114 | "squares = { num : num**2 for num in numbers if num % 2 == 0 }\n", 115 | "\n", 116 | "print(squares)" 117 | ] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "metadata": {}, 122 | "source": [ 123 | "# Lambda Functions" 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": 9, 129 | "metadata": {}, 130 | "outputs": [ 131 | { 132 | "data": { 133 | "text/plain": [ 134 | "16" 135 | ] 136 | }, 137 | "execution_count": 9, 138 | "metadata": {}, 139 | "output_type": "execute_result" 140 | } 141 | ], 142 | "source": [ 143 | "# using a lambda to square a number\n", 144 | "\n", 145 | "( lambda x: x**2 )(4) # takes in 4 and returns the number squared" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": 10, 151 | "metadata": {}, 152 | "outputs": [ 153 | { 154 | "data": { 155 | "text/plain": [ 156 | "50" 157 | ] 158 | }, 159 | "execution_count": 10, 160 | "metadata": {}, 161 | "output_type": "execute_result" 162 | } 163 | ], 164 | "source": [ 165 | "# passing multiple arguments into a lambda\n", 166 | "\n", 167 | "( lambda x, y: x * y)(10, 5) # x = 10, y = 5 and returns the result of 5 * 10" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": 11, 173 | "metadata": {}, 174 | "outputs": [ 175 | { 176 | "name": "stdout", 177 | "output_type": "stream", 178 | "text": [ 179 | " at 0x0000022934CA9400>\n", 180 | "50\n" 181 | ] 182 | } 183 | ], 184 | "source": [ 185 | "# saving a lambda function into a variable\n", 186 | "\n", 187 | "square = lambda x, y: x * y\n", 188 | "\n", 189 | "print(square)\n", 190 | "\n", 191 | "result = square(10, 5) # calls the lambda function stored in the square variable and returns 5 * 10\n", 192 | "\n", 193 | "print(result)" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": 12, 199 | "metadata": {}, 200 | "outputs": [ 201 | { 202 | "name": "stdout", 203 | "output_type": "stream", 204 | "text": [ 205 | "10\n" 206 | ] 207 | } 208 | ], 209 | "source": [ 210 | "# using if/else statements within a lambda to return the greater number\n", 211 | "\n", 212 | "greater = lambda x, y: x if x > y else y\n", 213 | "\n", 214 | "result = greater(5, 10)\n", 215 | "\n", 216 | "print(result)" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 13, 222 | "metadata": {}, 223 | "outputs": [ 224 | { 225 | "name": "stdout", 226 | "output_type": "stream", 227 | "text": [ 228 | "10\n", 229 | "15\n" 230 | ] 231 | } 232 | ], 233 | "source": [ 234 | "# returning a lambda function from another function\n", 235 | "\n", 236 | "def my_func(n):\n", 237 | " return lambda x: x * n\n", 238 | "\n", 239 | "doubler = my_func(2) # returns equivalent of lambda x: x * 2\n", 240 | "\n", 241 | "print( doubler(5) ) # will output 10\n", 242 | "\n", 243 | "tripler = my_func(3) # returns equivalent of lambda x: x * 3\n", 244 | "\n", 245 | "print(tripler(5)) # will output 15" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "metadata": {}, 251 | "source": [ 252 | "# Map, Reduce, and Filter" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": 15, 258 | "metadata": {}, 259 | "outputs": [ 260 | { 261 | "name": "stdout", 262 | "output_type": "stream", 263 | "text": [ 264 | "\n", 265 | "[54.5, 56.480000000000004, 59.0, 48.56]\n" 266 | ] 267 | } 268 | ], 269 | "source": [ 270 | "# using the map function without lambdas\n", 271 | "def convertDeg(C):\n", 272 | " return (9/5) * C + 32\n", 273 | "\n", 274 | "temps = [ 12.5, 13.6, 15, 9.2 ]\n", 275 | "\n", 276 | "converted_temps = map(convertDeg, temps) # returns map object\n", 277 | "\n", 278 | "print(converted_temps)\n", 279 | "\n", 280 | "converted_temps = list(converted_temps) # type convert map object into list of converted temps\n", 281 | "\n", 282 | "print(converted_temps)" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": 16, 288 | "metadata": {}, 289 | "outputs": [ 290 | { 291 | "name": "stdout", 292 | "output_type": "stream", 293 | "text": [ 294 | "[54.5, 56.480000000000004, 59.0, 48.56]\n" 295 | ] 296 | } 297 | ], 298 | "source": [ 299 | "# using a map function with lambdas\n", 300 | "\n", 301 | "temps = [ 12.5, 13.6, 15, 9.2 ]\n", 302 | "\n", 303 | "converted_temps = list( map( lambda C : (9/5) * C + 32, temps) ) # type convert the map object right away\n", 304 | "\n", 305 | "print(converted_temps)" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": 17, 311 | "metadata": {}, 312 | "outputs": [ 313 | { 314 | "name": "stdout", 315 | "output_type": "stream", 316 | "text": [ 317 | "\n", 318 | "[13.6, 15]\n" 319 | ] 320 | } 321 | ], 322 | "source": [ 323 | "# using the filter function without lambda functions, filter out temps below 55F\n", 324 | "\n", 325 | "def filterTemps(C):\n", 326 | " converted = (9/5) * C + 32\n", 327 | "\n", 328 | " return True if converted > 55 else False # use ternary operator\n", 329 | "\n", 330 | "temps = [ 12.5, 13.6, 15, 9.2 ]\n", 331 | "\n", 332 | "filtered_temps = filter(filterTemps, temps) # returns filter object\n", 333 | "\n", 334 | "print(filtered_temps)\n", 335 | "\n", 336 | "filtered_temps = list(filtered_temps) # convert filter object to list of filtered data\n", 337 | "\n", 338 | "print(filtered_temps)" 339 | ] 340 | }, 341 | { 342 | "cell_type": "code", 343 | "execution_count": 18, 344 | "metadata": {}, 345 | "outputs": [ 346 | { 347 | "name": "stdout", 348 | "output_type": "stream", 349 | "text": [ 350 | "[13.6, 15]\n" 351 | ] 352 | } 353 | ], 354 | "source": [ 355 | "# using the filter function with lambda functions, filter out temps below 55F\n", 356 | "\n", 357 | "temps = [ 12.5, 13.6, 15, 9.2 ]\n", 358 | "\n", 359 | "filtered_temps = list( filter( lambda C : True if (9/5) * C + 32 > 55 else False, temps) ) # type convert the filter\n", 360 | "\n", 361 | "print(filtered_temps)" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": 19, 367 | "metadata": {}, 368 | "outputs": [ 369 | { 370 | "name": "stdout", 371 | "output_type": "stream", 372 | "text": [ 373 | "24\n" 374 | ] 375 | } 376 | ], 377 | "source": [ 378 | "# for informational purposes this is how you use the reduce function\n", 379 | "from functools import reduce\n", 380 | "\n", 381 | "nums = [ 1, 2, 3, 4 ]\n", 382 | "\n", 383 | "result = reduce( lambda a, b : a * b, nums ) # result is 24\n", 384 | "\n", 385 | "print(result)" 386 | ] 387 | }, 388 | { 389 | "cell_type": "markdown", 390 | "metadata": {}, 391 | "source": [ 392 | "# Recursive Functions and Memoization" 393 | ] 394 | }, 395 | { 396 | "cell_type": "code", 397 | "execution_count": 22, 398 | "metadata": {}, 399 | "outputs": [ 400 | { 401 | "name": "stdout", 402 | "output_type": "stream", 403 | "text": [ 404 | "120\n" 405 | ] 406 | } 407 | ], 408 | "source": [ 409 | "# writing a factorial using recursive functions\n", 410 | "\n", 411 | "def factorial(n):\n", 412 | " # set your base case!\n", 413 | " if n <= 1:\n", 414 | " return 1\n", 415 | " else:\n", 416 | " return factorial( n - 1 ) * n\n", 417 | "\n", 418 | "print( factorial(5) ) # the result of 5 * 4 * 3 * 2 * 1" 419 | ] 420 | }, 421 | { 422 | "cell_type": "code", 423 | "execution_count": 23, 424 | "metadata": {}, 425 | "outputs": [ 426 | { 427 | "name": "stdout", 428 | "output_type": "stream", 429 | "text": [ 430 | "5\n" 431 | ] 432 | } 433 | ], 434 | "source": [ 435 | "# writing the recursive fibonacci sequence\n", 436 | "\n", 437 | "def fib(n):\n", 438 | " if n <= 1:\n", 439 | " return n\n", 440 | " else:\n", 441 | " return fib( n - 1 ) + fib( n - 2 )\n", 442 | "\n", 443 | "print( fib(5) ) # results in 5" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": 25, 449 | "metadata": {}, 450 | "outputs": [ 451 | { 452 | "name": "stdout", 453 | "output_type": "stream", 454 | "text": [ 455 | "12586269025\n" 456 | ] 457 | } 458 | ], 459 | "source": [ 460 | "# using memoization with the fibonacci sequence\n", 461 | "\n", 462 | "cache = { } # used to cache values to be used later\n", 463 | "\n", 464 | "def fib(n):\n", 465 | " if n in cache:\n", 466 | " return cache[ n ] # return value stored in dictionary\n", 467 | " \n", 468 | " result = 0\n", 469 | "\n", 470 | " # base case\n", 471 | " if n <= 1:\n", 472 | " result = n\n", 473 | " else:\n", 474 | " result = fib( n - 1 ) + fib( n - 2 )\n", 475 | " \n", 476 | " cache[ n ] = result # save result into dictionary with n as the key\n", 477 | " \n", 478 | " return result\n", 479 | "\n", 480 | "print( fib(50) ) # calculates almost instantly" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": 27, 486 | "metadata": {}, 487 | "outputs": [ 488 | { 489 | "data": { 490 | "text/plain": [ 491 | "12586269025" 492 | ] 493 | }, 494 | "execution_count": 27, 495 | "metadata": {}, 496 | "output_type": "execute_result" 497 | } 498 | ], 499 | "source": [ 500 | "# using @lru_cache, Python’s default moization/caching technique\n", 501 | "from functools import lru_cache\n", 502 | "\n", 503 | "@lru_cache( ) # python’s built-in memoization/caching system\n", 504 | "def fib(n):\n", 505 | " if n <= 1:\n", 506 | " return n\n", 507 | " else:\n", 508 | " return fib( n - 1 ) + fib( n - 2 )\n", 509 | "\n", 510 | "fib(50) # calculates almost instantly" 511 | ] 512 | }, 513 | { 514 | "cell_type": "markdown", 515 | "metadata": {}, 516 | "source": [ 517 | "# Friday Project: Writing a Binary Search" 518 | ] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": 35, 523 | "metadata": {}, 524 | "outputs": [ 525 | { 526 | "name": "stdout", 527 | "output_type": "stream", 528 | "text": [ 529 | "[1, 1, 3, 5, 10, 10, 11, 13, 13, 18]\n", 530 | "True\n" 531 | ] 532 | } 533 | ], 534 | "source": [ 535 | "# full output of binary search without comments\n", 536 | "import random\n", 537 | "\n", 538 | "nums = [ random.randint(0, 20) for i in range(10) ]\n", 539 | "\n", 540 | "def binarySearch(aList, num):\n", 541 | " aList.sort( )\n", 542 | " \n", 543 | " while aList:\n", 544 | " mid = len(aList) // 2\n", 545 | "\n", 546 | " if aList[mid] == num:\n", 547 | " return True\n", 548 | " elif aList[mid] > num:\n", 549 | " aList = aList[ : mid ]\n", 550 | " elif aList[mid] < num:\n", 551 | " aList = aList[ mid + 1 : ]\n", 552 | " \n", 553 | " return False\n", 554 | "\n", 555 | "print( sorted(nums) )\n", 556 | "print( binarySearch(nums, 3) )" 557 | ] 558 | }, 559 | { 560 | "cell_type": "markdown", 561 | "metadata": {}, 562 | "source": [ 563 | "# Monday Exercises - Answers" 564 | ] 565 | }, 566 | { 567 | "cell_type": "markdown", 568 | "metadata": {}, 569 | "source": [ 570 | "

\n", 571 | "1. Degree Conversion: Using list comprehension, convert the list below to Fahrenheit. Currently, the degrees are in Celsius temperatures. The conversion formula is \"(9/5) * C + 32\". Your output should be [53.6, 69.8, 59, 89.6]. \n", 572 | "

\n", 573 | "\n", 574 | "

\n", 575 | ">>> degrees = [12, 21, 15, 32]\n", 576 | "

" 577 | ] 578 | }, 579 | { 580 | "cell_type": "code", 581 | "execution_count": 78, 582 | "metadata": {}, 583 | "outputs": [ 584 | { 585 | "name": "stdout", 586 | "output_type": "stream", 587 | "text": [ 588 | "[53.6, 69.8, 59.0, 89.6]\n" 589 | ] 590 | } 591 | ], 592 | "source": [ 593 | "degrees = [12, 21, 15, 32]\n", 594 | "\n", 595 | "degrees = [round((9/5) * deg + 32, 1) for deg in degrees]\n", 596 | "\n", 597 | "print(degrees)" 598 | ] 599 | }, 600 | { 601 | "cell_type": "markdown", 602 | "metadata": {}, 603 | "source": [ 604 | "

\n", 605 | "2. User Input: Ask the user to input a single integer up to and including 100. Generate a list of numbers that are exactly divisble by that number up to and including 100 using list comprehension. For example, if the number 25 was input, then the output should be [25, 50, 75, 100].\n", 606 | "

" 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": 84, 612 | "metadata": {}, 613 | "outputs": [ 614 | { 615 | "name": "stdout", 616 | "output_type": "stream", 617 | "text": [ 618 | "Input a number up to or including 100: 25\n", 619 | "[25, 50, 75, 100]\n" 620 | ] 621 | } 622 | ], 623 | "source": [ 624 | "num = int(input('Input a number up to or including 100: '))\n", 625 | "\n", 626 | "numbers = [x for x in range(1, 101) if x % num == 0]\n", 627 | "\n", 628 | "print(numbers)" 629 | ] 630 | }, 631 | { 632 | "cell_type": "markdown", 633 | "metadata": {}, 634 | "source": [ 635 | "# Tuesday Exercises - Answers" 636 | ] 637 | }, 638 | { 639 | "cell_type": "markdown", 640 | "metadata": {}, 641 | "source": [ 642 | "

\n", 643 | "1. Fill in the Blanks: Fill in the blanks for the code below so that it takes in a parameter of \"x\" and returns \"True\" if it is greater than 50, otherwise it should return \"False\".\n", 644 | "

\n", 645 | "\n", 646 | "

\n", 647 | ">>> __________ x _____ True if x _ 50 ________ False\n", 648 | "

" 649 | ] 650 | }, 651 | { 652 | "cell_type": "code", 653 | "execution_count": 73, 654 | "metadata": {}, 655 | "outputs": [ 656 | { 657 | "data": { 658 | "text/plain": [ 659 | ">" 660 | ] 661 | }, 662 | "execution_count": 73, 663 | "metadata": {}, 664 | "output_type": "execute_result" 665 | } 666 | ], 667 | "source": [ 668 | "lambda x: True if x > 50 else False" 669 | ] 670 | }, 671 | { 672 | "cell_type": "markdown", 673 | "metadata": {}, 674 | "source": [ 675 | "

\n", 676 | "2. Degree Conversion: Write a lambda function that takes in a degree value in Celsius and returns the degree converted into Fahrenheit.\n", 677 | "

" 678 | ] 679 | }, 680 | { 681 | "cell_type": "code", 682 | "execution_count": 75, 683 | "metadata": {}, 684 | "outputs": [ 685 | { 686 | "data": { 687 | "text/plain": [ 688 | "32.0" 689 | ] 690 | }, 691 | "execution_count": 75, 692 | "metadata": {}, 693 | "output_type": "execute_result" 694 | } 695 | ], 696 | "source": [ 697 | "(lambda deg: (9/5) * deg + 32)(0)" 698 | ] 699 | }, 700 | { 701 | "cell_type": "markdown", 702 | "metadata": {}, 703 | "source": [ 704 | "# Wednesday Exercises - Answers" 705 | ] 706 | }, 707 | { 708 | "cell_type": "markdown", 709 | "metadata": {}, 710 | "source": [ 711 | "

\n", 712 | "1. Mapping Names: Use a lamba and map function to map over the list of names below to produce the following result \"[\"Ryan\", \"Paul\", \"Kevin Connors\"].\n", 713 | "

\n", 714 | "\n", 715 | "

\n", 716 | ">>> names = [ \" ryan\", \"PAUL\", \"kevin connors \"]\n", 717 | "

" 718 | ] 719 | }, 720 | { 721 | "cell_type": "code", 722 | "execution_count": 68, 723 | "metadata": {}, 724 | "outputs": [ 725 | { 726 | "name": "stdout", 727 | "output_type": "stream", 728 | "text": [ 729 | "['Ryan', 'Paul', 'Kevin Connors']\n" 730 | ] 731 | } 732 | ], 733 | "source": [ 734 | "names = [ \" ryan\", \"PAUL\", \"kevin connors \"]\n", 735 | "\n", 736 | "names = list(map(lambda name: name.strip().title(), names))\n", 737 | "\n", 738 | "print(names)" 739 | ] 740 | }, 741 | { 742 | "cell_type": "markdown", 743 | "metadata": {}, 744 | "source": [ 745 | "

\n", 746 | "2. Filter Names: Using a lambda and filter function, filter out all the names that start with the letter 'A'. Make it case insensitive so it filters out the name whether it's uppercase or not. The output of the list below should be [\"Frank\", \"Ripal\"].\n", 747 | "

\n", 748 | "\n", 749 | "

\n", 750 | ">>> names = [\"Amanda\", \"Frank\", \"abby\", \"Ripal\", \"Adam\"]\n", 751 | "

" 752 | ] 753 | }, 754 | { 755 | "cell_type": "code", 756 | "execution_count": 72, 757 | "metadata": {}, 758 | "outputs": [ 759 | { 760 | "name": "stdout", 761 | "output_type": "stream", 762 | "text": [ 763 | "['Frank', 'Ripal']\n" 764 | ] 765 | } 766 | ], 767 | "source": [ 768 | "names = [\"Amanda\", \"Frank\", \"abby\", \"Ripal\", \"Adam\"]\n", 769 | "\n", 770 | "names = list(filter(lambda name: True if name[0].lower() != 'a' else False, names))\n", 771 | "\n", 772 | "print(names)" 773 | ] 774 | }, 775 | { 776 | "cell_type": "markdown", 777 | "metadata": {}, 778 | "source": [ 779 | "# Thursday Exercises - Answers" 780 | ] 781 | }, 782 | { 783 | "cell_type": "markdown", 784 | "metadata": {}, 785 | "source": [ 786 | "

\n", 787 | "1. Factorial Caching: Apply either the lru_cache built-in decorator to the factorial function that we create previously, or setup your own caching system.\n", 788 | "

" 789 | ] 790 | }, 791 | { 792 | "cell_type": "code", 793 | "execution_count": 40, 794 | "metadata": {}, 795 | "outputs": [ 796 | { 797 | "name": "stdout", 798 | "output_type": "stream", 799 | "text": [ 800 | "815915283247897734345611269596115894272000000000\n" 801 | ] 802 | } 803 | ], 804 | "source": [ 805 | "from functools import lru_cache\n", 806 | "\n", 807 | "@lru_cache(500)\n", 808 | "def factorial(n):\n", 809 | " # set your base case!\n", 810 | " if n <= 1:\n", 811 | " return 1\n", 812 | " else:\n", 813 | " return factorial( n - 1 ) * n\n", 814 | "\n", 815 | "print( factorial(40) ) # the result of 5 * 4 * 3 * 2 * 1" 816 | ] 817 | }, 818 | { 819 | "cell_type": "markdown", 820 | "metadata": {}, 821 | "source": [ 822 | "

\n", 823 | "2. Searching Data: Create a function that takes in two arguments, a list of data and an item to search for. Search through the list of data passed in and return True if the item to search for appears, otherwise return False. If one of the items is another list, create a recursive call so that you don't need to create another loop. Use the example call below as a reference on what data to expect:\n", 824 | "

\n", 825 | "\n", 826 | "

\n", 827 | ">>> searchList( [2, 3, [18, 22], 6], 22)\n", 828 | "

" 829 | ] 830 | }, 831 | { 832 | "cell_type": "code", 833 | "execution_count": 37, 834 | "metadata": {}, 835 | "outputs": [ 836 | { 837 | "data": { 838 | "text/plain": [ 839 | "True" 840 | ] 841 | }, 842 | "execution_count": 37, 843 | "metadata": {}, 844 | "output_type": "execute_result" 845 | } 846 | ], 847 | "source": [ 848 | "def searchList(aList, num):\n", 849 | " result = False\n", 850 | " \n", 851 | " for item in aList:\n", 852 | " if item == num:\n", 853 | " return True\n", 854 | " elif isinstance(item, list):\n", 855 | " result = searchList(item, num)\n", 856 | " \n", 857 | " return result\n", 858 | "\n", 859 | "searchList([2, 3, [18, 22], 6], 22)" 860 | ] 861 | }, 862 | { 863 | "cell_type": "markdown", 864 | "metadata": {}, 865 | "source": [ 866 | "# End of Week Exercises - Answers" 867 | ] 868 | }, 869 | { 870 | "cell_type": "markdown", 871 | "metadata": {}, 872 | "source": [ 873 | "

\n", 874 | "1. Recursive Binary Search: Turn the Binary Search algorithm that we created together into a recursive function. Rather than using a while loop, it should call itself in order to cut the list down and eventually return True or False.\n", 875 | "

" 876 | ] 877 | }, 878 | { 879 | "cell_type": "code", 880 | "execution_count": 45, 881 | "metadata": {}, 882 | "outputs": [ 883 | { 884 | "name": "stdout", 885 | "output_type": "stream", 886 | "text": [ 887 | "[0, 4, 6, 7, 8, 10, 13, 14, 16, 20]\n", 888 | "False\n" 889 | ] 890 | } 891 | ], 892 | "source": [ 893 | "import random\n", 894 | "\n", 895 | "nums = [ random.randint(0, 20) for i in range(10) ]\n", 896 | "\n", 897 | "def binarySearch(aList, num):\n", 898 | " # base case\n", 899 | " if aList == []:\n", 900 | " return False\n", 901 | " \n", 902 | " aList.sort( )\n", 903 | " \n", 904 | " mid = len(aList) // 2\n", 905 | "\n", 906 | " if aList[mid] == num:\n", 907 | " return True\n", 908 | " elif aList[mid] > num:\n", 909 | " return binarySearch(aList[ : mid ], num)\n", 910 | " elif aList[mid] < num:\n", 911 | " return binarySearch(aList[ mid + 1 : ], num)\n", 912 | " \n", 913 | "print( sorted(nums) )\n", 914 | "print( binarySearch(nums, 3) )" 915 | ] 916 | }, 917 | { 918 | "cell_type": "markdown", 919 | "metadata": {}, 920 | "source": [ 921 | "

\n", 922 | "2. Efficient Algorithms: Looking at the Binary Search we wrote, how could you possibly make it even more efficient?\n", 923 | "

" 924 | ] 925 | }, 926 | { 927 | "cell_type": "markdown", 928 | "metadata": {}, 929 | "source": [ 930 | "

When you write the steps out, you can see that the algorithm always sorts the list, and continues to do so, even if the list is sorted. It would be better to require the list to be sorted before passing in the data to the function. This way if you use recursive functions that we would not have to sort the list each time.

" 931 | ] 932 | }, 933 | { 934 | "cell_type": "markdown", 935 | "metadata": {}, 936 | "source": [ 937 | "

\n", 938 | "3. Case Sensitive Search: Re-write the Binary Search so that it works with a list that holds both numbers and letters. It should be case sensitive. Use the function call below to understand the parameters being passed in. Hint \"22\" < 'a' will return True\n", 939 | "

\n", 940 | "\n", 941 | "

\n", 942 | ">>> binarySearch( ['a', 22, '3', 'hello', 1022, 4, 'e'], 'hello') # returns True\n", 943 | "

" 944 | ] 945 | }, 946 | { 947 | "cell_type": "code", 948 | "execution_count": 65, 949 | "metadata": {}, 950 | "outputs": [ 951 | { 952 | "name": "stdout", 953 | "output_type": "stream", 954 | "text": [ 955 | "True\n" 956 | ] 957 | } 958 | ], 959 | "source": [ 960 | "data = ['a', 22, '3', 'hello', 1022, 4, 'e']\n", 961 | "\n", 962 | "def binarySearch(aList, num):\n", 963 | " # convert data into strings\n", 964 | " for i in range(len(aList)):\n", 965 | " aList[i] = str(aList[i])\n", 966 | " \n", 967 | " # sort all strings as you could not sort strings and numbers together\n", 968 | " aList.sort()\n", 969 | " \n", 970 | " while aList:\n", 971 | " mid = len(aList) // 2\n", 972 | "\n", 973 | " if str(aList[mid]) == str(num):\n", 974 | " return True\n", 975 | " elif str(aList[mid]) > str(num):\n", 976 | " aList = aList[ : mid ]\n", 977 | " elif str(aList[mid]) < str(num):\n", 978 | " aList = aList[ mid + 1 : ]\n", 979 | " \n", 980 | " return False\n", 981 | "\n", 982 | "print( binarySearch(data, 'hello') )" 983 | ] 984 | } 985 | ], 986 | "metadata": { 987 | "kernelspec": { 988 | "display_name": "Python 3", 989 | "language": "python", 990 | "name": "python3" 991 | }, 992 | "language_info": { 993 | "codemirror_mode": { 994 | "name": "ipython", 995 | "version": 3 996 | }, 997 | "file_extension": ".py", 998 | "mimetype": "text/x-python", 999 | "name": "python", 1000 | "nbconvert_exporter": "python", 1001 | "pygments_lexer": "ipython3", 1002 | "version": "3.6.5" 1003 | } 1004 | }, 1005 | "nbformat": 4, 1006 | "nbformat_minor": 2 1007 | } 1008 | -------------------------------------------------------------------------------- /Week_09.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Generators and Iterators" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 20, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "baseball\n", 20 | "soccer\n", 21 | "football\n", 22 | "hockey\n", 23 | "basketball\n" 24 | ] 25 | }, 26 | { 27 | "ename": "StopIteration", 28 | "evalue": "", 29 | "output_type": "error", 30 | "traceback": [ 31 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 32 | "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", 33 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mitem\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 12\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 13\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmy_iter\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 34 | "\u001b[1;31mStopIteration\u001b[0m: " 35 | ] 36 | } 37 | ], 38 | "source": [ 39 | "# creating a basic iterator from an iterable\n", 40 | "\n", 41 | "sports = ['baseball', 'soccer', 'football', 'hockey', 'basketball']\n", 42 | "\n", 43 | "my_iter = iter(sports)\n", 44 | "\n", 45 | "print(next(my_iter))\n", 46 | "print(next(my_iter))\n", 47 | "\n", 48 | "for item in my_iter:\n", 49 | " print(item)\n", 50 | " \n", 51 | "print(next(my_iter))" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 22, 57 | "metadata": {}, 58 | "outputs": [ 59 | { 60 | "name": "stdout", 61 | "output_type": "stream", 62 | "text": [ 63 | "a\n", 64 | "b\n", 65 | "c\n", 66 | "d\n", 67 | "e\n", 68 | "f\n", 69 | "g\n", 70 | "h\n", 71 | "i\n", 72 | "j\n", 73 | "k\n", 74 | "l\n", 75 | "m\n", 76 | "n\n", 77 | "o\n", 78 | "p\n", 79 | "q\n", 80 | "r\n", 81 | "s\n", 82 | "t\n", 83 | "u\n", 84 | "v\n", 85 | "w\n", 86 | "x\n", 87 | "y\n", 88 | "z\n" 89 | ] 90 | } 91 | ], 92 | "source": [ 93 | "# creating our own iterator\n", 94 | "\n", 95 | "class Alphabet():\n", 96 | " def __iter__(self):\n", 97 | " self.letters = 'abcdefghijklmnopqrstuvwxyz'\n", 98 | " self.index = 0\n", 99 | " return self\n", 100 | " \n", 101 | " def __next__(self):\n", 102 | " if self.index <= 25:\n", 103 | " char = self.letters[self.index]\n", 104 | " self.index += 1\n", 105 | " return char\n", 106 | " else:\n", 107 | " raise StopIteration\n", 108 | " \n", 109 | "for char in Alphabet():\n", 110 | " print(char)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 14, 116 | "metadata": {}, 117 | "outputs": [ 118 | { 119 | "name": "stdout", 120 | "output_type": "stream", 121 | "text": [ 122 | "Generator Start Value: 0\n", 123 | "For Loop X Value: 0\n", 124 | "Generator Start Value: 1\n", 125 | "For Loop X Value: 1\n", 126 | "Generator Start Value: 2\n", 127 | "For Loop X Value: 2\n", 128 | "Generator Start Value: 3\n", 129 | "For Loop X Value: 3\n", 130 | "Generator Start Value: 4\n", 131 | "For Loop X Value: 4\n" 132 | ] 133 | } 134 | ], 135 | "source": [ 136 | "# creating our own range function with start, stop, and step parameters\n", 137 | "\n", 138 | "def myRange(stop, start=0, step=1):\n", 139 | " while start < stop:\n", 140 | " print(\"Generator Start Value: {}\".format(start))\n", 141 | " yield start\n", 142 | " start += step\n", 143 | " \n", 144 | "for x in myRange(5):\n", 145 | " print(\"For Loop X Value: {}\".format(x))" 146 | ] 147 | }, 148 | { 149 | "cell_type": "markdown", 150 | "metadata": {}, 151 | "source": [ 152 | "# Decorators" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": 60, 158 | "metadata": {}, 159 | "outputs": [ 160 | { 161 | "name": "stdout", 162 | "output_type": "stream", 163 | "text": [ 164 | "=======\n", 165 | "John!\n", 166 | "=======\n" 167 | ] 168 | } 169 | ], 170 | "source": [ 171 | "# creating and applying our own decorator using the @ symbol\n", 172 | "\n", 173 | "def decorator(func):\n", 174 | " def wrap():\n", 175 | " print(\"=======\")\n", 176 | " func()\n", 177 | " print(\"=======\")\n", 178 | " return wrap\n", 179 | "\n", 180 | "@decorator\n", 181 | "def printName():\n", 182 | " print(\"John!\")\n", 183 | " \n", 184 | "printName()" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 57, 190 | "metadata": {}, 191 | "outputs": [ 192 | { 193 | "name": "stdout", 194 | "output_type": "stream", 195 | "text": [ 196 | "Hello!\n", 197 | "Hello!\n", 198 | "Hello!\n", 199 | "Hello!\n" 200 | ] 201 | } 202 | ], 203 | "source": [ 204 | "# creating a decorator that takes in parameters\n", 205 | "\n", 206 | "def run_times(num):\n", 207 | " def wrap(func):\n", 208 | " for i in range(num):\n", 209 | " func()\n", 210 | " return wrap\n", 211 | "\n", 212 | "@run_times(4)\n", 213 | "def sayHello():\n", 214 | " print(\"Hello!\")" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": 65, 220 | "metadata": {}, 221 | "outputs": [ 222 | { 223 | "name": "stdout", 224 | "output_type": "stream", 225 | "text": [ 226 | "Happy birthday Paul, you are now 44.\n" 227 | ] 228 | } 229 | ], 230 | "source": [ 231 | "# creating a decorator for a function that accepts parameters\n", 232 | "\n", 233 | "def birthday(func):\n", 234 | " def wrap(name, age):\n", 235 | " func(name, age + 1)\n", 236 | " return wrap\n", 237 | "\n", 238 | "@birthday\n", 239 | "def celebrate(name, age):\n", 240 | " print(\"Happy birthday {}, you are now {}.\".format(name, age))\n", 241 | " \n", 242 | "celebrate(\"Paul\", 43)" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 75, 248 | "metadata": {}, 249 | "outputs": [ 250 | { 251 | "name": "stdout", 252 | "output_type": "stream", 253 | "text": [ 254 | "What is the password?klj;\n", 255 | "Access Denied\n" 256 | ] 257 | } 258 | ], 259 | "source": [ 260 | "# real world sim, restricting function access\n", 261 | "\n", 262 | "def login_required(func):\n", 263 | " def wrap(user):\n", 264 | " password = input(\"What is the password?\")\n", 265 | " if password == user[\"password\"]:\n", 266 | " func(user)\n", 267 | " else:\n", 268 | " print(\"Access Denied\")\n", 269 | " return wrap\n", 270 | "\n", 271 | "@login_required\n", 272 | "def restrictedFunc(user):\n", 273 | " print(\"Access granted, welcome {}\".format(user[\"name\"]))\n", 274 | " \n", 275 | "user = { \"name\" : \"Jess\", \"password\" : \"ilywpf\" }\n", 276 | " \n", 277 | "restrictedFunc(user)" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": { 283 | "collapsed": true 284 | }, 285 | "source": [ 286 | "# Modules" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 8, 292 | "metadata": {}, 293 | "outputs": [ 294 | { 295 | "name": "stdout", 296 | "output_type": "stream", 297 | "text": [ 298 | "2\n", 299 | "3\n", 300 | "3.141592653589793\n" 301 | ] 302 | } 303 | ], 304 | "source": [ 305 | "# import the entire math module\n", 306 | "import math\n", 307 | "\n", 308 | "print(math.floor(2.5))\n", 309 | "print(math.ceil(2.5))\n", 310 | "print(math.pi)" 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": 2, 316 | "metadata": {}, 317 | "outputs": [ 318 | { 319 | "name": "stdout", 320 | "output_type": "stream", 321 | "text": [ 322 | "2\n", 323 | "3.141592653589793\n" 324 | ] 325 | } 326 | ], 327 | "source": [ 328 | "# importing only variables and functions rather than an entire module, better efficiency\n", 329 | "from math import floor, pi\n", 330 | "\n", 331 | "print(floor(2.5))\n", 332 | "# print(ceil(2.5)) will cause error because we only imported floor and pi, not ceil and not all of math\n", 333 | "print(pi)" 334 | ] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": 4, 339 | "metadata": {}, 340 | "outputs": [ 341 | { 342 | "name": "stdout", 343 | "output_type": "stream", 344 | "text": [ 345 | "2\n" 346 | ] 347 | } 348 | ], 349 | "source": [ 350 | "# using the 'as' keyword to create an alias for imports\n", 351 | "from math import floor as f\n", 352 | "\n", 353 | "print(f(2.5))" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": 7, 359 | "metadata": {}, 360 | "outputs": [ 361 | { 362 | "name": "stdout", 363 | "output_type": "stream", 364 | "text": [ 365 | "5 10\n", 366 | "John Smith is 37 years old.\n" 367 | ] 368 | } 369 | ], 370 | "source": [ 371 | "# using the run command with Jupyter Notebook to access our own modules\n", 372 | "%run test.py\n", 373 | "\n", 374 | "print(length, width)\n", 375 | "\n", 376 | "printInfo('John Smith', 37)" 377 | ] 378 | }, 379 | { 380 | "cell_type": "markdown", 381 | "metadata": { 382 | "collapsed": true 383 | }, 384 | "source": [ 385 | "# Understanding Algorithmic Complexity" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 2, 391 | "metadata": { 392 | "collapsed": true 393 | }, 394 | "outputs": [], 395 | "source": [ 396 | "# creating data collections to test for time complexity\n", 397 | "import time\n", 398 | "\n", 399 | "d = {} # generate fake dictionary\n", 400 | "\n", 401 | "for i in range(10000000):\n", 402 | " d[i] = 'value'\n", 403 | " \n", 404 | "big_list = [x for x in range(10000000)] # generate fake list" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": 14, 410 | "metadata": {}, 411 | "outputs": [ 412 | { 413 | "name": "stdout", 414 | "output_type": "stream", 415 | "text": [ 416 | "Found in dictionary\n", 417 | "Elapsed time for dictionary: 0.0\n", 418 | "Found in list\n", 419 | "Elapsed time for list: 0.10376596450805664\n" 420 | ] 421 | } 422 | ], 423 | "source": [ 424 | "# retrieving information and tracking time to see which is faster\n", 425 | "\n", 426 | "start_time = time.time() # tracking time for dictionary\n", 427 | "\n", 428 | "if 9999999 in d:\n", 429 | " print('Found in dictionary')\n", 430 | "\n", 431 | "end_time = time.time() - start_time\n", 432 | "\n", 433 | "print('Elapsed time for dictionary: {}'.format(end_time))\n", 434 | "\n", 435 | "start_time = time.time() # tracking time for list\n", 436 | "\n", 437 | "if 9999999 in big_list:\n", 438 | " print('Found in list')\n", 439 | "\n", 440 | "end_time = time.time() - start_time\n", 441 | "\n", 442 | "print('Elapsed time for list: {}'.format(end_time))" 443 | ] 444 | }, 445 | { 446 | "cell_type": "code", 447 | "execution_count": 31, 448 | "metadata": { 449 | "collapsed": true 450 | }, 451 | "outputs": [], 452 | "source": [ 453 | "# testing a bubble sort vs. insertion sort\n", 454 | "\n", 455 | "def bubbleSort(aList):\n", 456 | " for i in range(len(aList)):\n", 457 | " switched = False\n", 458 | " for j in range(len(aList) - 1):\n", 459 | " if aList[j] > aList[j + 1]:\n", 460 | " aList[j], aList[j + 1] = aList[j + 1], aList[j]\n", 461 | " switched = True\n", 462 | " if switched == False:\n", 463 | " break\n", 464 | " return aList\n", 465 | "\n", 466 | "def insertionSort(aList):\n", 467 | " for i in range(1, len(aList)):\n", 468 | " if aList[i] < aList[i - 1]:\n", 469 | " for j in range(i, 0, -1):\n", 470 | " if aList[j] < aList[j - 1]:\n", 471 | " aList[j], aList[j - 1] = aList[j - 1], aList[j]\n", 472 | " else:\n", 473 | " break\n", 474 | " return aList" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": 36, 480 | "metadata": {}, 481 | "outputs": [ 482 | { 483 | "name": "stdout", 484 | "output_type": "stream", 485 | "text": [ 486 | "Elapsed time for Bubble Sort: 2.801460027694702\n", 487 | "Elapsed time for Insertion Sort: 0.0009980201721191406\n" 488 | ] 489 | } 490 | ], 491 | "source": [ 492 | "# calling bubble sort and insertion sort to test time complexity\n", 493 | "from random import randint\n", 494 | "\n", 495 | "nums = [randint(0, 100) for x in range(5000)]\n", 496 | "\n", 497 | "start_time = time.time() # tracking time bubble sort\n", 498 | "bubbleSort(nums)\n", 499 | "end_time = time.time() - start_time\n", 500 | "print('Elapsed time for Bubble Sort: {}'.format(end_time))\n", 501 | "\n", 502 | "start_time = time.time() # tracking time insertion sort\n", 503 | "insertionSort(nums)\n", 504 | "end_time = time.time() - start_time\n", 505 | "print('Elapsed time for Insertion Sort: {}'.format(end_time))" 506 | ] 507 | }, 508 | { 509 | "cell_type": "markdown", 510 | "metadata": {}, 511 | "source": [ 512 | "# Monday Exercises - Answers" 513 | ] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "metadata": {}, 518 | "source": [ 519 | "

\n", 520 | "1. Reverse Iteration: Create an iterator that takes in a list and when iterated over, it returns the information in a reverse order. Hint: When accepting arguments into an iterator, you need to use the init method, as well as iter and next. The call below should result in \"5, 4, 3, 2, 1\".\n", 521 | "

\n", 522 | "\n", 523 | "

\n", 524 | ">>> for i in RevIter([1, 2, 3, 4, 5]):\n", 525 | "

" 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "execution_count": 2, 531 | "metadata": {}, 532 | "outputs": [ 533 | { 534 | "name": "stdout", 535 | "output_type": "stream", 536 | "text": [ 537 | "5\n", 538 | "4\n", 539 | "3\n", 540 | "2\n", 541 | "1\n" 542 | ] 543 | } 544 | ], 545 | "source": [ 546 | "# creating an iterator that will iterate an iterable in reverse direction\n", 547 | "\n", 548 | "class ReverseIter():\n", 549 | " def __init__(self, items):\n", 550 | " self.items = items\n", 551 | " self.i = len(items) - 1\n", 552 | " \n", 553 | " def __iter__(self):\n", 554 | " return self\n", 555 | " \n", 556 | " def __next__(self):\n", 557 | " if self.i >= 0:\n", 558 | " item = self.items[self.i]\n", 559 | " self.i -= 1\n", 560 | " return item\n", 561 | " else:\n", 562 | " raise StopIteration\n", 563 | " \n", 564 | "rev_iter = ReverseIter([1, 2, 3, 4, 5])\n", 565 | "\n", 566 | "\n", 567 | "for num in rev_iter:\n", 568 | " print(num)" 569 | ] 570 | }, 571 | { 572 | "cell_type": "markdown", 573 | "metadata": {}, 574 | "source": [ 575 | "

\n", 576 | "2. Squares: Create a generator that acts like the range function, except it yields a squared number every time. The result of the call below should be \"0, 1, 4, 16\".\n", 577 | "

\n", 578 | "\n", 579 | "

\n", 580 | ">>> for i in range(4):\n", 581 | "

" 582 | ] 583 | }, 584 | { 585 | "cell_type": "code", 586 | "execution_count": 5, 587 | "metadata": {}, 588 | "outputs": [ 589 | { 590 | "name": "stdout", 591 | "output_type": "stream", 592 | "text": [ 593 | "0\n", 594 | "1\n", 595 | "4\n", 596 | "9\n", 597 | "16\n" 598 | ] 599 | } 600 | ], 601 | "source": [ 602 | "def squared(n):\n", 603 | " for i in range(n + 1):\n", 604 | " yield i**2\n", 605 | " \n", 606 | "for x in squared(4):\n", 607 | " print(x)" 608 | ] 609 | }, 610 | { 611 | "cell_type": "markdown", 612 | "metadata": {}, 613 | "source": [ 614 | "# Tuesday Exercises - Answers" 615 | ] 616 | }, 617 | { 618 | "cell_type": "markdown", 619 | "metadata": {}, 620 | "source": [ 621 | "

\n", 622 | "1. User Input: Create a decorator that will ask the user for a number and run the function it is attached to only if the number is less than 100. The function should simply output “Less than 100”. Use the function declaration below:\n", 623 | "

\n", 624 | "\n", 625 | "

\n", 626 | ">>> @decorator
\n", 627 | ">>> def numbers():
\n", 628 | ">>>      print(\"Less than 100\")\n", 629 | "

" 630 | ] 631 | }, 632 | { 633 | "cell_type": "code", 634 | "execution_count": 9, 635 | "metadata": {}, 636 | "outputs": [ 637 | { 638 | "name": "stdout", 639 | "output_type": "stream", 640 | "text": [ 641 | "Enter a number: 1000\n" 642 | ] 643 | } 644 | ], 645 | "source": [ 646 | "def decorator(f):\n", 647 | " def wrap():\n", 648 | " num = int(input(\"Enter a number: \"))\n", 649 | " if num < 100:\n", 650 | " f()\n", 651 | " return wrap\n", 652 | "\n", 653 | "@decorator\n", 654 | "def numbers():\n", 655 | " print(\"Less than 100\")\n", 656 | " \n", 657 | "numbers()" 658 | ] 659 | }, 660 | { 661 | "cell_type": "markdown", 662 | "metadata": {}, 663 | "source": [ 664 | "

\n", 665 | "2. Creating a Route: Create a decorator that takes in a string as an argument with a wrap function that takes in func. Have the wrap function print out the string and run the function passed in. The function passed in doesn’t need to do anything. In Flask, you can create a page by using decorators that accept a url string. Use the function declaration below to start:\n", 666 | "

\n", 667 | "\n", 668 | "

\n", 669 | ">>> @route(\"/index\")
\n", 670 | ">>> def index():
\n", 671 | ">>>      print(\"This is how web pages are made in Flask\")\n", 672 | "

" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": 10, 678 | "metadata": {}, 679 | "outputs": [ 680 | { 681 | "name": "stdout", 682 | "output_type": "stream", 683 | "text": [ 684 | "/index\n", 685 | "This is how web pages are made in Flask\n" 686 | ] 687 | } 688 | ], 689 | "source": [ 690 | "def route(endpoint):\n", 691 | " def wrap(f):\n", 692 | " print(endpoint)\n", 693 | " f()\n", 694 | " return wrap\n", 695 | "\n", 696 | "@route(\"/index\")\n", 697 | "def index():\n", 698 | " print(\"This is how web pages are made in Flask\")" 699 | ] 700 | }, 701 | { 702 | "cell_type": "markdown", 703 | "metadata": {}, 704 | "source": [ 705 | "# Wednesday Exercises - Answers" 706 | ] 707 | }, 708 | { 709 | "cell_type": "markdown", 710 | "metadata": {}, 711 | "source": [ 712 | "

\n", 713 | "1. Time Module: Import the time module and call the sleep function. Make the cell sleep for 5 seconds, and then print “Time module imported”. Although we haven’t covered this module, this exercise will provide good practice for you to try and work with a module on your own. Feel free to use Google, Quora, etc.\n", 714 | "

" 715 | ] 716 | }, 717 | { 718 | "cell_type": "code", 719 | "execution_count": 11, 720 | "metadata": {}, 721 | "outputs": [ 722 | { 723 | "name": "stdout", 724 | "output_type": "stream", 725 | "text": [ 726 | "Time module imported\n" 727 | ] 728 | } 729 | ], 730 | "source": [ 731 | "import time\n", 732 | "\n", 733 | "time.sleep(5)\n", 734 | "\n", 735 | "print(\"Time module imported\")" 736 | ] 737 | }, 738 | { 739 | "cell_type": "markdown", 740 | "metadata": {}, 741 | "source": [ 742 | "

\n", 743 | "2. Calculating Area: Create a module named “calculation.py” that has a single function within it. That function should take in two parameters and return the product of them. We can imagine that we’re trying to calculate the area of a rectangle and it needs to take in the length and width properties. Run the module within Jupyter Notebook and use the function call below within the cell:\n", 744 | "

\n", 745 | "\n", 746 | "

\n", 747 | ">>> calcArea(15, 30)\n", 748 | "

" 749 | ] 750 | }, 751 | { 752 | "cell_type": "code", 753 | "execution_count": 12, 754 | "metadata": {}, 755 | "outputs": [ 756 | { 757 | "name": "stdout", 758 | "output_type": "stream", 759 | "text": [ 760 | "450\n" 761 | ] 762 | } 763 | ], 764 | "source": [ 765 | "%run calculation.py\n", 766 | "\n", 767 | "print(calcArea(15, 30))" 768 | ] 769 | }, 770 | { 771 | "cell_type": "markdown", 772 | "metadata": {}, 773 | "source": [ 774 | "# Thursday Exercises - Answers" 775 | ] 776 | }, 777 | { 778 | "cell_type": "markdown", 779 | "metadata": {}, 780 | "source": [ 781 | "

\n", 782 | "1. Merge Sort: Do some research and try to find out the \"Big-O\" representation for a Merge Sort algorithm.\n", 783 | "

" 784 | ] 785 | }, 786 | { 787 | "cell_type": "markdown", 788 | "metadata": {}, 789 | "source": [ 790 | "

\n", 791 | "Merge sort is O(nLogn)\n", 792 | "

" 793 | ] 794 | }, 795 | { 796 | "cell_type": "markdown", 797 | "metadata": {}, 798 | "source": [ 799 | "

\n", 800 | "2. Binary Search: What is the max number of guesses it would take for a Binary Search to find a number within a list of 10 million numbers?\n", 801 | "

" 802 | ] 803 | }, 804 | { 805 | "cell_type": "code", 806 | "execution_count": 26, 807 | "metadata": { 808 | "collapsed": true 809 | }, 810 | "outputs": [], 811 | "source": [ 812 | "nums = [x for x in range(10000000)]" 813 | ] 814 | }, 815 | { 816 | "cell_type": "code", 817 | "execution_count": 28, 818 | "metadata": {}, 819 | "outputs": [ 820 | { 821 | "name": "stdout", 822 | "output_type": "stream", 823 | "text": [ 824 | "# of items in list: 10000000 \t\t # of guesses: 0\n", 825 | "# of items in list: 5000000 \t\t # of guesses: 1\n", 826 | "# of items in list: 2500000 \t\t # of guesses: 2\n", 827 | "# of items in list: 1250000 \t\t # of guesses: 3\n", 828 | "# of items in list: 625000 \t\t # of guesses: 4\n", 829 | "# of items in list: 312500 \t\t # of guesses: 5\n", 830 | "# of items in list: 156250 \t\t # of guesses: 6\n", 831 | "# of items in list: 78125 \t\t # of guesses: 7\n", 832 | "# of items in list: 39062 \t\t # of guesses: 8\n", 833 | "# of items in list: 19531 \t\t # of guesses: 9\n", 834 | "# of items in list: 9765 \t\t # of guesses: 10\n", 835 | "# of items in list: 4882 \t\t # of guesses: 11\n", 836 | "# of items in list: 2441 \t\t # of guesses: 12\n", 837 | "# of items in list: 1220 \t\t # of guesses: 13\n", 838 | "# of items in list: 610 \t\t # of guesses: 14\n", 839 | "# of items in list: 305 \t\t # of guesses: 15\n", 840 | "# of items in list: 152 \t\t # of guesses: 16\n", 841 | "# of items in list: 76 \t\t # of guesses: 17\n", 842 | "# of items in list: 38 \t\t # of guesses: 18\n", 843 | "# of items in list: 19 \t\t # of guesses: 19\n", 844 | "# of items in list: 9 \t\t # of guesses: 20\n", 845 | "# of items in list: 4 \t\t # of guesses: 21\n", 846 | "# of items in list: 2 \t\t # of guesses: 22\n", 847 | "# of items in list: 1 \t\t # of guesses: 23\n" 848 | ] 849 | }, 850 | { 851 | "data": { 852 | "text/plain": [ 853 | "True" 854 | ] 855 | }, 856 | "execution_count": 28, 857 | "metadata": {}, 858 | "output_type": "execute_result" 859 | } 860 | ], 861 | "source": [ 862 | "def binarySearch(aList, num):\n", 863 | " guesses = 0\n", 864 | " \n", 865 | " while aList:\n", 866 | " print(\"# of items in list: {} \\t\\t # of guesses: {}\".format(len(aList), guesses))\n", 867 | " guesses += 1\n", 868 | " \n", 869 | " mid = len(aList) // 2\n", 870 | "\n", 871 | " if aList[mid] == num:\n", 872 | " return True\n", 873 | " elif aList[mid] > num:\n", 874 | " aList = aList[ : mid ]\n", 875 | " elif aList[mid] < num:\n", 876 | " aList = aList[ mid + 1 : ]\n", 877 | " \n", 878 | " return False\n", 879 | "\n", 880 | "binarySearch(nums, 0)\n", 881 | "\n", 882 | "# the answer is 23" 883 | ] 884 | }, 885 | { 886 | "cell_type": "markdown", 887 | "metadata": {}, 888 | "source": [ 889 | "# End of Week Exercises - Answers" 890 | ] 891 | }, 892 | { 893 | "cell_type": "markdown", 894 | "metadata": {}, 895 | "source": [ 896 | "

\n", 897 | "1. Side Borders: In the Friday project, we ended up creating borders above and below the information printed out. Try adding a star border on the sides as well now.\n", 898 | "

" 899 | ] 900 | }, 901 | { 902 | "cell_type": "code", 903 | "execution_count": 35, 904 | "metadata": {}, 905 | "outputs": [ 906 | { 907 | "name": "stdout", 908 | "output_type": "stream", 909 | "text": [ 910 | "**************************************************\n", 911 | "*\t\tCoding Temple, Inc.\t\t *\n", 912 | "*\t\t283 Franklin St.\t\t *\n", 913 | "*\t\tBoston, Ma\t\t\t *\n", 914 | "*================================================*\n", 915 | "*\tProduct Name\tProduct Price\t\t *\n", 916 | "*\tBooks\t\t$49.95\t\t\t *\n", 917 | "*\tComputer\t$579.99\t\t\t *\n", 918 | "*\tMonitor\t\t$124.89\t\t\t *\n", 919 | "*================================================*\n", 920 | "*\t\t\tTotal\t\t\t *\n", 921 | "*\t\t\t$754.83\t\t\t *\n", 922 | "*================================================*\n", 923 | "*\t\t\t\t\t\t *\n", 924 | "*\tThanks for shopping with us today!\t *\n", 925 | "*\t\t\t\t\t\t *\n", 926 | "**************************************************\n" 927 | ] 928 | } 929 | ], 930 | "source": [ 931 | "# create a product and price for three items\n", 932 | "p1_name, p1_price = 'Books', 49.95\n", 933 | "p2_name, p2_price = 'Computer', 579.99\n", 934 | "p3_name, p3_price = 'Monitor', 124.89\n", 935 | "\n", 936 | "# create a company name and information\n", 937 | "company_name = 'coding temple, inc.'\n", 938 | "company_address = '283 Franklin St.'\n", 939 | "company_city = 'Boston, MA'\n", 940 | "\n", 941 | "# declare ending message\n", 942 | "message = 'Thanks for shopping with us today!'\n", 943 | "\n", 944 | "# create a top border\n", 945 | "print('*' * 50)\n", 946 | "\n", 947 | "# print company information first using format\n", 948 | "print('*\\t\\t{}\\t\\t *'.format(company_name.title()))\n", 949 | "print('*\\t\\t{}\\t\\t *'.format(company_address.title()))\n", 950 | "print('*\\t\\t{}\\t\\t\\t *'.format(company_city.title()))\n", 951 | "\n", 952 | "# print a line between sections\n", 953 | "print('*' + '=' * 48 + '*')\n", 954 | "\n", 955 | "# print out header for section of items\n", 956 | "print('*\\tProduct Name\\tProduct Price\\t\\t *')\n", 957 | "\n", 958 | "# create a print statement for each item\n", 959 | "print('*\\t{}\\t\\t${}\\t\\t\\t *'.format(p1_name.title(), p1_price))\n", 960 | "print('*\\t{}\\t${}\\t\\t\\t *'.format(p2_name.title(), p2_price))\n", 961 | "print('*\\t{}\\t\\t${}\\t\\t\\t *'.format(p3_name.title(), p3_price))\n", 962 | "\n", 963 | "# print a line between sections\n", 964 | "print('*' + '=' * 48 + '*')\n", 965 | "\n", 966 | "# print out header for section of total\n", 967 | "print('*\\t\\t\\tTotal\\t\\t\\t *')\n", 968 | "\n", 969 | "# calculate total price and print out\n", 970 | "total = p1_price + p2_price + p3_price\n", 971 | "print('*\\t\\t\\t${}\\t\\t\\t *'.format(total))\n", 972 | "\n", 973 | "# print a line between sections\n", 974 | "print('*' + '=' * 48 + '*')\n", 975 | "\n", 976 | "# output thank you message\n", 977 | "print('*\\t\\t\\t\\t\\t\\t *\\n*\\t{}\\t *\\n*\\t\\t\\t\\t\\t\\t *'.format(message))\n", 978 | "\n", 979 | "# create a bottom border\n", 980 | "print('*' * 50)" 981 | ] 982 | }, 983 | { 984 | "cell_type": "markdown", 985 | "metadata": {}, 986 | "source": [ 987 | "

\n", 988 | "2. Researching Methods: We've gone over a few of the string manipulation methods that are widely used; however, there's many more, try looking up some and implementing them.\n", 989 | "

" 990 | ] 991 | }, 992 | { 993 | "cell_type": "markdown", 994 | "metadata": {}, 995 | "source": [ 996 | "

\n", 997 | "3. Reverse: Declare a variable equal to \"Hello\". Reverse the string using slicing. Try looking it up if you struggle. Tip: You can define a start, stop, and step when slicing.\n", 998 | "

" 999 | ] 1000 | }, 1001 | { 1002 | "cell_type": "code", 1003 | "execution_count": 16, 1004 | "metadata": {}, 1005 | "outputs": [ 1006 | { 1007 | "name": "stdout", 1008 | "output_type": "stream", 1009 | "text": [ 1010 | "olleH\n" 1011 | ] 1012 | } 1013 | ], 1014 | "source": [ 1015 | "s = \"Hello\"\n", 1016 | "\n", 1017 | "print(s[::-1])" 1018 | ] 1019 | }, 1020 | { 1021 | "cell_type": "code", 1022 | "execution_count": 1, 1023 | "metadata": {}, 1024 | "outputs": [ 1025 | { 1026 | "name": "stdout", 1027 | "output_type": "stream", 1028 | "text": [ 1029 | "worked\n" 1030 | ] 1031 | } 1032 | ], 1033 | "source": [ 1034 | "import time\n", 1035 | "\n", 1036 | "time.sleep(5)\n", 1037 | "\n", 1038 | "print('worked')" 1039 | ] 1040 | } 1041 | ], 1042 | "metadata": { 1043 | "kernelspec": { 1044 | "display_name": "Python 3", 1045 | "language": "python", 1046 | "name": "python3" 1047 | }, 1048 | "language_info": { 1049 | "codemirror_mode": { 1050 | "name": "ipython", 1051 | "version": 3 1052 | }, 1053 | "file_extension": ".py", 1054 | "mimetype": "text/x-python", 1055 | "name": "python", 1056 | "nbconvert_exporter": "python", 1057 | "pygments_lexer": "ipython3", 1058 | "version": "3.6.5" 1059 | } 1060 | }, 1061 | "nbformat": 4, 1062 | "nbformat_minor": 2 1063 | } 1064 | -------------------------------------------------------------------------------- /calculation.py: -------------------------------------------------------------------------------- 1 | def calcArea(length, width): 2 | return length * width -------------------------------------------------------------------------------- /data.csv: -------------------------------------------------------------------------------- 1 | name,language 2 | Dave,Python 3 | Dennis,C 4 | Peter,Java 5 | Jess,Python 6 | -------------------------------------------------------------------------------- /errata.md: -------------------------------------------------------------------------------- 1 | # Errata for *Book Title* 2 | 3 | On **page xx** [Summary of error]: 4 | 5 | Details of error here. Highlight key pieces in **bold**. 6 | 7 | *** 8 | 9 | On **page xx** [Summary of error]: 10 | 11 | Details of error here. Highlight key pieces in **bold**. 12 | 13 | *** -------------------------------------------------------------------------------- /favorite_food.csv: -------------------------------------------------------------------------------- 1 | bacon 2 | bacon 3 | bread 4 | bacon 5 | bacon 6 | bread 7 | -------------------------------------------------------------------------------- /microsoft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/python-projects-for-beginners/73b734b311e18f6f15b7685e0f04b81e441d2ae1/microsoft.png -------------------------------------------------------------------------------- /microsoft_analysis.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/python-projects-for-beginners/73b734b311e18f6f15b7685e0f04b81e441d2ae1/microsoft_analysis.png -------------------------------------------------------------------------------- /numbers.txt: -------------------------------------------------------------------------------- 1 | favorite number is 9 -------------------------------------------------------------------------------- /population.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/python-projects-for-beginners/73b734b311e18f6f15b7685e0f04b81e441d2ae1/population.jpg -------------------------------------------------------------------------------- /site_data/microsoft_frequent_words.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/python-projects-for-beginners/73b734b311e18f6f15b7685e0f04b81e441d2ae1/site_data/microsoft_frequent_words.csv -------------------------------------------------------------------------------- /test.csv: -------------------------------------------------------------------------------- 1 | Name,City 2 | Craig Lou,Taiwan 3 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | # create our own module in a text editor 2 | 3 | # variables to import later 4 | length = 5 5 | width = 10 6 | 7 | # functions to import later 8 | def printInfo(name, age): 9 | print("{} is {} years old.".format(name, age)) 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | this is a test -------------------------------------------------------------------------------- /users.csv: -------------------------------------------------------------------------------- 1 | j@j.com,cat 2 | john@smith.com,red 3 | -------------------------------------------------------------------------------- /week_05.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Creating & Calling Functions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 6, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "Name: John Smith\n", 20 | "Age: 45\n", 21 | "Name: John Smith\n", 22 | "Age: 45\n" 23 | ] 24 | } 25 | ], 26 | "source": [ 27 | "# writing your first function\n", 28 | "\n", 29 | "def printInfo(): # defines what the function does when called\n", 30 | " print('Name: John Smith')\n", 31 | " print('Age: 45')\n", 32 | " \n", 33 | "printInfo() # calls the function to run\n", 34 | "printInfo() # calls the function again" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 7, 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "15\n" 47 | ] 48 | } 49 | ], 50 | "source": [ 51 | "# performing a calculation in a function\n", 52 | "\n", 53 | "def calc():\n", 54 | " x, y = 5, 10\n", 55 | " print(x + y)\n", 56 | " \n", 57 | "calc() # will run the block of code within calc and output 15" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "# Parameters" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": 8, 70 | "metadata": {}, 71 | "outputs": [ 72 | { 73 | "name": "stdout", 74 | "output_type": "stream", 75 | "text": [ 76 | "Your name is: John Smith\n", 77 | "Your name is: Amanda\n" 78 | ] 79 | } 80 | ], 81 | "source": [ 82 | "# passing a single parameter into a function\n", 83 | "\n", 84 | "def printName(full_name):\n", 85 | " print('Your name is: {}'.format(full_name))\n", 86 | "\n", 87 | "printName('John Smith')\n", 88 | "printName('Amanda')" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 9, 94 | "metadata": {}, 95 | "outputs": [ 96 | { 97 | "name": "stdout", 98 | "output_type": "stream", 99 | "text": [ 100 | "5 + 8 = 13\n", 101 | "3.5 + 5.5 = 9.0\n" 102 | ] 103 | } 104 | ], 105 | "source": [ 106 | "# passing multiple parameters into a function\n", 107 | "\n", 108 | "def addNums(num1, num2):\n", 109 | " result = num1 + num2\n", 110 | " print('{} + {} = {}'.format(num1, num2, result))\n", 111 | " \n", 112 | "addNums(5, 8) # will output 13\n", 113 | "addNums(3.5, 5.5) # will output 9.0" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 10, 119 | "metadata": {}, 120 | "outputs": [ 121 | { 122 | "name": "stdout", 123 | "output_type": "stream", 124 | "text": [ 125 | "4\n", 126 | "16\n", 127 | "25\n", 128 | "100\n", 129 | "1\n", 130 | "9\n", 131 | "36\n" 132 | ] 133 | } 134 | ], 135 | "source": [ 136 | "# using a function to square all information\n", 137 | "\n", 138 | "numbers1 = [2, 4, 5, 10]\n", 139 | "numbers2 = [1, 3, 6]\n", 140 | "\n", 141 | "def squares(nums):\n", 142 | " for num in nums:\n", 143 | " print(num**2)\n", 144 | " \n", 145 | "squares(numbers1)\n", 146 | "squares(numbers2)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": 11, 152 | "metadata": {}, 153 | "outputs": [ 154 | { 155 | "name": "stdout", 156 | "output_type": "stream", 157 | "text": [ 158 | "Area: 12.56\n" 159 | ] 160 | } 161 | ], 162 | "source": [ 163 | "# setting default parameter values\n", 164 | "\n", 165 | "def calcArea(r, pi=3.14):\n", 166 | " area = pi * (r**2)\n", 167 | " print('Area: {}'.format(area))\n", 168 | " \n", 169 | "calcArea(2) # assuming radius is the value of 2" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 12, 175 | "metadata": {}, 176 | "outputs": [ 177 | { 178 | "name": "stdout", 179 | "output_type": "stream", 180 | "text": [ 181 | "John Smith\n", 182 | "John Paul Smith\n" 183 | ] 184 | } 185 | ], 186 | "source": [ 187 | "# setting default parameter values\n", 188 | "\n", 189 | "def printName(first, last, middle=''):\n", 190 | " if middle:\n", 191 | " print('{} {} {}'.format(first, middle, last))\n", 192 | " else:\n", 193 | " print('{} {}'.format(first, last))\n", 194 | " \n", 195 | "printName('John', 'Smith')\n", 196 | "printName('John', 'Smith', 'Paul') # will output with middle name" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": 18, 202 | "metadata": {}, 203 | "outputs": [ 204 | { 205 | "name": "stdout", 206 | "output_type": "stream", 207 | "text": [ 208 | "2.5\n", 209 | "5\n" 210 | ] 211 | } 212 | ], 213 | "source": [ 214 | "# explicity assigning values to parameters by referncing the name\n", 215 | "\n", 216 | "def addNums(num1, num2):\n", 217 | " print(num2)\n", 218 | " print(num1)\n", 219 | " \n", 220 | "addNums(5, num2 = 2.5)" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 4, 226 | "metadata": { 227 | "scrolled": true 228 | }, 229 | "outputs": [ 230 | { 231 | "name": "stdout", 232 | "output_type": "stream", 233 | "text": [ 234 | "\n", 235 | "5\n", 236 | "True\n", 237 | "Jess\n" 238 | ] 239 | } 240 | ], 241 | "source": [ 242 | "# using args parameter to take in a tuple of arbitrary values\n", 243 | "\n", 244 | "def outputData(name, *args):\n", 245 | " print(type(args))\n", 246 | " \n", 247 | " for arg in args:\n", 248 | " print(arg)\n", 249 | " \n", 250 | "outputData(\"John Smith\", 5, True, \"Jess\")" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 7, 256 | "metadata": {}, 257 | "outputs": [ 258 | { 259 | "name": "stdout", 260 | "output_type": "stream", 261 | "text": [ 262 | "\n", 263 | "John Smith\n", 264 | "5\n" 265 | ] 266 | } 267 | ], 268 | "source": [ 269 | "# using kwargs parameter to take in a dictionary of arbitrary values\n", 270 | "\n", 271 | "def outputData(**kwargs):\n", 272 | " print(type(kwargs))\n", 273 | " \n", 274 | " print(kwargs[\"name\"])\n", 275 | " print(kwargs[\"num\"])\n", 276 | " \n", 277 | "outputData(name = \"John Smith\", num = 5, b = True)" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "# Return Statement" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 20, 290 | "metadata": {}, 291 | "outputs": [ 292 | { 293 | "name": "stdout", 294 | "output_type": "stream", 295 | "text": [ 296 | "10.0\n", 297 | "20\n" 298 | ] 299 | } 300 | ], 301 | "source": [ 302 | "# using return keyword to return the sum of two numbers\n", 303 | "\n", 304 | "def addNums(num1, num2):\n", 305 | " return num1 + num2\n", 306 | "\n", 307 | "num = addNums(5.5, 4.5) # saves returned value into num\n", 308 | "\n", 309 | "print(num)\n", 310 | "\n", 311 | "print(addNums(10, 10)) # doesn't save returned value" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": 22, 317 | "metadata": {}, 318 | "outputs": [ 319 | { 320 | "name": "stdout", 321 | "output_type": "stream", 322 | "text": [ 323 | "True\n" 324 | ] 325 | } 326 | ], 327 | "source": [ 328 | "# shorthand syntax using a ternary operator\n", 329 | "\n", 330 | "def searchList(aList, el):\n", 331 | " return True if el in aList else False\n", 332 | "\n", 333 | "result = searchList(['one', 2, 'three'], 2) # result = True\n", 334 | "\n", 335 | "print(result)" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": {}, 341 | "source": [ 342 | "# Scope" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 9, 348 | "metadata": {}, 349 | "outputs": [ 350 | { 351 | "ename": "UnboundLocalError", 352 | "evalue": "local variable 'number' referenced before assignment", 353 | "output_type": "error", 354 | "traceback": [ 355 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 356 | "\u001b[1;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", 357 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[0mnumber\u001b[0m \u001b[1;33m+=\u001b[0m \u001b[1;36m1\u001b[0m \u001b[1;31m# not accessible due to function level scope\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m \u001b[0mscopeTest\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 358 | "\u001b[1;32m\u001b[0m in \u001b[0;36mscopeTest\u001b[1;34m()\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mscopeTest\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0mnumber\u001b[0m \u001b[1;33m+=\u001b[0m \u001b[1;36m1\u001b[0m \u001b[1;31m# not accessible due to function level scope\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mscopeTest\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 359 | "\u001b[1;31mUnboundLocalError\u001b[0m: local variable 'number' referenced before assignment" 360 | ] 361 | } 362 | ], 363 | "source": [ 364 | "# where global variables can be accessed\n", 365 | "\n", 366 | "number = 5\n", 367 | "\n", 368 | "def scopeTest():\n", 369 | " number += 1 # not accessible due to function level scope\n", 370 | " \n", 371 | "scopeTest()" 372 | ] 373 | }, 374 | { 375 | "cell_type": "code", 376 | "execution_count": 23, 377 | "metadata": {}, 378 | "outputs": [ 379 | { 380 | "name": "stdout", 381 | "output_type": "stream", 382 | "text": [ 383 | "function\n" 384 | ] 385 | } 386 | ], 387 | "source": [ 388 | "# accessing variables defined in a function\n", 389 | "\n", 390 | "def scopeTest():\n", 391 | " word = 'function'\n", 392 | " return word\n", 393 | "\n", 394 | "value = scopeTest()\n", 395 | "\n", 396 | "print(value)" 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": 27, 402 | "metadata": {}, 403 | "outputs": [ 404 | { 405 | "name": "stdout", 406 | "output_type": "stream", 407 | "text": [ 408 | "Before Altering: ['baseball', 'football', 'hockey', 'basketball']\n", 409 | "After Altering: ['soccer', 'football', 'hockey', 'basketball']\n" 410 | ] 411 | } 412 | ], 413 | "source": [ 414 | "# changing list item values by index\n", 415 | "\n", 416 | "sports = ['baseball', 'football', 'hockey', 'basketball']\n", 417 | "\n", 418 | "def change(aList):\n", 419 | " aList[0] = 'soccer'\n", 420 | " \n", 421 | "print('Before Altering: {}'.format(sports))\n", 422 | "\n", 423 | "change(sports)\n", 424 | "\n", 425 | "print('After Altering: {}'.format(sports))" 426 | ] 427 | }, 428 | { 429 | "cell_type": "markdown", 430 | "metadata": {}, 431 | "source": [ 432 | "# Friday Project: Creating a Shopping Cart" 433 | ] 434 | }, 435 | { 436 | "cell_type": "code", 437 | "execution_count": 7, 438 | "metadata": {}, 439 | "outputs": [ 440 | { 441 | "name": "stdout", 442 | "output_type": "stream", 443 | "text": [ 444 | "Your cart is empty.\n" 445 | ] 446 | } 447 | ], 448 | "source": [ 449 | "# import necessary functions\n", 450 | "from IPython.display import clear_output\n", 451 | "\n", 452 | "# global list variable\n", 453 | "cart = []\n", 454 | "\n", 455 | "# create function to add items to cart\n", 456 | "def addItem(item):\n", 457 | " clear_output()\n", 458 | " cart.append(item)\n", 459 | " print('{} has been added.'.format(item))\n", 460 | "\n", 461 | "# create function to remove items from cart\n", 462 | "def removeItem(item):\n", 463 | " clear_output()\n", 464 | " try:\n", 465 | " cart.remove(item)\n", 466 | " print('{} has been removed.'.format(item))\n", 467 | " except:\n", 468 | " print('Sorry we could not remove that item.')\n", 469 | " \n", 470 | "# create function to show items in cart\n", 471 | "def showCart():\n", 472 | " clear_output()\n", 473 | " if cart:\n", 474 | " print('Here is your cart:')\n", 475 | " for item in cart:\n", 476 | " print('- {}'.format(item))\n", 477 | " else:\n", 478 | " print('Your cart is empty.')\n", 479 | "\n", 480 | "# create function to clear items from cart\n", 481 | "def clearCart():\n", 482 | " clear_output()\n", 483 | " cart.clear()\n", 484 | " print('Your cart is empty.')\n", 485 | "\n", 486 | "# create main function that loops until the user quits\n", 487 | "def main():\n", 488 | " done = False\n", 489 | " \n", 490 | " while not done:\n", 491 | " ans = input('quit/add/remove/show/clear: ').lower()\n", 492 | " \n", 493 | " # base case\n", 494 | " if ans == 'quit':\n", 495 | " print('Thanks for using our program.')\n", 496 | " showCart()\n", 497 | " done = True\n", 498 | " elif ans == 'add':\n", 499 | " item = input('What would you like to add? ').title()\n", 500 | " addItem(item)\n", 501 | " elif ans == 'remove':\n", 502 | " showCart()\n", 503 | " item = input('What item would you like to remove? ').title()\n", 504 | " removeItem(item)\n", 505 | " elif ans == 'show':\n", 506 | " showCart()\n", 507 | " elif ans == 'clear':\n", 508 | " clearCart()\n", 509 | " else:\n", 510 | " print('Sorry that was not an option.')\n", 511 | "\n", 512 | "main() # run the program" 513 | ] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "metadata": {}, 518 | "source": [ 519 | "# Monday Exercises - Answers" 520 | ] 521 | }, 522 | { 523 | "cell_type": "markdown", 524 | "metadata": {}, 525 | "source": [ 526 | "

\n", 527 | "1. Print Name: Define a function called myName, and have it print out your name when called.\n", 528 | "

" 529 | ] 530 | }, 531 | { 532 | "cell_type": "code", 533 | "execution_count": 1, 534 | "metadata": {}, 535 | "outputs": [ 536 | { 537 | "name": "stdout", 538 | "output_type": "stream", 539 | "text": [ 540 | "Connor P. Milliken\n" 541 | ] 542 | } 543 | ], 544 | "source": [ 545 | "def myName():\n", 546 | " print(\"Connor P. Milliken\")\n", 547 | " \n", 548 | "myName()" 549 | ] 550 | }, 551 | { 552 | "cell_type": "markdown", 553 | "metadata": {}, 554 | "source": [ 555 | "

\n", 556 | "2. Pizza Toppings: Define a function that prints out all your favorite pizza toppings called pizzaToppings. Call the function three times.\n", 557 | "

" 558 | ] 559 | }, 560 | { 561 | "cell_type": "code", 562 | "execution_count": 2, 563 | "metadata": {}, 564 | "outputs": [ 565 | { 566 | "name": "stdout", 567 | "output_type": "stream", 568 | "text": [ 569 | "Cheese, Bacon\n", 570 | "Cheese, Bacon\n", 571 | "Cheese, Bacon\n" 572 | ] 573 | } 574 | ], 575 | "source": [ 576 | "def pizzaToppings():\n", 577 | " print(\"Cheese, Bacon\")\n", 578 | " \n", 579 | "pizzaToppings()\n", 580 | "pizzaToppings()\n", 581 | "pizzaToppings()" 582 | ] 583 | }, 584 | { 585 | "cell_type": "markdown", 586 | "metadata": {}, 587 | "source": [ 588 | "# Tuesday Exercises - Answers" 589 | ] 590 | }, 591 | { 592 | "cell_type": "markdown", 593 | "metadata": {}, 594 | "source": [ 595 | "

\n", 596 | "1. User Input: Ask the user to input a word and pass that word into a function that checks if the word starts with an uppercase. If it does output \"True\" otherwise \"False\".\n", 597 | "

" 598 | ] 599 | }, 600 | { 601 | "cell_type": "code", 602 | "execution_count": 4, 603 | "metadata": {}, 604 | "outputs": [ 605 | { 606 | "name": "stdout", 607 | "output_type": "stream", 608 | "text": [ 609 | "Enter a word: yes\n", 610 | "False\n" 611 | ] 612 | } 613 | ], 614 | "source": [ 615 | "def checkUppercase(word):\n", 616 | " if word[0] == word[0].upper():\n", 617 | " print(True)\n", 618 | " else:\n", 619 | " print(False)\n", 620 | " \n", 621 | "ans = input(\"Enter a word: \")\n", 622 | "\n", 623 | "checkUppercase(ans)" 624 | ] 625 | }, 626 | { 627 | "cell_type": "markdown", 628 | "metadata": {}, 629 | "source": [ 630 | "

\n", 631 | "2. No Name: Define a function that takes in two arguments; first_name, last_name and makes both optional. If no values are passed into the parameters, it should output \"No name passed in\", otherwise it should print out the name.\n", 632 | "

" 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": 6, 638 | "metadata": {}, 639 | "outputs": [ 640 | { 641 | "name": "stdout", 642 | "output_type": "stream", 643 | "text": [ 644 | "No name passed in.\n", 645 | "Connor \n", 646 | "Connor Milliken\n" 647 | ] 648 | } 649 | ], 650 | "source": [ 651 | "def outputName(first_name='', last_name=''):\n", 652 | " if not first_name and not last_name:\n", 653 | " print(\"No name passed in.\")\n", 654 | " else:\n", 655 | " print(first_name, last_name)\n", 656 | " \n", 657 | "outputName()\n", 658 | "outputName('Connor')\n", 659 | "outputName('Connor', 'Milliken')" 660 | ] 661 | }, 662 | { 663 | "cell_type": "markdown", 664 | "metadata": {}, 665 | "source": [ 666 | "# Wednesday Exercises - Answers" 667 | ] 668 | }, 669 | { 670 | "cell_type": "markdown", 671 | "metadata": {}, 672 | "source": [ 673 | "

\n", 674 | "1. Full Name: Create a function that takes in a first and last name and returns the two names joined together.\n", 675 | "

" 676 | ] 677 | }, 678 | { 679 | "cell_type": "code", 680 | "execution_count": 7, 681 | "metadata": {}, 682 | "outputs": [ 683 | { 684 | "data": { 685 | "text/plain": [ 686 | "'Connor Milliken'" 687 | ] 688 | }, 689 | "execution_count": 7, 690 | "metadata": {}, 691 | "output_type": "execute_result" 692 | } 693 | ], 694 | "source": [ 695 | "def combineNames(first, last):\n", 696 | " return first + ' ' + last\n", 697 | "\n", 698 | "combineNames('Connor', 'Milliken')" 699 | ] 700 | }, 701 | { 702 | "cell_type": "markdown", 703 | "metadata": {}, 704 | "source": [ 705 | "

\n", 706 | "2. User Input: Within a function, ask for user input. Have this function return that input to be stored in a variable outside of the function. Then print out the input.\n", 707 | "

" 708 | ] 709 | }, 710 | { 711 | "cell_type": "code", 712 | "execution_count": 8, 713 | "metadata": {}, 714 | "outputs": [ 715 | { 716 | "name": "stdout", 717 | "output_type": "stream", 718 | "text": [ 719 | "Enter a word: Hello!\n", 720 | "Hello!\n" 721 | ] 722 | } 723 | ], 724 | "source": [ 725 | "def returnFunc():\n", 726 | " return input('Enter a word: ')\n", 727 | "\n", 728 | "ans = returnFunc()\n", 729 | "\n", 730 | "print(ans)" 731 | ] 732 | }, 733 | { 734 | "cell_type": "markdown", 735 | "metadata": {}, 736 | "source": [ 737 | "# Thursday Exercises - Answers" 738 | ] 739 | }, 740 | { 741 | "cell_type": "markdown", 742 | "metadata": {}, 743 | "source": [ 744 | "

\n", 745 | "1. Names: Create a function that will change the list passed in with a parameter of name at a given index. Such that if I were to pass in \"Bill\" and index 1 it would change \"Rich\" to \"Bill\". Use the list and function definition below:\n", 746 | "

\n", 747 | "\n", 748 | "

\n", 749 | ">>> names = [\"Bob\", \"Rich\", \"Amanda\"]
\n", 750 | ">>> def changeValue(aList, name, index):\n", 751 | "

" 752 | ] 753 | }, 754 | { 755 | "cell_type": "code", 756 | "execution_count": 11, 757 | "metadata": {}, 758 | "outputs": [ 759 | { 760 | "name": "stdout", 761 | "output_type": "stream", 762 | "text": [ 763 | "['Bob', 'Bill', 'Amanda']\n" 764 | ] 765 | } 766 | ], 767 | "source": [ 768 | "names = [\"Bob\", \"Rich\", \"Amanda\"]\n", 769 | "\n", 770 | "def changeValue(aList, name, index):\n", 771 | " aList[index] = name\n", 772 | " \n", 773 | "changeValue(names, \"Bill\", 1)\n", 774 | "\n", 775 | "print(names)" 776 | ] 777 | }, 778 | { 779 | "cell_type": "markdown", 780 | "metadata": {}, 781 | "source": [ 782 | "# End of Week Exercises - Answers" 783 | ] 784 | }, 785 | { 786 | "cell_type": "markdown", 787 | "metadata": {}, 788 | "source": [ 789 | "

\n", 790 | "1. Re-Factor Hangman: This is a large task, so tread lightly, but try to re-factor the Hangman project from last week to use functions. Think about what actions Hangman requires and turn those tasks into functions.\n", 791 | "

" 792 | ] 793 | }, 794 | { 795 | "cell_type": "code", 796 | "execution_count": 1, 797 | "metadata": {}, 798 | "outputs": [ 799 | { 800 | "name": "stdout", 801 | "output_type": "stream", 802 | "text": [ 803 | "You guessed correctly!\n", 804 | "Congratulations, you guessed it correctly!\n" 805 | ] 806 | } 807 | ], 808 | "source": [ 809 | "# import additional functions\n", 810 | "from random import choice\n", 811 | "from IPython.display import clear_output\n", 812 | "\n", 813 | "\n", 814 | "def checkGameCondition(lives, guesses, word):\n", 815 | " if lives <= 0:\n", 816 | " print('You lost all your lives, you lost!')\n", 817 | " return True\n", 818 | " elif word == ''.join(guesses):\n", 819 | " print('Congratulations, you guessed it correctly!')\n", 820 | " return True\n", 821 | " \n", 822 | " return False\n", 823 | "\n", 824 | "def checkGuess(ans, word, guesses, guessed, lives):\n", 825 | " game_over = False\n", 826 | " \n", 827 | " if ans == 'quit':\n", 828 | " print('Thanks for playing.')\n", 829 | " game_over = True\n", 830 | " elif ans in word and ans not in guessed:\n", 831 | " print('You guessed correctly!')\n", 832 | "\n", 833 | " # create a loop to change underscore to proper letter\n", 834 | " for i in range(len(word)):\n", 835 | " if word[i] == ans:\n", 836 | " guesses[i] = ans\n", 837 | " elif ans in guessed:\n", 838 | " print('You already guessed that. Try again.')\n", 839 | " else: # otherwise lose life\n", 840 | " lives -= 1\n", 841 | " print('Incorrect, you lost a life.')\n", 842 | "\n", 843 | " if ans not in guessed:\n", 844 | " guessed.append(ans) # add guess to guessed list\n", 845 | " \n", 846 | " return game_over, guesses, guessed, lives\n", 847 | "\n", 848 | "def outputGameInfo(guesses, guessed, lives):\n", 849 | " hidden_word = ''.join(guesses)\n", 850 | " print('Your guessed letters: {}'.format(guessed))\n", 851 | " print('Word to guess: {}'.format(hidden_word))\n", 852 | " print('Lives: {}'.format(lives))\n", 853 | "\n", 854 | "\n", 855 | "\n", 856 | "def gamePlay():\n", 857 | " # declare game variables\n", 858 | " words = ['tree', 'basket', 'chair', 'paper', 'python']\n", 859 | " word = choice(words)\n", 860 | " guessed, lives, game_over = [], 7, False\n", 861 | "\n", 862 | " # create a list of underscores to the length of the word\n", 863 | " guesses = ['_ '] * len(word)\n", 864 | "\n", 865 | " # create main game loop\n", 866 | " while not game_over:\n", 867 | " # output game information\n", 868 | " outputGameInfo(guesses, guessed, lives)\n", 869 | "\n", 870 | " ans = input('Type quit or guess a letter: ').lower()\n", 871 | "\n", 872 | " clear_output() # clear all previous output\n", 873 | "\n", 874 | " game_over, guesses, guessed, lives = checkGuess(ans, word, guesses, guessed, lives)\n", 875 | "\n", 876 | " game_over = checkGameCondition(lives, guesses, word)\n", 877 | " \n", 878 | "gamePlay()" 879 | ] 880 | }, 881 | { 882 | "cell_type": "markdown", 883 | "metadata": {}, 884 | "source": [ 885 | "

\n", 886 | "2. Removing by Index: In the shopping cart program, setup the remove function so that you can remove via the index as well. Set the list up so that it prints out as a numbered list, and when asked to remove an item the user can also type out a number next to the list item. For example, using the following you can type '1' to remove \"Grapes\":\n", 887 | "

\n", 888 | "\n", 889 | "

\n", 890 | ">>> 1) Grapes
\n", 891 | ">>> What would you like to remove? 1\n", 892 | "

" 893 | ] 894 | }, 895 | { 896 | "cell_type": "code", 897 | "execution_count": 18, 898 | "metadata": {}, 899 | "outputs": [ 900 | { 901 | "name": "stdout", 902 | "output_type": "stream", 903 | "text": [ 904 | "Here is your cart:\n", 905 | "1) Hat\n" 906 | ] 907 | } 908 | ], 909 | "source": [ 910 | "# import necessary functions\n", 911 | "from IPython.display import clear_output\n", 912 | "\n", 913 | "# global list variable\n", 914 | "cart = []\n", 915 | "\n", 916 | "# create function to add items to cart\n", 917 | "def addItem(item):\n", 918 | " clear_output()\n", 919 | " cart.append(item)\n", 920 | " print('{} has been added.'.format(item))\n", 921 | "\n", 922 | "# create function to remove items from cart\n", 923 | "def removeItem(item):\n", 924 | " clear_output()\n", 925 | " try:\n", 926 | " if item.isdigit():\n", 927 | " item_removed = cart.pop(int(item) - 1)\n", 928 | " print('{} has been removed.'.format(item_removed))\n", 929 | " else:\n", 930 | " cart.remove(item)\n", 931 | " print('{} has been removed.'.format(item))\n", 932 | " except:\n", 933 | " print('Sorry we could not remove that item.')\n", 934 | " \n", 935 | "# create function to show items in cart\n", 936 | "def showCart():\n", 937 | " clear_output()\n", 938 | " if cart:\n", 939 | " print('Here is your cart:')\n", 940 | " for i in range(len(cart)):\n", 941 | " print('{}) {}'.format(i + 1, cart[i]))\n", 942 | " else:\n", 943 | " print('Your cart is empty.')\n", 944 | "\n", 945 | "# create function to clear items from cart\n", 946 | "def clearCart():\n", 947 | " clear_output()\n", 948 | " cart.clear()\n", 949 | " print('Your cart is empty.')\n", 950 | "\n", 951 | "# create main function that loops until the user quits\n", 952 | "def main():\n", 953 | " done = False\n", 954 | " \n", 955 | " while not done:\n", 956 | " ans = input('quit/add/remove/show/clear: ').lower()\n", 957 | " \n", 958 | " # base case\n", 959 | " if ans == 'quit':\n", 960 | " print('Thanks for using our program.')\n", 961 | " showCart()\n", 962 | " done = True\n", 963 | " elif ans == 'add':\n", 964 | " item = input('What would you like to add? ').title()\n", 965 | " addItem(item)\n", 966 | " elif ans == 'remove':\n", 967 | " showCart()\n", 968 | " item = input('What item would you like to remove? ').title()\n", 969 | " removeItem(item)\n", 970 | " elif ans == 'show':\n", 971 | " showCart()\n", 972 | " elif ans == 'clear':\n", 973 | " clearCart()\n", 974 | " else:\n", 975 | " print('Sorry that was not an option.')\n", 976 | "\n", 977 | "main() # run the program" 978 | ] 979 | } 980 | ], 981 | "metadata": { 982 | "kernelspec": { 983 | "display_name": "Python 3", 984 | "language": "python", 985 | "name": "python3" 986 | }, 987 | "language_info": { 988 | "codemirror_mode": { 989 | "name": "ipython", 990 | "version": 3 991 | }, 992 | "file_extension": ".py", 993 | "mimetype": "text/x-python", 994 | "name": "python", 995 | "nbconvert_exporter": "python", 996 | "pygments_lexer": "ipython3", 997 | "version": "3.6.5" 998 | } 999 | }, 1000 | "nbformat": 4, 1001 | "nbformat_minor": 2 1002 | } 1003 | -------------------------------------------------------------------------------- /week_06.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Dictionaries" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 2, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "{'name': 'Morty', 'age': 26}\n" 20 | ] 21 | } 22 | ], 23 | "source": [ 24 | "# declaring a dictionary variable\n", 25 | "\n", 26 | "empty = {} # empty dictionary\n", 27 | "\n", 28 | "person = { 'name' : 'John Smith' } # dictionary with one key/value pair\n", 29 | "\n", 30 | "customer = {\n", 31 | " 'name' : 'Morty',\n", 32 | " 'age' : 26\n", 33 | "} # dictionary with two key/value pairs\n", 34 | "\n", 35 | "print(customer)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 3, 41 | "metadata": {}, 42 | "outputs": [ 43 | { 44 | "name": "stdout", 45 | "output_type": "stream", 46 | "text": [ 47 | "John\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "# accessing dictionary information through keys\n", 53 | "\n", 54 | "person = { 'name' : 'John' }\n", 55 | "\n", 56 | "print( person['name'] ) # access information through the key" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 4, 62 | "metadata": {}, 63 | "outputs": [ 64 | { 65 | "name": "stdout", 66 | "output_type": "stream", 67 | "text": [ 68 | "John\n", 69 | "Age is not available.\n" 70 | ] 71 | } 72 | ], 73 | "source": [ 74 | "# using the get method to access dictionary information\n", 75 | "\n", 76 | "person = { 'name' : 'John' }\n", 77 | "\n", 78 | "print( person.get('name') ) # retrieves value of name key as before\n", 79 | "\n", 80 | "print( person.get('age', 'Age is not available.') ) # get is a secure way to retrieve information" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": 5, 86 | "metadata": {}, 87 | "outputs": [ 88 | { 89 | "name": "stdout", 90 | "output_type": "stream", 91 | "text": [ 92 | "baseball\n" 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "# storing a list within a dictionary and accessing it\n", 98 | "\n", 99 | "data = { 'sports' : ['baseball', 'football', 'hockey', 'soccer'] }\n", 100 | "\n", 101 | "print( data['sports'][0] ) # first access the key, then the index" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 24, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "ename": "ValueError", 111 | "evalue": "dictionary update sequence element #0 has length 8; 2 is required", 112 | "output_type": "error", 113 | "traceback": [ 114 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 115 | "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", 116 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0msports\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m[\u001b[0m \u001b[1;34m\"baseball\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"football\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"hockey\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"soccer\"\u001b[0m \u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0msports_dict\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mdict\u001b[0m\u001b[1;33m(\u001b[0m \u001b[0msports\u001b[0m \u001b[1;33m)\u001b[0m \u001b[1;31m# will produce error, no key\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 117 | "\u001b[1;31mValueError\u001b[0m: dictionary update sequence element #0 has length 8; 2 is required" 118 | ] 119 | } 120 | ], 121 | "source": [ 122 | "# improperly storing a list within a dictionary\n", 123 | "\n", 124 | "sports = [ \"baseball\", \"football\", \"hockey\", \"soccer\" ]\n", 125 | "\n", 126 | "sports_dict = dict( sports ) # will produce error, no key" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 6, 132 | "metadata": {}, 133 | "outputs": [ 134 | { 135 | "name": "stdout", 136 | "output_type": "stream", 137 | "text": [ 138 | "{'name': 'Kirsten'}\n", 139 | "Kirsten\n" 140 | ] 141 | } 142 | ], 143 | "source": [ 144 | "# storing a dictionary within a list and accessing it\n", 145 | "\n", 146 | "data = ['John', 'Dennis', {'name' : 'Kirsten'}]\n", 147 | "\n", 148 | "print( data[2] ) # the dictionary is in index 2\n", 149 | "\n", 150 | "print( data[2]['name'] ) # first access the index, then access the key" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": 7, 156 | "metadata": {}, 157 | "outputs": [ 158 | { 159 | "name": "stdout", 160 | "output_type": "stream", 161 | "text": [ 162 | "{'2018': 108, '2017': 93}\n", 163 | "108\n" 164 | ] 165 | } 166 | ], 167 | "source": [ 168 | "# storing a dictionary within a dictionary and accessing it\n", 169 | "\n", 170 | "data = {\n", 171 | " 'team' : 'Boston Red Sox',\n", 172 | " 'wins' : { '2018' : 108, '2017' : 93 }\n", 173 | "}\n", 174 | "\n", 175 | "print( data['wins'] ) # will output the dictionary within the wins key\n", 176 | "\n", 177 | "print( data['wins']['2018'] ) # first access the wins key, then the next key" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "metadata": {}, 183 | "source": [ 184 | "# Working with Dictionaries" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 11, 190 | "metadata": {}, 191 | "outputs": [ 192 | { 193 | "name": "stdout", 194 | "output_type": "stream", 195 | "text": [ 196 | "Year: 2018\tColor: Blue\n" 197 | ] 198 | } 199 | ], 200 | "source": [ 201 | "# adding new key/value pairs to a dictionary\n", 202 | "\n", 203 | "car = { 'year' : 2018 }\n", 204 | "\n", 205 | "car['color'] = 'Blue'\n", 206 | "\n", 207 | "print(\"Year: {}\\tColor: {}\".format(car['year'], car['color']))" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": 12, 213 | "metadata": {}, 214 | "outputs": [ 215 | { 216 | "name": "stdout", 217 | "output_type": "stream", 218 | "text": [ 219 | "Year: 2018\tColor: Red\n" 220 | ] 221 | } 222 | ], 223 | "source": [ 224 | "# updating a value for a key/value pair that already exists\n", 225 | "\n", 226 | "car = { 'year' : 2018, 'color' : 'Blue' }\n", 227 | "\n", 228 | "car['color'] = 'Red'\n", 229 | "\n", 230 | "print(\"Year: {}\\tColor: {}\".format(car['year'], car['color']))" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": 13, 236 | "metadata": {}, 237 | "outputs": [ 238 | { 239 | "name": "stdout", 240 | "output_type": "stream", 241 | "text": [ 242 | "{}\n" 243 | ] 244 | } 245 | ], 246 | "source": [ 247 | "# deleting a key/value pair from a dictionary\n", 248 | "\n", 249 | "car = { 'year' : 2018 }\n", 250 | "\n", 251 | "try:\n", 252 | " del car['year']\n", 253 | " print(car)\n", 254 | "except:\n", 255 | " print('That key does not exist')" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": 14, 261 | "metadata": {}, 262 | "outputs": [ 263 | { 264 | "name": "stdout", 265 | "output_type": "stream", 266 | "text": [ 267 | "name\n", 268 | "John\n", 269 | "age\n", 270 | "26\n" 271 | ] 272 | } 273 | ], 274 | "source": [ 275 | "# looping over a dictionary via the keys\n", 276 | "\n", 277 | "person = { 'name' : 'John', 'age' : 26 }\n", 278 | "\n", 279 | "for key in person.keys():\n", 280 | " print(key)\n", 281 | " print(person[key]) # will output the value at the current key" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 15, 287 | "metadata": {}, 288 | "outputs": [ 289 | { 290 | "name": "stdout", 291 | "output_type": "stream", 292 | "text": [ 293 | "John\n", 294 | "26\n" 295 | ] 296 | } 297 | ], 298 | "source": [ 299 | "# looping over a dictionary via the values\n", 300 | "\n", 301 | "person = { 'name' : 'John', 'age' : 26 }\n", 302 | "\n", 303 | "for value in person.values():\n", 304 | " print(value)" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": 16, 310 | "metadata": {}, 311 | "outputs": [ 312 | { 313 | "name": "stdout", 314 | "output_type": "stream", 315 | "text": [ 316 | "name: John\n", 317 | "age: 26\n" 318 | ] 319 | } 320 | ], 321 | "source": [ 322 | "# looping over a dictionary via the key/value pair\n", 323 | "\n", 324 | "person = { 'name' : 'John', 'age' : 26 }\n", 325 | "\n", 326 | "for key, value in person.items():\n", 327 | " print(\"{}: {}\".format(key, value))" 328 | ] 329 | }, 330 | { 331 | "cell_type": "markdown", 332 | "metadata": {}, 333 | "source": [ 334 | "# Tuples, Sets, Frozensets" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": 20, 340 | "metadata": {}, 341 | "outputs": [ 342 | { 343 | "name": "stdout", 344 | "output_type": "stream", 345 | "text": [ 346 | " \n" 347 | ] 348 | }, 349 | { 350 | "ename": "TypeError", 351 | "evalue": "'tuple' object does not support item assignment", 352 | "output_type": "error", 353 | "traceback": [ 354 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 355 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 356 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m \u001b[0mtype\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mt1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mtype\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mt2\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m)\u001b[0m \u001b[1;31m# both are tuples\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[0mt1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m1\u001b[0m \u001b[1;31m# will crash, tuples are immutable once declared\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 357 | "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" 358 | ] 359 | } 360 | ], 361 | "source": [ 362 | "# declaring a tuple\n", 363 | "\n", 364 | "t1 = (\"hello\", 2, \"hello\") # with parens\n", 365 | "\n", 366 | "t2 = True, 1 # without parens\n", 367 | "\n", 368 | "print( type(t1), type(t2) ) # both are tuples\n", 369 | "\n", 370 | "t1[0] = 1 # will crash, tuples are immutable once declared" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": 23, 376 | "metadata": {}, 377 | "outputs": [ 378 | { 379 | "name": "stdout", 380 | "output_type": "stream", 381 | "text": [ 382 | "{2, 3, 5}\n" 383 | ] 384 | } 385 | ], 386 | "source": [ 387 | "# declaring a set\n", 388 | "\n", 389 | "s1 = set( [1, 2, 3, 1] ) # uses the set keyword\n", 390 | "\n", 391 | "s2 = {4, 4, 5} # uses curly brackets, like dictionary\n", 392 | "\n", 393 | "s1.add(5) # using the add method to add new items to a set\n", 394 | "\n", 395 | "s1.remove(1) # using the remove method to get rid of the value 1\n", 396 | "\n", 397 | "print(s1) # notice when printed it removed the second \"1\" at the end" 398 | ] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "execution_count": 24, 403 | "metadata": {}, 404 | "outputs": [ 405 | { 406 | "name": "stdout", 407 | "output_type": "stream", 408 | "text": [ 409 | "\n" 410 | ] 411 | } 412 | ], 413 | "source": [ 414 | "# declaring a frozenset\n", 415 | "\n", 416 | "fset = frozenset([1, 2, 3, 4])\n", 417 | "\n", 418 | "print( type(fset) )" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "metadata": { 424 | "collapsed": true 425 | }, 426 | "source": [ 427 | "# Reading & Writing Files" 428 | ] 429 | }, 430 | { 431 | "cell_type": "code", 432 | "execution_count": 31, 433 | "metadata": {}, 434 | "outputs": [ 435 | { 436 | "name": "stdout", 437 | "output_type": "stream", 438 | "text": [ 439 | "this is a test\n" 440 | ] 441 | } 442 | ], 443 | "source": [ 444 | "# opening/creating and writing to a text file\n", 445 | "\n", 446 | "f = open(\"test.txt\", 'w+') # open file in writing and reading mode\n", 447 | "\n", 448 | "f.write('this is a test')\n", 449 | "\n", 450 | "f.close()\n", 451 | "\n", 452 | "# reading from a text file\n", 453 | "f = open('test.txt', 'r')\n", 454 | "\n", 455 | "data = f.read()\n", 456 | "\n", 457 | "f.close()\n", 458 | "\n", 459 | "print(data)" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": 32, 465 | "metadata": { 466 | "collapsed": true 467 | }, 468 | "outputs": [], 469 | "source": [ 470 | "# opening/creating and writing to a csv file\n", 471 | "import csv\n", 472 | "\n", 473 | "with open('test.csv', mode='w', newline='') as f:\n", 474 | " writer = csv.writer(f, delimiter=',')\n", 475 | " writer.writerow(['Name', 'City'])\n", 476 | " writer.writerow(['Craig Lou', 'Taiwan'])" 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "execution_count": 33, 482 | "metadata": {}, 483 | "outputs": [ 484 | { 485 | "name": "stdout", 486 | "output_type": "stream", 487 | "text": [ 488 | "['Name', 'City']\n", 489 | "['Craig Lou', 'Taiwan']\n" 490 | ] 491 | } 492 | ], 493 | "source": [ 494 | "# reading from csv files\n", 495 | "\n", 496 | "with open('test.csv', mode='r') as f:\n", 497 | " reader = csv.reader(f, delimiter=',')\n", 498 | " \n", 499 | " for row in reader:\n", 500 | " print(row)" 501 | ] 502 | }, 503 | { 504 | "cell_type": "markdown", 505 | "metadata": { 506 | "collapsed": true 507 | }, 508 | "source": [ 509 | "# Friday project: Creating a User Database with CSV Files" 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "execution_count": 34, 515 | "metadata": {}, 516 | "outputs": [ 517 | { 518 | "name": "stdout", 519 | "output_type": "stream", 520 | "text": [ 521 | "Thanks for using our software!\n" 522 | ] 523 | } 524 | ], 525 | "source": [ 526 | "# import all necessary packages to be used\n", 527 | "import csv\n", 528 | "from IPython.display import clear_output\n", 529 | "\n", 530 | "# handle user registration and writing to csv\n", 531 | "def registerUser():\n", 532 | " with open('users.csv', mode='a', newline='') as f:\n", 533 | " writer = csv.writer(f, delimiter=',')\n", 534 | " \n", 535 | " print('To register, please enter your info:')\n", 536 | " email = input('E-mail: ')\n", 537 | " password = input('Password: ')\n", 538 | " password2 = input('Re-type password: ')\n", 539 | "\n", 540 | " clear_output()\n", 541 | " \n", 542 | " if password == password2:\n", 543 | " writer.writerow([email, password])\n", 544 | " print('You are now registered!')\n", 545 | " else:\n", 546 | " print('Something went wrong. Try again.')\n", 547 | " \n", 548 | "# ask for user info and return true to login\n", 549 | "def loginUser():\n", 550 | " print('To login, please enter your info:')\n", 551 | " email = input('E-mail: ')\n", 552 | " password = input('Password: ')\n", 553 | " \n", 554 | " clear_output()\n", 555 | " \n", 556 | " with open('users.csv', mode='r') as f:\n", 557 | " reader = csv.reader(f, delimiter=',')\n", 558 | " \n", 559 | " for row in reader:\n", 560 | " if row == [email, password]:\n", 561 | " print('You are now logged in!')\n", 562 | " return True\n", 563 | " \n", 564 | " print('Something went wrong, try again.')\n", 565 | " return False\n", 566 | " \n", 567 | "# variables for main loop\n", 568 | "active = True\n", 569 | "logged_in = False\n", 570 | "\n", 571 | "# main loop\n", 572 | "while active:\n", 573 | " if logged_in:\n", 574 | " print('1. Logout\\n2. Quit')\n", 575 | " else:\n", 576 | " print('1. Login\\n2. Register\\n3. Quit')\n", 577 | " \n", 578 | " choice = input('What would you like to do? ').lower()\n", 579 | " \n", 580 | " clear_output()\n", 581 | " \n", 582 | " if choice == 'register' and logged_in == False:\n", 583 | " registerUser()\n", 584 | " elif choice == 'login' and logged_in == False:\n", 585 | " logged_in = loginUser()\n", 586 | " elif choice == 'quit':\n", 587 | " active = False\n", 588 | " print('Thanks for using our software!')\n", 589 | " elif choice == 'logout' and logged_in == True:\n", 590 | " logged_in = False\n", 591 | " print('You are now logged out.')\n", 592 | " else:\n", 593 | " print('Sorry, please try again!')" 594 | ] 595 | }, 596 | { 597 | "cell_type": "markdown", 598 | "metadata": {}, 599 | "source": [ 600 | "# Monday Exercises - Answers" 601 | ] 602 | }, 603 | { 604 | "cell_type": "markdown", 605 | "metadata": {}, 606 | "source": [ 607 | "

\n", 608 | "1. User Input: Ask the user for their name and age, then create a dictionary with those key-value pairs. Output the dictionary once created.\n", 609 | "

" 610 | ] 611 | }, 612 | { 613 | "cell_type": "code", 614 | "execution_count": 9, 615 | "metadata": {}, 616 | "outputs": [ 617 | { 618 | "name": "stdout", 619 | "output_type": "stream", 620 | "text": [ 621 | "What is your name? Connor\n", 622 | "What is your age? 27\n", 623 | "{'name': 'Connor', 'age': '27'}\n" 624 | ] 625 | } 626 | ], 627 | "source": [ 628 | "name = input('What is your name? ')\n", 629 | "age = input('What is your age? ')\n", 630 | "\n", 631 | "person = { 'name' : name, 'age' : age }\n", 632 | "\n", 633 | "print(person)" 634 | ] 635 | }, 636 | { 637 | "cell_type": "markdown", 638 | "metadata": {}, 639 | "source": [ 640 | "

\n", 641 | "2. Accessing Ingredients: Output all the ingredients from the list below within the 'ingredients' key using a for loop:\n", 642 | "

\n", 643 | "\n", 644 | "

\n", 645 | ">>> pizza = {
\n", 646 | ">>>      'ingredients' : ['cheese', 'sausage', 'peppers']
\n", 647 | ">>> }\n", 648 | "

" 649 | ] 650 | }, 651 | { 652 | "cell_type": "code", 653 | "execution_count": 8, 654 | "metadata": {}, 655 | "outputs": [ 656 | { 657 | "name": "stdout", 658 | "output_type": "stream", 659 | "text": [ 660 | "cheese\n", 661 | "sausage\n", 662 | "peppers\n" 663 | ] 664 | } 665 | ], 666 | "source": [ 667 | "pizza = {\n", 668 | " 'ingredients' : ['cheese', 'sausage', 'peppers']\n", 669 | "}\n", 670 | "\n", 671 | "for topping in pizza['ingredients']:\n", 672 | " print(topping)" 673 | ] 674 | }, 675 | { 676 | "cell_type": "markdown", 677 | "metadata": {}, 678 | "source": [ 679 | "# Tuesday Exercises - Answers" 680 | ] 681 | }, 682 | { 683 | "cell_type": "markdown", 684 | "metadata": {}, 685 | "source": [ 686 | "

\n", 687 | "1. User Input: Declare an empty dictionary. Ask the user for their name, address, and number. Add that information to the dictionary and iterate over it to show the user.\n", 688 | "

" 689 | ] 690 | }, 691 | { 692 | "cell_type": "code", 693 | "execution_count": 19, 694 | "metadata": {}, 695 | "outputs": [ 696 | { 697 | "name": "stdout", 698 | "output_type": "stream", 699 | "text": [ 700 | "What is your name? John Smith\n", 701 | "What is your address? 5 Main Street, Boston, MA\n", 702 | "What is your number? 800-828-7300\n", 703 | "name: John Smith\n", 704 | "address: 5 Main Street, Boston, MA\n", 705 | "number: 800-828-7300\n" 706 | ] 707 | } 708 | ], 709 | "source": [ 710 | "info = {}\n", 711 | "\n", 712 | "name = input('What is your name? ')\n", 713 | "address = input('What is your address? ')\n", 714 | "number = input('What is your number? ')\n", 715 | "\n", 716 | "info['name'] = name\n", 717 | "info['address'] = address\n", 718 | "info['number'] = number\n", 719 | "\n", 720 | "for k, v in info.items():\n", 721 | " print(\"{}: {}\".format(k, v))" 722 | ] 723 | }, 724 | { 725 | "cell_type": "markdown", 726 | "metadata": {}, 727 | "source": [ 728 | "

\n", 729 | "2. Problem Solving: What is wrong with the following code:\n", 730 | "

\n", 731 | "\n", 732 | "

\n", 733 | ">>> person = { 'name', 'John Smith' }
\n", 734 | ">>> print(person['name'])\n", 735 | "

" 736 | ] 737 | }, 738 | { 739 | "cell_type": "code", 740 | "execution_count": 18, 741 | "metadata": { 742 | "collapsed": true 743 | }, 744 | "outputs": [], 745 | "source": [ 746 | "# the name key and John Smith value should be separated by a colon, not comma" 747 | ] 748 | }, 749 | { 750 | "cell_type": "markdown", 751 | "metadata": {}, 752 | "source": [ 753 | "# Wednesday Exercises - Answers" 754 | ] 755 | }, 756 | { 757 | "cell_type": "markdown", 758 | "metadata": {}, 759 | "source": [ 760 | "

\n", 761 | "1. User Input: Ask the user to input as many bank account numbers as they'd like and store them within a list initially. Once the user is done entering information, convert the list to a frozenset and print it out.\n", 762 | "

" 763 | ] 764 | }, 765 | { 766 | "cell_type": "code", 767 | "execution_count": 28, 768 | "metadata": {}, 769 | "outputs": [ 770 | { 771 | "name": "stdout", 772 | "output_type": "stream", 773 | "text": [ 774 | "Enter an account number or quit: 1\n", 775 | "Enter an account number or quit: quit\n", 776 | "Account Number: 1\n" 777 | ] 778 | } 779 | ], 780 | "source": [ 781 | "accounts = []\n", 782 | "done = False\n", 783 | "\n", 784 | "while not done:\n", 785 | " ans = input('Enter an account number or quit: ').lower()\n", 786 | " \n", 787 | " if ans == 'quit':\n", 788 | " done = True\n", 789 | " \n", 790 | " accounts = frozenset(accounts)\n", 791 | " for acc in accounts:\n", 792 | " print(\"Account Number: {}\".format(acc))\n", 793 | " \n", 794 | " else:\n", 795 | " accounts.append(ans)" 796 | ] 797 | }, 798 | { 799 | "cell_type": "markdown", 800 | "metadata": {}, 801 | "source": [ 802 | "

\n", 803 | "2. Conversion: Convert the list below into a set of unique values. Print it out after to check there are no duplicates.\n", 804 | "

\n", 805 | "\n", 806 | "

\n", 807 | ">>> nums = [3, 4, 3, 7, 10]\n", 808 | "

" 809 | ] 810 | }, 811 | { 812 | "cell_type": "code", 813 | "execution_count": 29, 814 | "metadata": {}, 815 | "outputs": [ 816 | { 817 | "name": "stdout", 818 | "output_type": "stream", 819 | "text": [ 820 | "{10, 3, 4, 7}\n" 821 | ] 822 | } 823 | ], 824 | "source": [ 825 | "nums = [3, 4, 3, 7, 10]\n", 826 | "\n", 827 | "nums = set(nums)\n", 828 | "\n", 829 | "print(nums)" 830 | ] 831 | }, 832 | { 833 | "cell_type": "markdown", 834 | "metadata": {}, 835 | "source": [ 836 | "# Thursday Exercises - Answers" 837 | ] 838 | }, 839 | { 840 | "cell_type": "markdown", 841 | "metadata": {}, 842 | "source": [ 843 | "

\n", 844 | "1. User Input: Ask a user for their favorite number and save it to a text file.\n", 845 | "

" 846 | ] 847 | }, 848 | { 849 | "cell_type": "code", 850 | "execution_count": 35, 851 | "metadata": {}, 852 | "outputs": [ 853 | { 854 | "name": "stdout", 855 | "output_type": "stream", 856 | "text": [ 857 | "What is your favorite number? 9\n" 858 | ] 859 | } 860 | ], 861 | "source": [ 862 | "ans = input(\"What is your favorite number? \")\n", 863 | "\n", 864 | "f = open(\"numbers.txt\", 'w+') # open file in writing and reading mode\n", 865 | "\n", 866 | "f.write('favorite number is {}'.format(ans))\n", 867 | "\n", 868 | "f.close()" 869 | ] 870 | }, 871 | { 872 | "cell_type": "markdown", 873 | "metadata": {}, 874 | "source": [ 875 | "

\n", 876 | "2. Data Dumping: Using the dictionary of data below, save the information to a csv file with the keys as the headers and the values as the rows of data.\n", 877 | "

\n", 878 | "\n", 879 | "

\n", 880 | ">>> data = {
\n", 881 | ">>>      'name' : [\"Dave\", \"Dennis\", \"Peter\", \"Jess\"],
\n", 882 | ">>>      'language' : ['Python', 'C', 'Java', 'Python']
\n", 883 | ">>> }\n", 884 | "

" 885 | ] 886 | }, 887 | { 888 | "cell_type": "code", 889 | "execution_count": 36, 890 | "metadata": { 891 | "collapsed": true 892 | }, 893 | "outputs": [], 894 | "source": [ 895 | "data = {\n", 896 | " 'name' : ['Dave', 'Dennis', 'Peter', \"Jess\"],\n", 897 | " 'language' : ['Python', 'C', 'Java', 'Python']\n", 898 | "}\n", 899 | "\n", 900 | "import csv\n", 901 | "\n", 902 | "with open('data.csv', mode='w', newline='') as f:\n", 903 | " writer = csv.writer(f, delimiter=',')\n", 904 | " writer.writerow(data.keys())\n", 905 | " \n", 906 | " for i in range(len(data['name'])):\n", 907 | " writer.writerow([data['name'][i], data['language'][i]])" 908 | ] 909 | }, 910 | { 911 | "cell_type": "markdown", 912 | "metadata": {}, 913 | "source": [ 914 | "# End of Week Exercises - Answers" 915 | ] 916 | }, 917 | { 918 | "cell_type": "markdown", 919 | "metadata": {}, 920 | "source": [ 921 | "

\n", 922 | "1. Changing Passwords: Add a function called \"changePassword\" to the project from Friday that will allow users to change their password when logged in.\n", 923 | "

" 924 | ] 925 | }, 926 | { 927 | "cell_type": "code", 928 | "execution_count": 8, 929 | "metadata": {}, 930 | "outputs": [ 931 | { 932 | "name": "stdout", 933 | "output_type": "stream", 934 | "text": [ 935 | "Thanks for using our software!\n" 936 | ] 937 | } 938 | ], 939 | "source": [ 940 | "# import all necessary packages to be used\n", 941 | "import csv\n", 942 | "from IPython.display import clear_output\n", 943 | "\n", 944 | "# handle user changing password\n", 945 | "def changePassword():\n", 946 | " ''' \n", 947 | " This function must confirm email and pass, then read data and save to local list\n", 948 | " because you cannot change a single value, you must save all data, then overwrite\n", 949 | " the entire file all together.\n", 950 | " '''\n", 951 | " \n", 952 | " email = input('Please confirm your e-mail: ')\n", 953 | " password = input('Please confirm your current password: ')\n", 954 | " \n", 955 | " emails = []\n", 956 | " passwords = []\n", 957 | " found = False\n", 958 | "\n", 959 | " with open('users.csv', mode='r') as f:\n", 960 | " reader = csv.reader(f, delimiter=',')\n", 961 | " \n", 962 | " for row in reader:\n", 963 | " if row == [email, password]:\n", 964 | " found = True\n", 965 | " elif row:\n", 966 | " emails.append(row[0])\n", 967 | " passwords.append(row[1])\n", 968 | " \n", 969 | " if found:\n", 970 | " new_pass = input('What would you like to change your password to? ')\n", 971 | " \n", 972 | " emails.append(email)\n", 973 | " passwords.append(new_pass)\n", 974 | " \n", 975 | " with open('users.csv', mode='w') as f:\n", 976 | " writer = csv.writer(f, delimiter=',')\n", 977 | " \n", 978 | " for i in range(len(emails)):\n", 979 | " writer.writerow([emails[i], passwords[i]])\n", 980 | " else:\n", 981 | " print('Sorry those credentials were incorrect.')\n", 982 | "\n", 983 | "# handle user registration and writing to csv\n", 984 | "def registerUser():\n", 985 | " with open('users.csv', mode='a', newline='') as f:\n", 986 | " writer = csv.writer(f, delimiter=',')\n", 987 | " \n", 988 | " print('To register, please enter your info:')\n", 989 | " email = input('E-mail: ')\n", 990 | " password = input('Password: ')\n", 991 | " password2 = input('Re-type password: ')\n", 992 | "\n", 993 | " clear_output()\n", 994 | " \n", 995 | " if password == password2:\n", 996 | " writer.writerow([email, password])\n", 997 | " print('You are now registered!')\n", 998 | " else:\n", 999 | " print('Something went wrong. Try again.')\n", 1000 | " \n", 1001 | "# ask for user info and return true to login\n", 1002 | "def loginUser():\n", 1003 | " print('To login, please enter your info:')\n", 1004 | " email = input('E-mail: ')\n", 1005 | " password = input('Password: ')\n", 1006 | " \n", 1007 | " clear_output()\n", 1008 | " \n", 1009 | " with open('users.csv', mode='r') as f:\n", 1010 | " reader = csv.reader(f, delimiter=',')\n", 1011 | " \n", 1012 | " for row in reader:\n", 1013 | " if row == [email, password]:\n", 1014 | " print('You are now logged in!')\n", 1015 | " return True\n", 1016 | " \n", 1017 | " print('Something went wrong, try again.')\n", 1018 | " return False\n", 1019 | " \n", 1020 | "# variables for main loop\n", 1021 | "active = True\n", 1022 | "logged_in = False\n", 1023 | "\n", 1024 | "# main loop\n", 1025 | "while active:\n", 1026 | " if logged_in:\n", 1027 | " print('1. Logout\\n2. Change Password\\n3. Quit')\n", 1028 | " else:\n", 1029 | " print('1. Login\\n2. Register\\n3. Quit')\n", 1030 | " \n", 1031 | " choice = input('What would you like to do? ').lower()\n", 1032 | " \n", 1033 | " clear_output()\n", 1034 | " \n", 1035 | " if choice == 'register' and logged_in == False:\n", 1036 | " registerUser()\n", 1037 | " elif choice == 'login' and logged_in == False:\n", 1038 | " logged_in = loginUser()\n", 1039 | " elif choice == 'quit':\n", 1040 | " active = False\n", 1041 | " print('Thanks for using our software!')\n", 1042 | " elif choice == 'logout' and logged_in == True:\n", 1043 | " logged_in = False\n", 1044 | " print('You are now logged out.')\n", 1045 | " elif choice == 'change password' and logged_in == True:\n", 1046 | " changePassword()\n", 1047 | " else:\n", 1048 | " print('Sorry, please try again!')" 1049 | ] 1050 | }, 1051 | { 1052 | "cell_type": "markdown", 1053 | "metadata": {}, 1054 | "source": [ 1055 | "

\n", 1056 | "2. Favorite Food: Write a new program that will ask users what their favorite food is. Save the answers to a csv file called \"favorite_food.csv\". After answering, display a table of tallied results. Example of table:\n", 1057 | "

\n", 1058 | "\n", 1059 | "

\n", 1060 | "Favorite Food?              # of Votes
\n", 1061 | "Turkey                            5
\n", 1062 | "Salad                              3\n", 1063 | "

" 1064 | ] 1065 | }, 1066 | { 1067 | "cell_type": "code", 1068 | "execution_count": 11, 1069 | "metadata": {}, 1070 | "outputs": [ 1071 | { 1072 | "name": "stdout", 1073 | "output_type": "stream", 1074 | "text": [ 1075 | "Here are the results so far...\n", 1076 | "bacon: 4\n", 1077 | "bread: 2\n" 1078 | ] 1079 | } 1080 | ], 1081 | "source": [ 1082 | "def saveFood():\n", 1083 | " ans = input('What is your favorite food? ')\n", 1084 | " \n", 1085 | " with open('favorite_food.csv', mode='a', newline='') as f:\n", 1086 | " writer = csv.writer(f, delimiter=',')\n", 1087 | " \n", 1088 | " writer.writerow([ans])\n", 1089 | " \n", 1090 | " print('Food added!')\n", 1091 | " \n", 1092 | "def countFood():\n", 1093 | " food_count = {}\n", 1094 | " \n", 1095 | " with open('favorite_food.csv', mode='r') as f:\n", 1096 | " reader = csv.reader(f, delimiter=',')\n", 1097 | " \n", 1098 | " for row in reader:\n", 1099 | " if row[0].lower() in food_count:\n", 1100 | " food_count[row[0].lower()] += 1\n", 1101 | " else:\n", 1102 | " food_count[row[0].lower()] = 1\n", 1103 | " \n", 1104 | " return food_count\n", 1105 | "\n", 1106 | "def main():\n", 1107 | " while input('Would you like to add more? ').lower() != 'no':\n", 1108 | " saveFood()\n", 1109 | " \n", 1110 | " clear_output()\n", 1111 | " \n", 1112 | " print('Here are the results so far...')\n", 1113 | " \n", 1114 | " food_count = countFood()\n", 1115 | " \n", 1116 | " for k, v in food_count.items():\n", 1117 | " print(\"{}: {}\".format(k, v))\n", 1118 | " \n", 1119 | "main()" 1120 | ] 1121 | } 1122 | ], 1123 | "metadata": { 1124 | "kernelspec": { 1125 | "display_name": "Python 3", 1126 | "language": "python", 1127 | "name": "python3" 1128 | }, 1129 | "language_info": { 1130 | "codemirror_mode": { 1131 | "name": "ipython", 1132 | "version": 3 1133 | }, 1134 | "file_extension": ".py", 1135 | "mimetype": "text/x-python", 1136 | "name": "python", 1137 | "nbconvert_exporter": "python", 1138 | "pygments_lexer": "ipython3", 1139 | "version": "3.6.5" 1140 | } 1141 | }, 1142 | "nbformat": 4, 1143 | "nbformat_minor": 2 1144 | } 1145 | --------------------------------------------------------------------------------