├── .gitignore ├── FAQ.md ├── README.md └── src ├── 00_hello.py ├── 01_bignum.py ├── 02_datatypes.py ├── 03_modules.py ├── 04_printing.py ├── 05_lists.py ├── 06_tuples.py ├── 07_slices.py ├── 08_comprehensions.py ├── 09_dictionaries.py ├── 10_functions.py ├── 11_args.py ├── 12_scopes.py ├── 13_file_io.py ├── 14_cal.py ├── 15_classes.py └── foo.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | *.pyc 3 | __pycache__ -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | # FAQ 2 | 3 | 7 | 8 | ## Contents 9 | 10 | ### General CS 11 | 12 | * [What are some things we can do to prepare for CS?](#q100) 13 | * [What are some ways to learn a new language?](#q3600) 14 | * [Why test code frequently?](#q3700) 15 | * [Why isn't official documentation more helpful than Stack Overflow?](#q3800) 16 | * [During an interview, what do I do if I can't remember the exact syntax?](#q3900) 17 | 18 | ### General Python 19 | 20 | * [In regard to the code challenge solution, why is the '+' operator being used to concatenate strings? I thought we were supposed to use the join() method in Python?](#q300) 21 | * [How do you get out of the Python built-in `help`?](#q400) 22 | * [Are there any helpful VS Code extensions that are recommend for using with Python?](#q500) 23 | * [I'm on Windows; what command do I use to run Python?](#q600) 24 | * [What version of Python do I need?](#q700) 25 | * [How do I get out of the Python REPL?](#q900) 26 | * [What does "REPL" mean?](#q1000) 27 | * [I'm on a Mac and when I run Python it says I'm on version 2.7. Why?](#q1100) 28 | * [Does Python use tabs or spaces?](#q1200) 29 | * [Can you use boolean shortcut assignments?](#q1700) 30 | * [Can you do anonymous functions?](#q1800) 31 | * [What are all those method names with double underscores around them?](#q2000) 32 | * [Where are good Python docs?](#q2600) 33 | * [Which linter?](#q2700) 34 | * [What's the difference between __repr__ and __str__?](#q3300) 35 | * [How does `sys.argv` work?](#q3400) 36 | 37 | ### Pipenv 38 | 39 | * [Do I need to use pipenv?](#q800) 40 | * [When do we run pipenv shell?](#q2200) 41 | * [How do I get out of the pipenv shell?](#q2300) 42 | * [How do I install additional packages from pipenv?](#q2400) 43 | * [Is it possible to use system-wide packages from inside the virtual environment?](#q2500) 44 | 45 | ### Object-Oriented Programming 46 | 47 | * [Why is there such a debate between OOP and functional programming, and why should we care?](#q200) 48 | * [Following this flow: 1) class Dog is created with attributes size and weight. 2) New instance called Snoopy of class Dog is created. 3) Class Dog gets the method bark() dynamically added to it. Question: will Snoopy now have access to bark() method?](#q2900) 49 | * [Can you dynamically add new methods/properties to class through other functions? Or must all properties/methods be declared at once?](#q2800) 50 | * [If a subclass inherits from two superclasses with a method of the same name, which method will the subclass use?](#q3000) 51 | * [How to handle multiple inheritance and why/when to do it in the first place?](#q3100) 52 | 53 | ### Python Scoping 54 | 55 | * [Does Python have hoisting?](#q1400) 56 | * [Does scoping work similar to other languages?](#q1500) 57 | * [Can you return a reference to a function from another function? Or store it in a variable?](#q1600) 58 | * [Can you do anonymous functions?](#q1800) 59 | 60 | ### Types 61 | 62 | * [How do I convert an iterator into a list?](#q1300) 63 | * [Is a dict like a JavaScript object?](#q1900) 64 | * [How do I get a value from a dict?](#q2100) 65 | * [Why use tuples instead of lists?](#q3200) 66 | * [How do I concatenate two arrays into a single array?](#q3500) 67 | 68 | ## Questions 69 | 70 | 71 | ### What are some things we can do to prepare for CS? 72 | 73 | * [CS Wiki](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki) 74 | * [Polya's Problem Solving Techniques](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/Polya%27s-Problem-Solving-Techniques) 75 | * [Solving Programming Problems](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/Solving-Programming-Problems) 76 | * [CS Reading List](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/Computer-Science-Reading-List) 77 | * [How to Google effectively](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/How-to-Google-Effectively) 78 | * [How to read specs and code](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/How-to-Read-Specifications-and-Code) 79 | * [Command line primer](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/Command-Line-Primer) 80 | * [Coding style guidelines](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/CS-Coding-Style-Guidelines) 81 | 82 | ------------------------------------------------------------------------ 83 | 84 | 85 | ### Why is there such a debate between OOP and functional programming, and why should we care? 86 | 87 | There are a lot of [programming 88 | paradigms](https://en.wikipedia.org/wiki/Programming_paradigm) and they all have 89 | their strengths and weaknesses when it comes to solving different types of 90 | problems. 91 | 92 | People can be quite opinionated about their favorites, but it's important to 93 | remember that no one language or paradigm is the right tool for all jobs. And, 94 | additionally, that virtually all problems can be solved in any of the 95 | declarative or imperative paradigms. (Some might produce cleaner, more elegant 96 | code for a particular problem.) 97 | 98 | Paradigms are the hardest thing to learn because you often have to take all the 99 | knowledge you have about solving a problem in another paradigm and throw it out 100 | the window. You have to learn new patterns and techniques to be effective. 101 | 102 | But we encourage this kind of learning because most popular languages are to 103 | some degree _multi-paradigm_, and the more techniques you know from more 104 | paradigms, the more effective you are in that multi-paradigm langage. 105 | 106 | ------------------------------------------------------------------------ 107 | 108 | 109 | ### In regard to the code challenge solution, why is the '+' operator being used to concatenate strings? I thought we were supposed to use the join() method in Python? 110 | 111 | Using `join()` to join large numbers of strings is definitely faster in Python 112 | than using the `+` operator to do it. The reason is that every time you `join()` 113 | or use the `+` operator, a new string is created. So if you only have to 114 | `join()` once, versus using `+` hundreds of times, you'll run faster. 115 | 116 | That said, if you want to use the `join()` approach, you'll have to have all 117 | your strings in a list, which uses more memory than just having the two or three 118 | that you need at a time to use `+`. So there's a tradeoff. 119 | 120 | Another tradeoff might be in readability. It might be easier to read the `+` 121 | version. That's worth something. 122 | 123 | Finally, if `+` is fast enough for this case, it might not be worth the time to 124 | bother with making a list of strings to `join()`. 125 | 126 | * [Speed comparison with different ways of concatenating strings](https://waymoot.org/home/python_string/) 127 | 128 | ------------------------------------------------------------------------ 129 | 130 | 131 | ### How do you get out of the Python built-in `help`? 132 | 133 | Hit `q` for "quit". 134 | 135 | It's a common command in Unix "pagers" (programs that show documents a page at a 136 | time). 137 | 138 | ------------------------------------------------------------------------ 139 | 140 | 141 | ### Are there any helpful VS Code extensions that are recommend for using with Python? 142 | 143 | * [Official VS Code Python Extension](https://code.visualstudio.com/docs/languages/python) 144 | 145 | ------------------------------------------------------------------------ 146 | 147 | 148 | ### I'm on Windows; what command do I use to run Python? 149 | 150 | If you're running in PowerShell or cmd, use: 151 | 152 | ``` 153 | py 154 | ``` 155 | 156 | If in bash, use `python` or `python3`. 157 | 158 | ------------------------------------------------------------------------ 159 | 160 | 161 | ### What version of Python do I need? 162 | 163 | You should have version 3.7 or higher. Test with: 164 | 165 | ```shell 166 | python --version 167 | ``` 168 | 169 | ------------------------------------------------------------------------ 170 | 171 | 172 | ### Do I need to use pipenv? 173 | 174 | You should. Good Python devs know how. 175 | 176 | ------------------------------------------------------------------------ 177 | 178 | 179 | ### How do I get out of the Python REPL? 180 | 181 | Hit `CTRL-D`. This is the way End-Of-File is signified in Unix-likes. 182 | 183 | ------------------------------------------------------------------------ 184 | 185 | 186 | ### What does "REPL" mean? 187 | 188 | _Read, Evaluate, Print Loop_. 189 | 190 | It reads your input, evaluates it, and prints the result. And loops. 191 | 192 | ------------------------------------------------------------------------ 193 | 194 | 195 | ### I'm on a Mac and when I run Python it says I'm on version 2.7. Why? 196 | 197 | Macs come with version 2.7 by default. You'll need to install version 3. 198 | 199 | And preferable use `pipenv` after that. 200 | 201 | ------------------------------------------------------------------------ 202 | 203 | 204 | ### Does Python use tabs or spaces? 205 | 206 | [PEP 8](https://www.python.org/dev/peps/pep-0008/) says four spaces. 207 | 208 | ------------------------------------------------------------------------ 209 | 210 | 211 | ### How do I convert an iterator into a list? 212 | 213 | Cast it: 214 | 215 | ```python 216 | list(range(5)) 217 | ``` 218 | 219 | produces: 220 | 221 | ```python 222 | [0, 1, 2, 3, 4] 223 | ``` 224 | 225 | ------------------------------------------------------------------------ 226 | 227 | 228 | ### Does Python have hoisting? 229 | 230 | No. 231 | 232 | * [What is hoisting?](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) 233 | 234 | ------------------------------------------------------------------------ 235 | 236 | 237 | ### Does scoping work similar to other languages? 238 | 239 | Generally, and also not really. Variables are either global or function-local. 240 | 241 | Since there are no declarations, there's no block-level scope. 242 | 243 | It is similar to `var` in JavaScript. 244 | 245 | ------------------------------------------------------------------------ 246 | 247 | 248 | ### Can you return a reference to a function from another function? Or store it in a variable? 249 | 250 | Yes. Functions are [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen). 251 | 252 | ------------------------------------------------------------------------ 253 | 254 | 255 | ### Can you use boolean shortcut assignments? 256 | 257 | Yes, you can. This is common in Perl and JavaScript, but it's not particularly [idiomatic](https://en.wikipedia.org/wiki/Programming_idiom) in Python. 258 | 259 | ```python 260 | x = SomethingFalsey or 5 261 | ``` 262 | 263 | ------------------------------------------------------------------------ 264 | 265 | 266 | ### Can you do anonymous functions? 267 | 268 | You can use `lambda` for simple functions: 269 | 270 | ```python 271 | adder = lambda x, y: x + y 272 | 273 | adder(4, 5) # 9 274 | 275 | do_some_math(4, 5, lambda x, y: y - x) 276 | ``` 277 | 278 | ------------------------------------------------------------------------ 279 | 280 | 281 | ### Is a dict like a JavaScript object? 282 | 283 | Sort of. 284 | 285 | The syntax is different, though. In Python you must use `[]` notation to access elements. And you must use `"` around the key names. 286 | 287 | ------------------------------------------------------------------------ 288 | 289 | 290 | ### What are all those method names with double underscores around them? 291 | 292 | Those are function you typically don't need to use, but can override or call if you wish. 293 | 294 | Most commonly used are: 295 | 296 | * `__init__()` is the constructor for objects 297 | * `__str__()` returns a string representation of the object 298 | * `__repr__()` returns a string representation of the object, for debugging 299 | 300 | ------------------------------------------------------------------------ 301 | 302 | 303 | ### How do I get a value from a dict? 304 | 305 | ```python 306 | d = { 307 | "a": 2, 308 | "b": 3 309 | } 310 | 311 | print(d["a"]) 312 | ``` 313 | 314 | You don't use dot notation. 315 | 316 | ------------------------------------------------------------------------ 317 | 318 | 319 | ### When do we run pipenv shell? 320 | 321 | `pipenv shell` puts you into your work environment. When you're ready to work, or run the code, or install new dependencies, you should be in your pipenv shell. 322 | 323 | ------------------------------------------------------------------------ 324 | 325 | 326 | ### How do I get out of the pipenv shell? 327 | 328 | Type `exit`. 329 | 330 | ------------------------------------------------------------------------ 331 | 332 | 333 | ### How do I install additional packages from pipenv? 334 | 335 | ```shell 336 | pipenv install packagename 337 | ``` 338 | 339 | ------------------------------------------------------------------------ 340 | 341 | 342 | ### Is it possible to use system-wide packages from inside the virtual environment? 343 | 344 | This is [not recommended](https://pipenv.readthedocs.io/en/latest/diagnose/#no-module-named-module-name). 345 | 346 | ------------------------------------------------------------------------ 347 | 348 | 349 | ### Where are good Python docs? 350 | 351 | * [Official documentation](https://docs.python.org/3/) tutorial and library reference. 352 | 353 | The official docs might be hard to read at first, but you'll get used to them 354 | quickly 355 | 356 | ------------------------------------------------------------------------ 357 | 358 | 359 | ### Which linter? 360 | 361 | Pylint or Flake8. The latter seems to be a bit more popular. 362 | 363 | ------------------------------------------------------------------------ 364 | 365 | 366 | ### Can you dynamically add new methods/properties to class through other functions? Or must all properties/methods be declared at once? 367 | 368 | You can add them dynamically at runtime, but you have to add them to the class itself: 369 | 370 | ```python 371 | class Foo(): 372 | pass 373 | 374 | f = Foo() 375 | 376 | Foo.x = 12 # Dynamically add property to class 377 | 378 | f.x == 12 # True! 379 | 380 | def a_method(self): 381 | print("Hi") 382 | 383 | Foo.hi = a_method # Dynamically add method to class 384 | 385 | f.hi() # Prints "Hi" 386 | ``` 387 | 388 | This is not a common thing to see in Python, however. 389 | 390 | ------------------------------------------------------------------------ 391 | 392 | 393 | ### Following this flow: 1) class Dog is created with attributes size and weight. 2) New instance called Snoopy of class Dog is created. 3) Class Dog gets the method bark() dynamically added to it. Question: will Snoopy now have access to bark() method? 394 | 395 | Yes. 396 | 397 | ------------------------------------------------------------------------ 398 | 399 | 400 | ### If a subclass inherits from two superclasses with a method of the same name, which method will the subclass use? 401 | 402 | The answer to this is twofold: 403 | 404 | 1. Lots of devs and shops frown on multiple inheritance, so maybe just don't do 405 | it. 406 | ([Discussion](https://softwareengineering.stackexchange.com/questions/218458/is-there-any-real-reason-multiple-inheritance-is-hated)) 407 | 408 | 2. As for the order in which methods of the same name are resolved, check out 409 | the [MRO Algorithm](https://en.wikipedia.org/wiki/C3_linearization) which is 410 | what Python uses. 411 | 412 | 413 | ------------------------------------------------------------------------ 414 | 415 | 416 | ### How to handle multiple inheritance and why/when to do it in the first place? 417 | 418 | ```python 419 | class Base1: 420 | pass 421 | 422 | class Base2: 423 | pass 424 | 425 | class Derived(Base1, Base2): # Multiple inheritance 426 | pass 427 | ``` 428 | 429 | Sometimes multiple inheritance can lead to elegant solutions when a subclass 430 | needs attributes from multiple, otherwise-unrelated parent classes. 431 | 432 | However, [a lot of people find it's not worth the 433 | trouble](https://softwareengineering.stackexchange.com/questions/218458/is-there-any-real-reason-multiple-inheritance-is-hated)) 434 | and opt for other solutions, like composition. 435 | 436 | ------------------------------------------------------------------------ 437 | 438 | 439 | ### Why use tuples instead of lists? 440 | 441 | * Tuples are immutable. There's a school of thought that says bugs can be reduced if you make as many things immutable as you can. 442 | * Tuples are faster than lists to access. 443 | * Some tuples (containing primitive types), can be used as `dict` keys. 444 | 445 | ------------------------------------------------------------------------ 446 | 447 | 448 | ### What's the difference between __repr__ and __str__? 449 | 450 | Generally speaking, `__repr__` is the string a dev would want to see if they 451 | dumped an object to the screen. `__str__` is the string a user would want to see 452 | if the object were `print()`ed. 453 | 454 | The output of `__repr__` should be _valid Python code that can reproduce the 455 | object_. 456 | 457 | ```python 458 | class Goat: 459 | def __init__(self, leg_count): 460 | self.leg_count = leg_count 461 | 462 | def __repr__(self): 463 | return f'Goat(leg_count={self.leg_count})' 464 | 465 | def __str__(self): 466 | return f'a goat with {self.leg_count} legs' 467 | ``` 468 | 469 | In action: 470 | 471 | ```python 472 | >>> g = Goat(4) 473 | >>> str(g) 474 | 'a goat with 4 legs' 475 | >>> g 476 | Goat(leg_count=4) 477 | >>> Goat(leg_count=4) # output of __repr__ makes a clone of that object! 478 | Goat(leg_count=4) 479 | ``` 480 | 481 | ------------------------------------------------------------------------ 482 | 483 | 484 | ### How does `sys.argv` work? 485 | 486 | It's a list that holds _command line arguments_. This is a way for a user to run 487 | your program and specify different behavior from the command line. 488 | 489 | Here's a small program that prints the command line arguments: 490 | 491 | ```python 492 | import sys 493 | 494 | for i in range(len(sys.argv)): 495 | print(f'Argument #{i} is: {sys.argv[i]}') 496 | ``` 497 | 498 | and here's some output, assuming you named the script `foo.py`: 499 | 500 | ```screen 501 | $ python foo.py 502 | Argument #0 is: foo.py 503 | ``` 504 | 505 | ```screen 506 | $ python foo.py antelope buffalo 507 | Argument #0 is: foo.py 508 | Argument #1 is: antelope 509 | Argument #2 is: buffalo 510 | ``` 511 | 512 | Note that the 0th element in the list is the name of the program. 513 | 514 | Here's another program that prints up to whatever number the user specifies: 515 | 516 | ```python 517 | import sys 518 | 519 | for i in range(int(sys.argv[1])): 520 | print(i+1) 521 | ``` 522 | 523 | Example runs: 524 | 525 | ```screen 526 | $ python foo.py 2 527 | 1 528 | 2 529 | ``` 530 | 531 | ```screen 532 | $ python foo.py 4 533 | 1 534 | 2 535 | 3 536 | 4 537 | ``` 538 | 539 | ------------------------------------------------------------------------ 540 | 541 | 542 | ### How do I concatenate two arrays into a single array? 543 | 544 | Use `extend()`. 545 | 546 | ```python 547 | a = [1, 2, 3] 548 | b = [4, 5, 6] 549 | 550 | a.extend(b) 551 | 552 | print(a) # [ 1, 2, 3, 4, 5, 6 ] 553 | ``` 554 | 555 | ------------------------------------------------------------------------ 556 | 557 | 558 | ### What are some ways to learn a new language? 559 | 560 | * Figure out how variables and functions work. 561 | * Build small toy programs to test individual features. 562 | * Build a larger project that exercises many features. 563 | * Don't get frustrated! Treat the problem like a curiosity, a thing to be studied. 564 | * Do small tutorials or code-alongs. 565 | * Find docs you like. 566 | * Learn the differences between this language and one you know. 567 | * Learn this language's way of doing the things you know. 568 | 569 | Things to look for in the new language: 570 | 571 | * Collections (arrays, vectors, dictionaries) 572 | * Data types 573 | * Iterators 574 | * Flow control (if, while, loops, etc) 575 | * Functions 576 | * etc. 577 | 578 | ------------------------------------------------------------------------ 579 | 580 | 581 | ### Why test code frequently? 582 | 583 | It's often better to make progress in small increments than to write a bunch of 584 | stuff and test it in one go. 585 | 586 | Also, it's easier to stay motivated if you spend 10 minutes getting a first 587 | version going, even if it's missing 99% of its features, and then starting to 588 | iterate on that. 589 | 590 | ------------------------------------------------------------------------ 591 | 592 | 593 | ### Why isn't official documentation more helpful than Stack Overflow? 594 | 595 | Often official documentation is more geared toward being a concise reference. 596 | Stack Overflow is more of an example-based learning environment. 597 | 598 | Sometimes you need to know the specific details. In those cases, you can dig 599 | into the spec, with all it's lawyerly language, and try to decipher what it is 600 | you have to do. 601 | 602 | Other times, you just need a getting-started example, and Stack Overflow is 603 | great for that. 604 | 605 | Both types of documentation have their purpose. 606 | 607 | ------------------------------------------------------------------------ 608 | 609 | 610 | ### During an interview, what do I do if I can't remember the exact syntax? 611 | 612 | Just say so. 613 | 614 | "I can't remember how to add an element to the end of the list in Python... is 615 | it `push()`? In any case, we'll call the function here that does that." 616 | 617 | (Turns out it's `append()` in Python, but being honest and describing what it is 618 | your're trying to do will get you 99% of the way there in an interview.) 619 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Intro to Python I 2 | 3 | _Note: This project spans two modules (modules 1 and 2). You should roughly try to finish the first half of the problems during module 1 and the second half of the problems during module 2._ 4 | 5 | It's time to learn a new language! Python! 6 | 7 | Python is a popular, easy-to-use programming language that has significant 8 | traction in the field. 9 | 10 | Remember the goal is _learning to learn_, so keep track of what works for you 11 | and what doesn't as you go through the process of exploring Python. 12 | 13 | ## Techniques for learning new languages 14 | 15 | * Try to relate things you already know in another language (e.g. what an 16 | _array_ is) to the corresponding things in Python (e.g. a _list_) and how to 17 | use them. 18 | 19 | * Write a bunch of "toy programs" that demonstrate different key features of the 20 | language 21 | 22 | * Explore the standard library that's available for the language. Skim it 23 | briefly for now--the idea isn't to memorize everything but to file away 24 | generally what functionality is available. 25 | 26 | * Write a more substantial toy program that uses a variety of the features. 27 | 28 | Again, keep track of what works for you. Try different things to see what works 29 | best for learning new languages. 30 | 31 | ## Resources 32 | 33 | * [Installing Python 3](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/Installing-Python-3) 34 | * [JavaScript<->Python cheatsheet](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/Javascript-Python-cheatsheet) 35 | * [How to read Specs and Code](https://github.com/BloomInstituteOfTechnology/CS-Wiki/wiki/How-to-Read-Specifications-and-Code) 36 | * [Python 3 standard library](https://docs.python.org/3.6/library/) 37 | 38 | ## Getting started 39 | 40 | Make sure you have Python 3 installed. You can check this by running `python3 --version` in your terminal and ensuring that it returns a version string that is at least 3.6.5. 41 | 42 | ## Goals 43 | 44 | * Learn the basic syntax and structure of Python 45 | 46 | ## Summary 47 | 48 | * Implement a number of tiny Python programs that demonstrate Python syntax and 49 | language concepts. 50 | 51 | ## Instructions 52 | 53 | _Note: This project spans two modules (modules 1 and 2). You should roughly try to finish the first half of the problems during module 1 and the second half of the problems during module 2._ 54 | 55 | Each directory inside the `src/` directory presents exercises revolving around a 56 | particular concept in Python. Not all of these concepts are unique to Python (in 57 | fact, most probably aren't). This means that you can leverage knowledge you've 58 | obtained via exposure to other programming languages towards learning Python. 59 | 60 | The suggested order for going through each of the directories is: 61 | 62 | * `hello` -- Hello world 63 | * `bignum` -- Print some big numbers 64 | * `datatypes` -- Experiment with type conversion 65 | * `modules` -- Learn to import from modules 66 | * `printing` -- Formatted print output 67 | * `lists` -- Python's version of arrays 68 | * `tuples` -- Immutable lists typically for heterogenous data 69 | * `slices` -- Accessing parts of lists 70 | * `comprehensions` -- List comprehensions 71 | * `dictionaries` -- Dictionaries 72 | * `functions` -- Functions 73 | * `args` -- Arguments and Keyword Arguments 74 | * `scopes` -- Global, Local, and Non-Local scope 75 | * `file_io` -- Read and write from files 76 | * `cal` -- Experiment with module imports and implement a text-based calendar 77 | * `classes` -- Classes and objects 78 | 79 | ## Stretch Goals 80 | 81 | 1. One of Python's main philosophical tenets is its emphasis on readability. To 82 | that end, the Python community has standardized around a style guide called 83 | [PEP 8](https://www.python.org/dev/peps/pep-0008/). Take a look at it and 84 | then go over the code you've written and make sure it adheres to what PEP 8 85 | recommends. Alternatively, PEP 8 linters exist for most code editors (you can 86 | find instructions on installing a Python linter for VSCode 87 | [here](https://code.visualstudio.com/docs/python/linting)). Try installing 88 | one for your editor! 89 | 90 | 2. Rewrite code challenges you've solved before or projects you've implemented 91 | before in a different language in Python. Start getting in as much practice 92 | with the language as possible! 93 | 94 | 3. Write a program to determine if a number, given on the command line, is prime. 95 | 96 | 1. How can you optimize this program? 97 | 2. Implement [The Sieve of 98 | Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one 99 | of the oldest algorithms known (ca. 200 BC). 100 | -------------------------------------------------------------------------------- /src/00_hello.py: -------------------------------------------------------------------------------- 1 | # Print "Hello, world!" to your terminal -------------------------------------------------------------------------------- /src/01_bignum.py: -------------------------------------------------------------------------------- 1 | # Print out 2 to the 65536 power 2 | # (try doing the same thing in the JS console and see what it outputs) 3 | 4 | # YOUR CODE HERE -------------------------------------------------------------------------------- /src/02_datatypes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python is a strongly-typed language under the hood, which means 3 | that the types of values matter, especially when we're trying 4 | to perform operations on them. 5 | 6 | Note that if you try running the following code without making any 7 | changes, you'll get a TypeError saying you can't perform an operation 8 | on a string and an integer. 9 | """ 10 | 11 | x = 5 12 | y = "7" 13 | 14 | # Write a print statement that combines x + y into the integer value 12 15 | 16 | # YOUR CODE HERE 17 | 18 | 19 | # Write a print statement that combines x + y into the string value 57 20 | 21 | # YOUR CODE HERE -------------------------------------------------------------------------------- /src/03_modules.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this exercise, you'll be playing around with the sys module, 3 | which allows you to access many system specific variables and 4 | methods, and the os module, which gives you access to lower- 5 | level operating system functionality. 6 | """ 7 | 8 | import sys 9 | # See docs for the sys module: https://docs.python.org/3.7/library/sys.html 10 | 11 | # Print out the command line arguments in sys.argv, one per line: 12 | # YOUR CODE HERE 13 | 14 | # Print out the OS platform you're using: 15 | # YOUR CODE HERE 16 | 17 | # Print out the version of Python you're using: 18 | # YOUR CODE HERE 19 | 20 | 21 | import os 22 | # See the docs for the OS module: https://docs.python.org/3.7/library/os.html 23 | 24 | # Print the current process ID 25 | # YOUR CODE HERE 26 | 27 | # Print the current working directory (cwd): 28 | # YOUR CODE HERE 29 | 30 | # Print out your machine's login name 31 | # YOUR CODE HERE 32 | -------------------------------------------------------------------------------- /src/04_printing.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python provides a number of ways to perform printing. Research 3 | how to print using the printf operator, the `format` string 4 | method, and by using f-strings. 5 | """ 6 | 7 | x = 10 8 | y = 2.24552 9 | z = "I like turtles!" 10 | 11 | # Using the printf operator (%), print the following feeding in the values of x, 12 | # y, and z: 13 | # x is 10, y is 2.25, z is "I like turtles!" 14 | 15 | # Use the 'format' string method to print the same thing 16 | 17 | # Finally, print the same thing using an f-string -------------------------------------------------------------------------------- /src/05_lists.py: -------------------------------------------------------------------------------- 1 | # For the exercise, look up the methods and functions that are available for use 2 | # with Python lists. 3 | 4 | x = [1, 2, 3] 5 | y = [8, 9, 10] 6 | 7 | # For the following, DO NOT USE AN ASSIGNMENT (=). 8 | 9 | # Change x so that it is [1, 2, 3, 4] 10 | # YOUR CODE HERE 11 | print(x) 12 | 13 | # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] 14 | # YOUR CODE HERE 15 | print(x) 16 | 17 | # Change x so that it is [1, 2, 3, 4, 9, 10] 18 | # YOUR CODE HERE 19 | print(x) 20 | 21 | # Change x so that it is [1, 2, 3, 4, 9, 99, 10] 22 | # YOUR CODE HERE 23 | print(x) 24 | 25 | # Print the length of list x 26 | # YOUR CODE HERE 27 | 28 | # Print all the values in x multiplied by 1000 29 | # YOUR CODE HERE -------------------------------------------------------------------------------- /src/06_tuples.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python tuples are sort of like lists, except they're immutable and 3 | are usually used to hold heterogenous data, as opposed to lists 4 | which are typically used to hold homogenous data. Tuples use 5 | parens instead of square brackets. 6 | 7 | More specifically, tuples are faster than lists. If you're looking 8 | to just define a constant set of values and that set of values 9 | never needs to be mutated, use a tuple instead of a list. 10 | 11 | Additionally, your code will be safer if you opt to "write-protect" 12 | data that does not need to be changed. Tuples enforce immutability 13 | automatically. 14 | """ 15 | 16 | # Example: 17 | 18 | import math 19 | 20 | def dist(a, b): 21 | """Compute the distance between two x,y points.""" 22 | x0, y0 = a # Destructuring assignment 23 | x1, y1 = b 24 | 25 | return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) 26 | 27 | a = (2, 7) # <-- x,y coordinates stored in tuples 28 | b = (-14, 72) 29 | 30 | # Prints "Distance is 66.94" 31 | print("Distance is: {:.2f}".format(dist(a, b))) 32 | 33 | 34 | 35 | # Write a function `print_tuple` that prints all the values in a tuple 36 | 37 | # YOUR CODE HERE 38 | 39 | t = (1, 2, 5, 7, 99) 40 | print_tuple(t) # Prints 1 2 5 7 99, one per line 41 | 42 | # Declare a tuple of 1 element then print it 43 | u = (1) # What needs to be added to make this work? 44 | print_tuple(u) 45 | -------------------------------------------------------------------------------- /src/07_slices.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python exposes a terse and intuitive syntax for performing 3 | slicing on lists and strings. This makes it easy to reference 4 | only a portion of a list or string. 5 | 6 | This Stack Overflow answer provides a brief but thorough 7 | overview: https://stackoverflow.com/a/509295 8 | 9 | Use Python's slice syntax to achieve the following: 10 | """ 11 | 12 | a = [2, 4, 1, 7, 9, 6] 13 | 14 | # Output the second element: 4: 15 | print() 16 | 17 | # Output the second-to-last element: 9 18 | print() 19 | 20 | # Output the last three elements in the array: [7, 9, 6] 21 | print() 22 | 23 | # Output the two middle elements in the array: [1, 7] 24 | print() 25 | 26 | # Output every element except the first one: [4, 1, 7, 9, 6] 27 | print() 28 | 29 | # Output every element except the last one: [2, 4, 1, 7, 9] 30 | print() 31 | 32 | # For string s... 33 | 34 | s = "Hello, world!" 35 | 36 | # Output just the 8th-12th characters: "world" 37 | print() -------------------------------------------------------------------------------- /src/08_comprehensions.py: -------------------------------------------------------------------------------- 1 | """ 2 | List comprehensions are one cool and unique feature of Python. 3 | They essentially act as a terse and concise way of initializing 4 | and populating a list given some expression that specifies how 5 | the list should be populated. 6 | 7 | Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions 8 | for more info regarding list comprehensions. 9 | """ 10 | 11 | # Write a list comprehension to produce the array [1, 2, 3, 4, 5] 12 | 13 | y = [] 14 | 15 | print (y) 16 | 17 | # Write a list comprehension to produce the cubes of the numbers 0-9: 18 | # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] 19 | 20 | y = [] 21 | 22 | print(y) 23 | 24 | # Write a list comprehension to produce the uppercase version of all the 25 | # elements in array a. Hint: "foo".upper() is "FOO". 26 | 27 | a = ["foo", "bar", "baz"] 28 | 29 | y = [] 30 | 31 | print(y) 32 | 33 | # Use a list comprehension to create a list containing only the _even_ elements 34 | # the user entered into list x. 35 | 36 | x = input("Enter comma-separated numbers: ").split(',') 37 | 38 | # What do you need between the square brackets to make it work? 39 | y = [] 40 | 41 | print(y) -------------------------------------------------------------------------------- /src/09_dictionaries.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dictionaries are Python's implementation of associative arrays. 3 | There's not much different with Python's version compared to what 4 | you'll find in other languages (though you can also initialize and 5 | populate dictionaries using comprehensions just like you can with 6 | lists!). 7 | 8 | The docs can be found here: 9 | https://docs.python.org/3/tutorial/datastructures.html#dictionaries 10 | 11 | For this exercise, you have a list of dictionaries. Each dictionary 12 | has the following keys: 13 | - lat: a signed integer representing a latitude value 14 | - lon: a signed integer representing a longitude value 15 | - name: a name string for this location 16 | """ 17 | 18 | waypoints = [ 19 | { 20 | "lat": 43, 21 | "lon": -121, 22 | "name": "a place" 23 | }, 24 | { 25 | "lat": 41, 26 | "lon": -123, 27 | "name": "another place" 28 | }, 29 | { 30 | "lat": 43, 31 | "lon": -122, 32 | "name": "a third place" 33 | } 34 | ] 35 | 36 | # Add a new waypoint to the list 37 | # YOUR CODE HERE 38 | 39 | # Modify the dictionary with name "a place" such that its longitude 40 | # value is -130 and change its name to "not a real place" 41 | # Note: It's okay to access the dictionary using bracket notation on the 42 | # waypoints list. 43 | 44 | # YOUR CODE HERE 45 | 46 | # Write a loop that prints out all the field values for all the waypoints 47 | # YOUR CODE HERE -------------------------------------------------------------------------------- /src/10_functions.py: -------------------------------------------------------------------------------- 1 | # Write a function is_even that will return true if the passed-in number is even. 2 | 3 | # YOUR CODE HERE 4 | 5 | # Read a number from the keyboard 6 | num = input("Enter a number: ") 7 | num = int(num) 8 | 9 | # Print out "Even!" if the number is even. Otherwise print "Odd" 10 | 11 | # YOUR CODE HERE 12 | 13 | -------------------------------------------------------------------------------- /src/11_args.py: -------------------------------------------------------------------------------- 1 | # Experiment with positional arguments, arbitrary arguments, and keyword 2 | # arguments. 3 | 4 | # Write a function f1 that takes two integer positional arguments and returns 5 | # the sum. This is what you'd consider to be a regular, normal function. 6 | 7 | # YOUR CODE HERE 8 | 9 | print(f1(1, 2)) 10 | 11 | # Write a function f2 that takes any number of integer arguments and returns the 12 | # sum. 13 | # Note: Google for "python arbitrary arguments" and look for "*args" 14 | 15 | # YOUR CODE HERE 16 | 17 | print(f2(1)) # Should print 1 18 | print(f2(1, 3)) # Should print 4 19 | print(f2(1, 4, -12)) # Should print -7 20 | print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33 21 | 22 | a = [7, 6, 5, 4] 23 | 24 | # How do you have to modify the f2 call below to make this work? 25 | print(f2(a)) # Should print 22 26 | 27 | # Write a function f3 that accepts either one or two arguments. If one argument, 28 | # it returns that value plus 1. If two arguments, it returns the sum of the 29 | # arguments. 30 | # Note: Google "python default arguments" for a hint. 31 | 32 | # YOUR CODE HERE 33 | 34 | print(f3(1, 2)) # Should print 3 35 | print(f3(8)) # Should print 9 36 | 37 | 38 | # Write a function f4 that accepts an arbitrary number of keyword arguments and 39 | # prints out the keys and values like so: 40 | # 41 | # key: foo, value: bar 42 | # key: baz, value: 12 43 | # 44 | # Note: Google "python keyword arguments". 45 | 46 | # YOUR CODE HERE 47 | 48 | # Should print 49 | # key: a, value: 12 50 | # key: b, value: 30 51 | f4(a=12, b=30) 52 | 53 | # Should print 54 | # key: city, value: Berkeley 55 | # key: population, value: 121240 56 | # key: founded, value: "March 23, 1868" 57 | f4(city="Berkeley", population=121240, founded="March 23, 1868") 58 | 59 | d = { 60 | "monster": "goblin", 61 | "hp": 3 62 | } 63 | 64 | # How do you have to modify the f4 call below to make this work? 65 | f4(d) 66 | -------------------------------------------------------------------------------- /src/12_scopes.py: -------------------------------------------------------------------------------- 1 | # Experiment with scopes in Python. 2 | # Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables 3 | 4 | # When you use a variable in a function, it's local in scope to the function. 5 | x = 12 6 | 7 | def change_x(): 8 | x = 99 9 | 10 | change_x() 11 | 12 | # This prints 12. What do we have to modify in change_x() to get it to print 99? 13 | print(x) 14 | 15 | 16 | # This nested function has a similar problem. 17 | 18 | def outer(): 19 | y = 120 20 | 21 | def inner(): 22 | y = 999 23 | 24 | inner() 25 | 26 | # This prints 120. What do we have to change in inner() to get it to print 27 | # 999? 28 | # Note: Google "python nested function scope". 29 | print(y) 30 | 31 | 32 | outer() 33 | -------------------------------------------------------------------------------- /src/13_file_io.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python makes performing file I/O simple. Take a look 3 | at how to read and write to files here: 4 | 5 | https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files 6 | """ 7 | 8 | # Open up the "foo.txt" file (which already exists) for reading 9 | # Print all the contents of the file, then close the file 10 | # Note: pay close attention to your current directory when trying to open "foo.txt" 11 | 12 | # YOUR CODE HERE 13 | 14 | # Open up a file called "bar.txt" (which doesn't exist yet) for 15 | # writing. Write three lines of arbitrary content to that file, 16 | # then close the file. Open up "bar.txt" and inspect it to make 17 | # sure that it contains what you expect it to contain 18 | 19 | # YOUR CODE HERE -------------------------------------------------------------------------------- /src/14_cal.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Python standard library's 'calendar' module allows you to 3 | render a calendar to your terminal. 4 | https://docs.python.org/3.6/library/calendar.html 5 | 6 | Write a program that accepts user input of the form 7 | `14_cal.py [month] [year]` 8 | and does the following: 9 | - If the user doesn't specify any input, your program should 10 | print the calendar for the current month. The 'datetime' 11 | module may be helpful for this. 12 | - If the user specifies one argument, assume they passed in a 13 | month and render the calendar for that month of the current year. 14 | - If the user specifies two arguments, assume they passed in 15 | both the month and the year. Render the calendar for that 16 | month and year. 17 | - Otherwise, print a usage statement to the terminal indicating 18 | the format that your program expects arguments to be given. 19 | Then exit the program. 20 | 21 | Note: the user should provide argument input (in the initial call to run the file) and not 22 | prompted input. Also, the brackets around year are to denote that the argument is 23 | optional, as this is a common convention in documentation. 24 | 25 | This would mean that from the command line you would call `python3 14_cal.py 4 2015` to 26 | print out a calendar for April in 2015, but if you omit either the year or both values, 27 | it should use today’s date to get the month and year. 28 | """ 29 | 30 | import sys 31 | import calendar 32 | from datetime import datetime -------------------------------------------------------------------------------- /src/15_classes.py: -------------------------------------------------------------------------------- 1 | # Make a class LatLon that can be passed parameters `lat` and `lon` to the 2 | # constructor 3 | 4 | # YOUR CODE HERE 5 | 6 | # Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the 7 | # constructor. It should inherit from LatLon. Look up the `super` method. 8 | 9 | # YOUR CODE HERE 10 | 11 | # Make a class Geocache that can be passed parameters `name`, `difficulty`, 12 | # `size`, `lat`, and `lon` to the constructor. What should it inherit from? 13 | 14 | # YOUR CODE HERE 15 | 16 | # Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 17 | 18 | # YOUR CODE HERE 19 | 20 | # Without changing the following line, how can you make it print into something 21 | # more human-readable? Hint: Look up the `object.__str__` method 22 | print(waypoint) 23 | 24 | # Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 25 | 26 | # YOUR CODE HERE 27 | 28 | # Print it--also make this print more nicely 29 | print(geocache) 30 | -------------------------------------------------------------------------------- /src/foo.txt: -------------------------------------------------------------------------------- 1 | Do you bite your thumb at us, sir? 2 | I do bite my thumb, sir. 3 | Do you bite your thumb at us, sir? 4 | No, sir. I do not bite my thumb at you, sir, but I bite my thumb, sir. 5 | Do you quarrel, sir? 6 | Quarrel, sir? No, sir. --------------------------------------------------------------------------------