diff --git a/FAQ.md b/FAQ.md new file mode 100644 index 0000000000..cbdac517b2 --- /dev/null +++ b/FAQ.md @@ -0,0 +1,618 @@ +# FAQ + + + +## Contents + +### General CS + +* [What are some things we can do to prepare for CS?](#q100) +* [What are some ways to learn a new language?](#q3600) +* [Why test code frequently?](#q3700) +* [Why isn't official documentation more helpful than Stack Overflow?](#q3800) +* [During an interview, what do I do if I can't remember the exact syntax?](#q3900) + +### General Python + +* [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) +* [How do you get out of the Python built-in `help`?](#q400) +* [Are there any helpful VS Code extensions that are recommend for using with Python?](#q500) +* [I'm on Windows; what command do I use to run Python?](#q600) +* [What version of Python do I need?](#q700) +* [How do I get out of the Python REPL?](#q900) +* [What does "REPL" mean?](#q1000) +* [I'm on a Mac and when I run Python it says I'm on version 2.7. Why?](#q1100) +* [Does Python use tabs or spaces?](#q1200) +* [Can you use boolean shortcut assignments?](#q1700) +* [Can you do anonymous functions?](#q1800) +* [What are all those method names with double underscores around them?](#q2000) +* [Where are good Python docs?](#q2600) +* [Which linter?](#q2700) +* [What's the difference between __repr__ and __str__?](#q3300) +* [How does `sys.argv` work?](#q3400) + +### Pipenv + +* [Do I need to use pipenv?](#q800) +* [When do we run pipenv shell?](#q2200) +* [How do I get out of the pipenv shell?](#q2300) +* [How do I install additional packages from pipenv?](#q2400) +* [Is it possible to use system-wide packages from inside the virtual environment?](#q2500) + +### Object-Oriented Programming + +* [Why is there such a debate between OOP and functional programming, and why should we care?](#q200) +* [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) +* [Can you dynamically add new methods/properties to class through other functions? Or must all properties/methods be declared at once?](#q2800) +* [If a subclass inherits from two superclasses with a method of the same name, which method will the subclass use?](#q3000) +* [How to handle multiple inheritance and why/when to do it in the first place?](#q3100) + +### Python Scoping + +* [Does Python have hoisting?](#q1400) +* [Does scoping work similar to other languages?](#q1500) +* [Can you return a reference to a function from another function? Or store it in a variable?](#q1600) +* [Can you do anonymous functions?](#q1800) + +### Types + +* [How do I convert an iterator into a list?](#q1300) +* [Is a dict like a JavaScript object?](#q1900) +* [How do I get a value from a dict?](#q2100) +* [Why use tuples instead of lists?](#q3200) +* [How do I concatenate two arrays into a single array?](#q3500) + +## Questions + + +### What are some things we can do to prepare for CS? + +* [CS Wiki](https://github.com/LambdaSchool/CS-Wiki/wiki) +* [Polya's Problem Solving Techniques](https://github.com/LambdaSchool/CS-Wiki/wiki/Polya%27s-Problem-Solving-Techniques) +* [Solving Programming Problems](https://github.com/LambdaSchool/CS-Wiki/wiki/Solving-Programming-Problems) +* [CS Reading List](https://github.com/LambdaSchool/CS-Wiki/wiki/Computer-Science-Reading-List) +* [How to Google effectively](https://github.com/LambdaSchool/CS-Wiki/wiki/How-to-Google-Effectively) +* [How to read specs and code](https://github.com/LambdaSchool/CS-Wiki/wiki/How-to-Read-Specifications-and-Code) +* [Command line primer](https://github.com/LambdaSchool/CS-Wiki/wiki/Command-Line-Primer) +* [Coding style guidelines](https://github.com/LambdaSchool/CS-Wiki/wiki/CS-Coding-Style-Guidelines) + +------------------------------------------------------------------------ + + +### Why is there such a debate between OOP and functional programming, and why should we care? + +There are a lot of [programming +paradigms](https://en.wikipedia.org/wiki/Programming_paradigm) and they all have +their strengths and weaknesses when it comes to solving different types of +problems. + +People can be quite opinionated about their favorites, but it's important to +remember that no one language or paradigm is the right tool for all jobs. And, +additionally, that virtually all problems can be solved in any of the +declarative or imperative paradigms. (Some might produce cleaner, more elegant +code for a particular problem.) + +Paradigms are the hardest thing to learn because you often have to take all the +knowledge you have about solving a problem in another paradigm and throw it out +the window. You have to learn new patterns and techniques to be effective. + +But we encourage this kind of learning because most popular languages are to +some degree _multi-paradigm_, and the more techniques you know from more +paradigms, the more effective you are in that multi-paradigm langage. + +------------------------------------------------------------------------ + + +### 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? + +Using `join()` to join large numbers of strings is definitely faster in Python +than using the `+` operator to do it. The reason is that every time you `join()` +or use the `+` operator, a new string is created. So if you only have to +`join()` once, versus using `+` hundreds of times, you'll run faster. + +That said, if you want to use the `join()` approach, you'll have to have all +your strings in a list, which uses more memory than just having the two or three +that you need at a time to use `+`. So there's a tradeoff. + +Another tradeoff might be in readability. It might be easier to read the `+` +version. That's worth something. + +Finally, if `+` is fast enough for this case, it might not be worth the time to +bother with making a list of strings to `join()`. + +* [Speed comparison with different ways of concatenating strings](https://waymoot.org/home/python_string/) + +------------------------------------------------------------------------ + + +### How do you get out of the Python built-in `help`? + +Hit `q` for "quit". + +It's a common command in Unix "pagers" (programs that show documents a page at a +time). + +------------------------------------------------------------------------ + + +### Are there any helpful VS Code extensions that are recommend for using with Python? + +* [Official VS Code Python Extension](https://code.visualstudio.com/docs/languages/python) + +------------------------------------------------------------------------ + + +### I'm on Windows; what command do I use to run Python? + +If you're running in PowerShell or cmd, use: + +``` +py +``` + +If in bash, use `python` or `python3`. + +------------------------------------------------------------------------ + + +### What version of Python do I need? + +You should have version 3.7 or higher. Test with: + +```shell +python --version +``` + +------------------------------------------------------------------------ + + +### Do I need to use pipenv? + +You should. Good Python devs know how. + +------------------------------------------------------------------------ + + +### How do I get out of the Python REPL? + +Hit `CTRL-D`. This is the way End-Of-File is signified in Unix-likes. + +------------------------------------------------------------------------ + + +### What does "REPL" mean? + +_Read, Evaluate, Print Loop_. + +It reads your input, evaluates it, and prints the result. And loops. + +------------------------------------------------------------------------ + + +### I'm on a Mac and when I run Python it says I'm on version 2.7. Why? + +Macs come with version 2.7 by default. You'll need to install version 3. + +And preferable use `pipenv` after that. + +------------------------------------------------------------------------ + + +### Does Python use tabs or spaces? + +[PEP 8](https://www.python.org/dev/peps/pep-0008/) says four spaces. + +------------------------------------------------------------------------ + + +### How do I convert an iterator into a list? + +Cast it: + +```python +list(range(5)) +``` + +produces: + +```python +[0, 1, 2, 3, 4] +``` + +------------------------------------------------------------------------ + + +### Does Python have hoisting? + +No. + +* [What is hoisting?](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) + +------------------------------------------------------------------------ + + +### Does scoping work similar to other languages? + +Generally, and also not really. Variables are either global or function-local. + +Since there are no declarations, there's no block-level scope. + +It is similar to `var` in JavaScript. + +------------------------------------------------------------------------ + + +### Can you return a reference to a function from another function? Or store it in a variable? + +Yes. Functions are [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen). + +------------------------------------------------------------------------ + + +### Can you use boolean shortcut assignments? + +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. + +```python +x = SomethingFalsey or 5 +``` + +------------------------------------------------------------------------ + + +### Can you do anonymous functions? + +You can use `lambda` for simple functions: + +```python +adder = lambda x, y: x + y + +adder(4, 5) # 9 + +do_some_math(4, 5, lambda x, y: y - x) +``` + +------------------------------------------------------------------------ + + +### Is a dict like a JavaScript object? + +Sort of. + +The syntax is different, though. In Python you must use `[]` notation to access elements. And you must use `"` around the key names. + +------------------------------------------------------------------------ + + +### What are all those method names with double underscores around them? + +Those are function you typically don't need to use, but can override or call if you wish. + +Most commonly used are: + +* `__init__()` is the constructor for objects +* `__str__()` returns a string representation of the object +* `__repr__()` returns a string representation of the object, for debugging + +------------------------------------------------------------------------ + + +### How do I get a value from a dict? + +```python +d = { + "a": 2, + "b": 3 +} + +print(d["a"]) +``` + +You don't use dot notation. + +------------------------------------------------------------------------ + + +### When do we run pipenv shell? + +`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. + +------------------------------------------------------------------------ + + +### How do I get out of the pipenv shell? + +Type `exit`. + +------------------------------------------------------------------------ + + +### How do I install additional packages from pipenv? + +```shell +pipenv install packagename +``` + +------------------------------------------------------------------------ + + +### Is it possible to use system-wide packages from inside the virtual environment? + +This is [not recommended](https://pipenv.readthedocs.io/en/latest/diagnose/#no-module-named-module-name). + +------------------------------------------------------------------------ + + +### Where are good Python docs? + +* [Official documentation](https://docs.python.org/3/) tutorial and library reference. + +The official docs might be hard to read at first, but you'll get used to them +quickly + +------------------------------------------------------------------------ + + +### Which linter? + +Pylint or Flake8. The latter seems to be a bit more popular. + +------------------------------------------------------------------------ + + +### Can you dynamically add new methods/properties to class through other functions? Or must all properties/methods be declared at once? + +You can add them dynamically at runtime, but you have to add them to the class itself: + +```python +class Foo(): + pass + +f = Foo() + +Foo.x = 12 # Dynamically add property to class + +f.x == 12 # True! + +def a_method(self): + print("Hi") + +Foo.hi = a_method # Dynamically add method to class + +f.hi() # Prints "Hi" +``` + +This is not a common thing to see in Python, however. + +------------------------------------------------------------------------ + + +### 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? + +Yes. + +------------------------------------------------------------------------ + + +### If a subclass inherits from two superclasses with a method of the same name, which method will the subclass use? + +The answer to this is twofold: + +1. Lots of devs and shops frown on multiple inheritance, so maybe just don't do + it. + ([Discussion](https://softwareengineering.stackexchange.com/questions/218458/is-there-any-real-reason-multiple-inheritance-is-hated)) + +2. As for the order in which methods of the same name are resolved, check out + the [MRO Algorithm](https://en.wikipedia.org/wiki/C3_linearization) which is + what Python uses. + + +------------------------------------------------------------------------ + + +### How to handle multiple inheritance and why/when to do it in the first place? + +```python +class Base1: + pass + +class Base2: + pass + +class Derived(Base1, Base2): # Multiple inheritance + pass +``` + +Sometimes multiple inheritance can lead to elegant solutions when a subclass +needs attributes from multiple, otherwise-unrelated parent classes. + +However, [a lot of people find it's not worth the +trouble](https://softwareengineering.stackexchange.com/questions/218458/is-there-any-real-reason-multiple-inheritance-is-hated)) +and opt for other solutions, like composition. + +------------------------------------------------------------------------ + + +### Why use tuples instead of lists? + +* 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. +* Tuples are faster than lists to access. +* Some tuples (containing primitive types), can be used as `dict` keys. + +------------------------------------------------------------------------ + + +### What's the difference between __repr__ and __str__? + +Generally speaking, `__repr__` is the string a dev would want to see if they +dumped an object to the screen. `__str__` is the string a user would want to see +if the object were `print()`ed. + +The output of `__repr__` should be _valid Python code that can reproduce the +object_. + +```python +class Goat: + def __init__(self, leg_count): + self.leg_count = leg_count + + def __repr__(self): + return f'Goat(leg_count={self.leg_count})' + + def __str__(self): + return f'a goat with {self.leg_count} legs' +``` + +In action: + +```python +>>> g = Goat(4) +>>> str(g) +'a goat with 4 legs' +>>> g +Goat(leg_count=4) +>>> Goat(leg_count=4) # output of __repr__ makes a clone of that object! +Goat(leg_count=4) +``` + +------------------------------------------------------------------------ + + +### How does `sys.argv` work? + +It's a list that holds _command line arguments_. This is a way for a user to run +your program and specify different behavior from the command line. + +Here's a small program that prints the command line arguments: + +```python +import sys + +for i in range(len(sys.argv)): + print(f'Argument #{i} is: {sys.argv[i]}') +``` + +and here's some output, assuming you named the script `foo.py`: + +```screen +$ python foo.py +Argument #0 is: foo.py +``` + +```screen +$ python foo.py antelope buffalo +Argument #0 is: foo.py +Argument #1 is: antelope +Argument #2 is: buffalo +``` + +Note that the 0th element in the list is the name of the program. + +Here's another program that prints up to whatever number the user specifies: + +```python +import sys + +for i in range(int(sys.argv[1])): + print(i+1) +``` + +Example runs: + +```screen +$ python foo.py 2 +1 +2 +``` + +```screen +$ python foo.py 4 +1 +2 +3 +4 +``` + +------------------------------------------------------------------------ + + +### How do I concatenate two arrays into a single array? + +Use `extend()`. + +```python +a = [1, 2, 3] +b = [4, 5, 6] + +a.extend(b) + +print(a) # [ 1, 2, 3, 4, 5, 6 ] +``` + +------------------------------------------------------------------------ + + +### What are some ways to learn a new language? + +* Figure out how variables and functions work. +* Build small toy programs to test individual features. +* Build a larger project that exercises many features. +* Don't get frustrated! Treat the problem like a curiosity, a thing to be studied. +* Do small tutorials or code-alongs. +* Find docs you like. +* Learn the differences between this language and one you know. +* Learn this language's way of doing the things you know. + +Things to look for in the new language: + +* Collections (arrays, vectors, dictionaries) +* Data types +* Iterators +* Flow control (if, while, loops, etc) +* Functions +* etc. + +------------------------------------------------------------------------ + + +### Why test code frequently? + +It's often better to make progress in small increments than to write a bunch of +stuff and test it in one go. + +Also, it's easier to stay motivated if you spend 10 minutes getting a first +version going, even if it's missing 99% of its features, and then starting to +iterate on that. + +------------------------------------------------------------------------ + + +### Why isn't official documentation more helpful than Stack Overflow? + +Often official documentation is more geared toward being a concise reference. +Stack Overflow is more of an example-based learning environment. + +Sometimes you need to know the specific details. In those cases, you can dig +into the spec, with all it's lawyerly language, and try to decipher what it is +you have to do. + +Other times, you just need a getting-started example, and Stack Overflow is +great for that. + +Both types of documentation have their purpose. + +------------------------------------------------------------------------ + + +### During an interview, what do I do if I can't remember the exact syntax? + +Just say so. + +"I can't remember how to add an element to the end of the list in Python... is +it `push()`? In any case, we'll call the function here that does that." + +(Turns out it's `append()` in Python, but being honest and describing what it is +your're trying to do will get you 99% of the way there in an interview.) diff --git a/README.md b/README.md index 400b72d43e..f54d2b3343 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ -# Intro to Python - -## Goals +# Intro to Python I It's time to learn a new language! Python! @@ -57,254 +55,59 @@ best for learning new languages. You can exit the virtual environment by typing `exit`. -## Day 1 - -### Goals +## Goals * Learn the basic syntax and structure of Python -### Summary - -* Implement a number of tiny Python programs that demonstrate Python syntax. +## Summary -### Instructions +* Implement a number of tiny Python programs that demonstrate Python syntax and + language concepts. -Take a look in the `src/` directory. +## Instructions -NOTE: `adv/` is for Day 2, so ignore it for today. +Each directory inside the `src/` directory presents exercises revolving around a +particular concept in Python. Not all of these concepts are unique to Python (in +fact, most probably aren't). This means that you can leverage knowledge you've +obtained via exposure to other programming languages towards learning Python. -Suggested order for implementing the toy programs: +The suggested order for going through each of the directories is: * `hello` -- Hello world * `bignum` -- Print some big numbers * `datatypes` -- Experiment with type conversion * `modules` -- Learn to import from modules -* `printf` -- Formatted print output +* `printing` -- Formatted print output * `lists` -- Python's version of arrays * `tuples` -- Immutable lists typically for heterogenous data -* `slice` -- Accessing parts of lists -* `comp` -- List comprehensions -* `dicts` -- Dictionaries -* `func` -- Functions +* `slices` -- Accessing parts of lists +* `comprehensions` -- List comprehensions +* `dictionaries` -- Dictionaries +* `functions` -- Functions * `args` -- Arguments and Keyword Arguments -* `scope` -- Global, Local, and Non-Local scope -* `fileio` -- Read and write from files -* `cal` -- Experiment with module imports -* `obj` -- Classes and objects - -## Day 2 - -### Goals - -* Solidify the Python basics - - -### Summary - -* Implement a basic text adventure game -* Add classes for rooms and the player -* Add a simple parser that reads user input and performs actions - -### Instructions - -This is in `src/adv/`. Check it out! - -* Put the Room class in room.py based on what you see in `adv.py`. - -* Put the Player class in `player.py`. - -* Follow the instructions `adv.py`. - -* Figure out what all those `.pyc` files are that appear after you successfully - run the program. - -## Day 3 - -### Goals - -* Prepare for more OOP techniques -* Practice classes and lists - -### Summary - -* Add items to the game that the user can carry around -* Make rooms able to hold multiple items -* Make the player able to carry multiple items -* Add two-word commands to the parser -* Add the `get` and `drop` commands to the parser - -### Instructions - -* Add an `Item` class in a file `item.py`. - - * This will be the _base class_ for specialized item types to be declared - later. - - * The item should have `name` and `description` attributes. - - * Hint: the name should be one word for ease in parsing later. - -* Add capability to add items to rooms. - - * The `Room` class should be extended with a `list` that holds the `Item`s - that are currently in that room. - - * Add functionality to the main loop that prints out all the items that are - visible to the player when they are in that room. - -* Add capability to add `Item`s to the player's inventory. The inventory can - also be a `list` of items "in" the player, similar to how `Item`s can be in a - `Room`. - -* Add a new type of sentence the parser can understand: two words. - - * Until now, the parser could just understand one sentence form: - - `verb` - - such as "n" or "q". - - * But now we want to add the form: - - `verb` `object` - - such as "take coins" or "drop sword". - - * Split the entered command and see if it has 1 or 2 words in it to determine - if it's the first or second form. - -* Implement support for the verb `get` followed by an `Item` name. This will be - used to pick up `Item`s. - - * If the user enters `get` or `take` followed by an `Item` name, look at the - contents of the current `Room` to see if the item is there. - - * If it is there, remove it from the `Room` contents, and add it to the - `Player` contents. - - * If it's not there, print an error message telling the user so. - -* Implement support for the verb `drop` followed by an `Item` name. This is the - opposite of `get`/`take`. - -* Add the `i` and `inventory` commands that both show a list of items currently - carried by the player. - -## Day 4 - -### Goals - -* Practice inheritance -* Practice method overriding -* Be able to call superclass methods -* Implement a callback/event structure - -### Summary - -* Add scoring -* Subclass items into treasures -* Subclass items into light sources -* Add methods to notify items when they are picked up or dropped -* Add light and darkness to the game - -### Instructions - -* Add a `score` to your `Player` class. Set it to 0. - -* Add a single word command, `score`, that the user can type in to see their - current score. - -* Add a subclass to `Item` called `Treasure`. - - * The `Treasure` constructor should accept a name, description, and value. - -* During world creation, add three `Treasure`s to convenient `Room`s. - -* Add an `on_take` method to `Item`. - - * Call this method when the `Item` is picked up by the player. - - * The `Item` can use this to run additional code when it is picked up. - -* Override `on_take` in `Treasure` so that the player gets the value of the - `Treasure` added to their `score` attribute _but only the first time the - treasure is picked up_. - - * If the treasure is dropped and picked up again later, the player should - _not_ have the value added to their score again. - -* Add an `on_drop` method to `Item`. Implement it similar to `on_take`. - -* Add a subclass to `Item` called `LightSource`. - -* During world creation, add a `lamp` `LightSource` to a convenient `Room`. - -* Override `on_drop` in `LightSource` that tells the player "It's not wise to - drop your source of light!" if the player drops it. (But still lets them drop - it.) - -* Add an attribute to `Room` called `is_light` that is `True` if the `Room` is - naturally illuminated, or `False` if a `LightSource` is required to see what - is in the room. - -* Modify the main loop to test if there is light in the `Room` (i.e. if - `is_light` is `True` **or** there is a `LightSource` item in the `Room`'s - contents **or** if there is a `LightSource` item in the `Player`'s contents). - - * If there is light in the room, display name, description, and contents as - normal. - - * If there isn't, print out "It's pitch black!" instead. - - * Hint: `isinstance` might help you figure out if there's a `LightSource` - among all the nearby `Item`s. - -* Modify the `get`/`take` code to print "Good luck finding that in the dark!" if - the user tries to pick up an `Item` in the dark. +* `scopes` -- Global, Local, and Non-Local scope +* `file_io` -- Read and write from files +* `cal` -- Experiment with module imports and implement a text-based calendar +* `classes` -- Classes and objects ## Stretch Goals -In arbitrary order: - -* Add more rooms. - -* Add more items to the game. - -* Add a way to win. - -* Add more to the parser. - - * Remember the last `Item` mentioned and substitute that if the user types - "it" later, e.g. - - ``` - take sword - drop it - ``` - - * Add `Item`s with adjectives, like "rusty sword" and "silver sword". - - * Modify the parser to handle commands like "take rusty sword" as well as - "take sword". - - * If the user is in a room that contains both the rusty sword _and_ silver - sword, and they type "take sword", the parser should say, "I don't know - which you mean: rusty sword or silver sword." - -* Modify the code that calls `on_take` to check the return value. If `on_take` - returns `False`, then don't continue picking up the object. (I.e. prevent the - user from picking it up.) - - * This enables you to add logic to `on_take` to code things like "don't allow - the user to pick up the dirt unless they're holding the shovel. - -* Add monsters. - -* Add the `attack` verb that allows you to specify a monster to attack. - -* Add an `on_attack` method to the monster class. - -* Similar to the `on_take` return value modification, above, have `on_attack` - prevent the attack from succeeding unless the user possesses a `sword` item. - -* Come up with more stretch goals! The sky's the limit! +1. One of Python's main philosophical tenets is its emphasis on readability. To + that end, the Python community has standardized around a style guide called + [PEP 8](https://www.python.org/dev/peps/pep-0008/). Take a look at it and + then go over the code you've written and make sure it adheres to what PEP 8 + recommends. Alternatively, PEP 8 linters exist for most code editors (you can + find instructions on installing a Python linter for VSCode + [here](https://code.visualstudio.com/docs/python/linting)). Try installing + one for your editor! + +2. Rewrite code challenges you've solved before or projects you've implemented + before in a different language in Python. Start getting in as much practice + with the language as possible! + +3. Write a program to determine if a number, given on the command line, is prime. + + 1. How can you optimize this program? + 2. Implement [The Sieve of + Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one + of the oldest algorithms known (ca. 200 BC). diff --git a/src/00_hello.py b/src/00_hello.py new file mode 100644 index 0000000000..a397544874 --- /dev/null +++ b/src/00_hello.py @@ -0,0 +1,2 @@ +# Print "Hello, world!" to your terminal +print('Hello, world!') diff --git a/src/01_bignum.py b/src/01_bignum.py new file mode 100644 index 0000000000..2b41cda051 --- /dev/null +++ b/src/01_bignum.py @@ -0,0 +1,5 @@ +# Print out 2 to the 65536 power +# (try doing the same thing in the JS console and see what it outputs) + +# YOUR CODE HERE +print(pow(2, 65536)) diff --git a/src/02_datatypes.py b/src/02_datatypes.py new file mode 100644 index 0000000000..5a6c8ca465 --- /dev/null +++ b/src/02_datatypes.py @@ -0,0 +1,22 @@ +""" +Python is a strongly-typed language under the hood, which means +that the types of values matter, especially when we're trying +to perform operations on them. + +Note that if you try running the following code without making any +changes, you'll get a TypeError saying you can't perform an operation +on a string and an integer. +""" + +x = 5 +y = "7" + +# Write a print statement that combines x + y into the integer value 12 + +# YOUR CODE HERE +print(x + int(y)) + +# Write a print statement that combines x + y into the string value 57 + +# YOUR CODE HERE +print(str(x) + y) diff --git a/src/03_modules.py b/src/03_modules.py new file mode 100644 index 0000000000..747f29fb0e --- /dev/null +++ b/src/03_modules.py @@ -0,0 +1,32 @@ +""" +In this exercise, you'll be playing around with the sys module, +which allows you to access many system specific variables and +methods, and the os module, which gives you access to lower- +level operating system functionality. +""" + +import os +import sys +# See docs for the sys module: https://docs.python.org/3.7/library/sys.html + +# Print out the command line arguments in sys.argv, one per line: +# YOUR CODE HERE +print(sys.argv) +# Print out the OS platform you're using: +# YOUR CODE HERE +print(sys.platform) +# Print out the version of Python you're using: +# YOUR CODE HERE +print(sys.version) + +# See the docs for the OS module: https://docs.python.org/3.7/library/os.html + +# Print the current process ID +# YOUR CODE HERE +print(os.getpid()) +# Print the current working directory (cwd): +# YOUR CODE HERE +print(os.getcwd()) +# Print out your machine's login name +# YOUR CODE HERE +print(os.getlogin()) diff --git a/src/04_printing.py b/src/04_printing.py new file mode 100644 index 0000000000..4208703833 --- /dev/null +++ b/src/04_printing.py @@ -0,0 +1,18 @@ +""" +Python provides a number of ways to perform printing. Research +how to print using the printf operator, the `format` string +method, and by using f-strings. +""" + +x = 10 +y = 2.24552 +z = "I like turtles!" + +# Using the printf operator (%), print the following feeding in the values of x, +# y, and z: +# x is 10, y is 2.25, z is "I like turtles!" +print("x is %d, y is %.2f, z is \"%s\"" % (x, y, z)) +# Use the 'format' string method to print the same thing +print("x is {}, y is {:.2f}, z is \"{}\"".format(x, y, z)) +# Finally, print the same thing using an f-string +print(f'x is {x}, y is {round(y, 2)}, z is "{z}"') diff --git a/src/day-1-toy/lists.py b/src/05_lists.py similarity index 65% rename from src/day-1-toy/lists.py rename to src/05_lists.py index 6076f340a9..8601b4dc93 100644 --- a/src/day-1-toy/lists.py +++ b/src/05_lists.py @@ -7,23 +7,29 @@ # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] -# [command here] +# YOUR CODE HERE +x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] -# [command here] +# YOUR CODE HERE +x.extend(y) print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] -# [command here] +# YOUR CODE HERE +x.remove(8) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] -# [command here] +# YOUR CODE HERE +x.insert(5, 99) print(x) # Print the length of list x -# [command here] +# YOUR CODE HERE print(len(x)) - -# Using a for loop, print all the element values multiplied by 1000 \ No newline at end of file +# Print all the values in x multiplied by 1000 +# YOUR CODE HERE +for num in x: + print(num * 1000) diff --git a/src/06_tuples.py b/src/06_tuples.py new file mode 100644 index 0000000000..c3bf2ab809 --- /dev/null +++ b/src/06_tuples.py @@ -0,0 +1,47 @@ +""" +Python tuples are sort of like lists, except they're immutable and +are usually used to hold heterogenous data, as opposed to lists +which are typically used to hold homogenous data. Tuples use +parens instead of square brackets. +More specifically, tuples are faster than lists. If you're looking +to just define a constant set of values and that set of values +never needs to be mutated, use a tuple instead of a list. +Additionally, your code will be safer if you opt to "write-protect" +data that does not need to be changed. Tuples enforce immutability +automatically. +""" + +# # Example: + +import math + + +def dist(a, b): + """Compute the distance between two x,y points.""" + x0, y0 = a # Destructuring assignment + x1, y1 = b + + return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) + + +a = (2, 7) # <-- x,y coordinates stored in tuples +b = (-14, 72) + +# Prints "Distance is 66.94" +print("Distance is: {:.2f}".format(dist(a, b))) + + +# Write a function `print_tuple` that prints all the values in a tuple + +# YOUR CODE HERE +def print_tuple(x): + for num in x: + print(num) + + +t = (1, 2, 5, 7, 99) +print_tuple(t) # Prints 1 2 5 7 99, one per line + +# Declare a tuple of 1 element then print it +u = (1,) # What needs to be added to make this work? +print_tuple(u) diff --git a/src/07_slices.py b/src/07_slices.py new file mode 100644 index 0000000000..7fe7b647c2 --- /dev/null +++ b/src/07_slices.py @@ -0,0 +1,35 @@ +""" +# Python exposes a terse and intuitive syntax for performing +# slicing on lists and strings. This makes it easy to reference +# only a portion of a list or string. +# This Stack Overflow answer provides a brief but thorough +# overview: https://stackoverflow.com/a/509295 +# Use Python's slice syntax to achieve the following: +""" + +a = [2, 4, 1, 7, 9, 6] + +# Output the second element: 4: +print(a[1]) + +# Output the second-to-last element: 9 +print(a[-2]) + +# Output the last three elements in the array: [7, 9, 6] +print(a[-3:]) + +# Output the two middle elements in the array: [1, 7] +print(a[2:4]) + +# Output every element except the first one: [4, 1, 7, 9, 6] +print(a[1:]) + +# Output every element except the last one: [2, 4, 1, 7, 9] +print(a[:-1]) + +# For string s... + +s = "Hello, world!" + +# Output just the 8th-12th characters: "world" +print(s[-6:-1]) diff --git a/src/day-1-toy/comp.py b/src/08_comprehensions.py similarity index 53% rename from src/day-1-toy/comp.py rename to src/08_comprehensions.py index 083e9b9140..e12c3fc52e 100644 --- a/src/day-1-toy/comp.py +++ b/src/08_comprehensions.py @@ -1,22 +1,36 @@ +""" +List comprehensions are one cool and unique feature of Python. +They essentially act as a terse and concise way of initializing +and populating a list given some expression that specifies how +the list should be populated. + +Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions +for more info regarding list comprehensions. +""" + # Write a list comprehension to produce the array [1, 2, 3, 4, 5] y = [] - -print (y) +for x in range(1, 6): + y.append(x) +print(y) # Write a list comprehension to produce the cubes of the numbers 0-9: # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] y = [] - +for x in range(10): + y.append(x**3) print(y) # Write a list comprehension to produce the uppercase version of all the # elements in array a. Hint: "foo".upper() is "FOO". a = ["foo", "bar", "baz"] - y = [] +for x in a: + x = x.upper() + y.append(x) print(y) @@ -26,7 +40,6 @@ x = input("Enter comma-separated numbers: ").split(',') # What do you need between the square brackets to make it work? -y = [] +y = [i for i in x if int(i) % 2 == 0] print(y) - diff --git a/src/09_dictionaries.py b/src/09_dictionaries.py new file mode 100644 index 0000000000..a7e2475405 --- /dev/null +++ b/src/09_dictionaries.py @@ -0,0 +1,48 @@ +""" +Dictionaries are Python's implementation of associative arrays. +There's not much different with Python's version compared to what +you'll find in other languages (though you can also initialize and +populate dictionaries using comprehensions just like you can with +lists!). + +The docs can be found here: +https://docs.python.org/3/tutorial/datastructures.html#dictionaries + +For this exercise, you have a list of dictionaries. Each dictionary +has the following keys: + - lat: a signed integer representing a latitude value + - lon: a signed integer representing a longitude value + - name: a name string for this location +""" + +waypoints = [ + { + "lat": 43, + "lon": -121, + "name": "a place" + }, + { + "lat": 41, + "lon": -123, + "name": "another place" + }, + { + "lat": 43, + "lon": -122, + "name": "a third place" + } +] +# Add a new waypoint to the list +# YOUR CODE HERE +waypoints.append({"lat": 27, "lon": -12, "name": "my house"}) + +# Modify the dictionary with name "a place" such that its longitude +# value is -130 and change its name to "not a real place" +# YOUR CODE HERE +waypoints[0]["lon"] = -130 +waypoints[0]["name"] = "not a real place" + +# Write a loop that prints out all the field values for all the waypoints +# YOUR CODE HERE +for i in waypoints: + print(i) diff --git a/src/10_functions.py b/src/10_functions.py new file mode 100644 index 0000000000..b1f6ca344b --- /dev/null +++ b/src/10_functions.py @@ -0,0 +1,20 @@ +# Write a function is_even that will return true if the passed-in number is even. + +# YOUR CODE HERE + +# Read a number from the keyboard +num = input("Enter a number: ") +num = int(num) + +# Print out "Even!" if the number is even. Otherwise print "Odd" + + +def evenOrOdd(num): + if num % 2 == 0: + print("Even!") + else: + print("Odd") + + +# YOUR CODE HERE +evenOrOdd(num) diff --git a/src/day-1-toy/args.py b/src/11_args.py similarity index 63% rename from src/day-1-toy/args.py rename to src/11_args.py index 06a830e4c8..e482ba2ccc 100644 --- a/src/day-1-toy/args.py +++ b/src/11_args.py @@ -4,14 +4,27 @@ # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. -#def f1(... +# YOUR CODE HERE + + +def f1(x, y): + return x + y + print(f1(1, 2)) -# Write a function f2 that takes any number of iteger arguments and prints the +# Write a function f2 that takes any number of integer arguments and prints the # sum. Google for "python arbitrary arguments" and look for "*args" -# def f2(... +# YOUR CODE HERE + + +def f2(*args): + total = 0 + for num in args: + total = total + num + return total + print(f2(1)) # Should print 1 print(f2(1, 3)) # Should print 4 @@ -21,37 +34,50 @@ a = [7, 6, 5, 4] # What thing do you have to add to make this work? +a = 22 print(f2(a)) # Should print 22 # Write a function f3 that accepts either one or two arguments. If one argument, # it returns that value plus 1. If two arguments, it returns the sum of the # arguments. Google "python default arguments" for a hint. -#def f3(... +# YOUR CODE HERE + + +def f3(x, y=0): + if x == x + y: + return x + 1 + else: + return x + y + print(f3(1, 2)) # Should print 3 print(f3(8)) # Should print 9 # Write a function f4 that accepts an arbitrary number of keyword arguments and -# prints ouf the keys and values like so: +# prints out the keys and values like so: # # key: foo, value: bar # key: baz, value: 12 # # Google "python keyword arguments". -#def f4(... +# YOUR CODE HERE +def f4(**kwargs): + for key, value in kwargs.items(): + print("key: {}, value: {}".format(key, value)) + # Should print # key: a, value: 12 # key: b, value: 30 f4(a=12, b=30) -# Should print -# key: city, value: Berkeley -# key: population, value: 121240 -# key: founded, value: "March 23, 1868" +# # Should print +# # key: city, value: Berkeley +# # key: population, value: 121240 +# # key: founded, value: "March 23, 1868" f4(city="Berkeley", population=121240, founded="March 23, 1868") d = { @@ -59,5 +85,5 @@ "hp": 3 } -# What thing do you have to add to make this work? -f4(d) \ No newline at end of file +# # What thing do you have to add to make this work? +f4(d=d) diff --git a/src/day-1-toy/scope.py b/src/12_scopes.py similarity index 87% rename from src/day-1-toy/scope.py rename to src/12_scopes.py index 68ecc6c412..c3d0e54e00 100644 --- a/src/day-1-toy/scope.py +++ b/src/12_scopes.py @@ -1,12 +1,15 @@ -# Experiment with scope in Python. +# Experiment with scopes in Python. # Good reading: https://www.programiz.com/python-programming/global-local-nonlocal-variables # When you use a variable in a function, it's local in scope to the function. x = 12 + def changeX(): + global x x = 99 + changeX() # This prints 12. What do we have to modify in changeX() to get it to print 99? @@ -19,6 +22,7 @@ def outer(): y = 120 def inner(): + nonlocal y y = 999 inner() @@ -27,4 +31,5 @@ def inner(): # 999? Google "python nested function scope". print(y) -outer() \ No newline at end of file + +outer() diff --git a/src/13_file_io.py b/src/13_file_io.py new file mode 100644 index 0000000000..b725cd74e2 --- /dev/null +++ b/src/13_file_io.py @@ -0,0 +1,26 @@ +""" +Python makes performing file I/O simple. Take a look +at how to read and write to files here: + +https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files +""" + +# Open up the "foo.txt" file (which already exists) for reading +# Print all the contents of the file, then close the file + +# YOUR CODE HERE +x = open('foo.txt', 'r') +for line in x: + print(line) +x.close() + +# Open up a file called "bar.txt" (which doesn't exist yet) for +# writing. Write three lines of arbitrary content to that file, +# then close the file. Open up "bar.txt" and inspect it to make +# sure that it contains what you expect it to contain + +# YOUR CODE HERE +string = 'Hello\nHow are you?\nI am fine' +y = open('bar.txt', 'w') +y.write(string) +y.close() \ No newline at end of file diff --git a/src/14_cal.py b/src/14_cal.py new file mode 100644 index 0000000000..b8a689b519 --- /dev/null +++ b/src/14_cal.py @@ -0,0 +1,43 @@ +""" +The Python standard library's 'calendar' module allows you to +render a calendar to your terminal. +https://docs.python.org/3.6/library/calendar.html + +Write a program that accepts user input of the form + `14_cal.py month [year]` +and does the following: + - If the user doesn't specify any input, your program should + print the calendar for the current month. The 'datetime' + module may be helpful for this. + - If the user specifies one argument, assume they passed in a + month and render the calendar for that month of the current year. + - If the user specifies two arguments, assume they passed in + both the month and the year. Render the calendar for that + month and year. + - Otherwise, print a usage statement to the terminal indicating + the format that your program expects arguments to be given. + Then exit the program. +""" + +import sys +import calendar +from datetime import datetime + +lengthArg = len(sys.argv) + +cal = calendar.TextCalendar() + +if lengthArg == 2: + month = None + year = int(sys.argv[1]) +elif lengthArg == 3: + month = int(sys.argv[1]) + year = int(sys.argv[2]) +else: + print("usage: cal.py [month] year") + sys.exit(1) + +if month != None: + cal.prmonth(year, month) +else: + cal.pryear(year) \ No newline at end of file diff --git a/src/15_classes.py b/src/15_classes.py new file mode 100644 index 0000000000..b77c3423d4 --- /dev/null +++ b/src/15_classes.py @@ -0,0 +1,44 @@ +# Make a class LatLon that can be passed parameters `lat` and `lon` to the +# constructor + +# YOUR CODE HERE +class LatLon: + def __init__(self, lat, lon): + self.lat = lat + self.lon = lon +# Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the +# constructor. It should inherit from LatLon. Look up the `super` method. +class Waypoint(LatLon): + def __init__(self, name, lat, lon): + super().__init__(lat, lon) + self.name = name + def __str__(self): + return 'Waypoint of %s: Lat %s and Lon %s' %(self.name, self.lat, self.lon) +# YOUR CODE HERE + +# Make a class Geocache that can be passed parameters `name`, `difficulty`, +# `size`, `lat`, and `lon` to the constructor. What should it inherit from? +# YOUR CODE HERE +class Geocache(Waypoint): + def __init__(self, name, difficulty, size, lat, lon): + super().__init__(name, lat, lon) + self.difficulty = difficulty + self.size = size + def __str__(self): + return f'Waypoint of {self.name}: Lat {self.lat}, Lon {self.lon}. Difficulty is {self.difficulty} and size is {self.size}' + +# Make a new waypoint and print it out: "Catacombs", 41.70505, -121.51521 +# YOUR CODE HERE +waypoint = Waypoint("Catacombs", 41.70505, -121.51521).__str__() + +# Without changing the following line, how can you make it print into something +# more human-readable? Hint: Look up the `object.__str__` method +print(waypoint) + +# Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 + +# YOUR CODE HERE +geocache = Geocache("Newberry Views", 1.5, 2, 44.052137, -121.41556).__str__() + +# Print it--also make this print more nicely +print(geocache) \ No newline at end of file diff --git a/src/bar.txt b/src/bar.txt new file mode 100644 index 0000000000..cfc792f806 --- /dev/null +++ b/src/bar.txt @@ -0,0 +1,3 @@ +Hello +How are you? +I am fine \ No newline at end of file diff --git a/src/day-1-toy/bignum.py b/src/day-1-toy/bignum.py deleted file mode 100644 index 77e8d66ffa..0000000000 --- a/src/day-1-toy/bignum.py +++ /dev/null @@ -1 +0,0 @@ -# Print out 2 to the 65536 power \ No newline at end of file diff --git a/src/day-1-toy/cal.py b/src/day-1-toy/cal.py deleted file mode 100644 index 2a3771eb5b..0000000000 --- a/src/day-1-toy/cal.py +++ /dev/null @@ -1,16 +0,0 @@ -# Use the 'calendar' module to draw calendars to the console -# https://docs.python.org/3.6/library/calendar.html -# -# Use the sys module to look for command line arguments in the `argv` list -# variable. -# -# If the user specifies two command line arguments, month and year, then draw -# the calendar for that month. - -# Stretch goal: if the user doesn't specify anything on the command line, show -# the calendar for the current month. See the 'datetime' module. - -# Hint: this should be about 15 lines of code. No loops are required. Read the -# docs for the calendar module closely. - -import sys diff --git a/src/day-1-toy/datatypes.py b/src/day-1-toy/datatypes.py deleted file mode 100644 index f5967611a7..0000000000 --- a/src/day-1-toy/datatypes.py +++ /dev/null @@ -1,8 +0,0 @@ -x = 5 -y = "7" - -# Write a print statement that combines x + y into the integer value 12 -print(x + y) - -# Write a print statement that combines x + y into the string value 57 -print(x + y) \ No newline at end of file diff --git a/src/day-1-toy/dicts.py b/src/day-1-toy/dicts.py deleted file mode 100644 index eac1779a42..0000000000 --- a/src/day-1-toy/dicts.py +++ /dev/null @@ -1,29 +0,0 @@ -# Make an array of dictionaries. Each dictionary should have keys: -# -# lat: the latitude -# lon: the longitude -# name: the waypoint name -# -# Make up three entries of various values. - -waypoints = [ - { - "lat": 43, - "lon": -121, - "name": "a place" - }, - { - "lat": 41, - "lon": -123, - "name": "another place" - }, - { - "lat": 43, - "lon": -122, - "name": "a third place" - } -] - -# Write a loop that prints out all the field values for all the waypoints - -# Add a new waypoint to the list diff --git a/src/day-1-toy/fileio.py b/src/day-1-toy/fileio.py deleted file mode 100644 index bc8e79b7cc..0000000000 --- a/src/day-1-toy/fileio.py +++ /dev/null @@ -1,12 +0,0 @@ -# Use open to open file "foo.txt" for reading - -# Print all the lines in the file - -# Close the file - - -# Use open to open file "bar.txt" for writing - -# Use the write() method to write three lines to the file - -# Close the file \ No newline at end of file diff --git a/src/day-1-toy/func.py b/src/day-1-toy/func.py deleted file mode 100644 index 2b7f435ffa..0000000000 --- a/src/day-1-toy/func.py +++ /dev/null @@ -1,6 +0,0 @@ -# Write a function is_even that will return true if the passed in number is even. - -# Read a number from the keyboard -num = input("Enter a number: ") - -# Print out "Even!" if the number is even. Otherwise print "Odd" \ No newline at end of file diff --git a/src/day-1-toy/hello.py b/src/day-1-toy/hello.py deleted file mode 100644 index 37968da4d4..0000000000 --- a/src/day-1-toy/hello.py +++ /dev/null @@ -1 +0,0 @@ -# Write Hello, world \ No newline at end of file diff --git a/src/day-1-toy/modules.py b/src/day-1-toy/modules.py deleted file mode 100644 index 5313fc1934..0000000000 --- a/src/day-1-toy/modules.py +++ /dev/null @@ -1,31 +0,0 @@ -import sys -import os - -# Module "sys" -# -# See docs for the sys module: https://docs.python.org/3.7/library/sys.html - -# Print out the command line arguments in sys.argv, one per line: - - -# Print out the plaform from sys: -print() - -# Print out the Python version from sys: -print() - - - -# Module "os" -# -# See the docs for the OS module: https://docs.python.org/3.7/library/os.html - -# Print the current process ID -print() - -# Print the current working directory (cwd): -print() - -# Print your login name -print() - diff --git a/src/day-1-toy/obj.py b/src/day-1-toy/obj.py deleted file mode 100644 index 84c78a2f53..0000000000 --- a/src/day-1-toy/obj.py +++ /dev/null @@ -1,21 +0,0 @@ -# Make a class LatLon that can be passed parameters `lat` and `lon` to the -# constructor - -# Make a class Waypoint that can be passed parameters `name`, `lat`, and `lon` to the -# constructor. It should inherit from LatLon. - -# Make a class Geocache that can be passed parameters `name`, `difficulty`, -# `size`, `lat`, and `lon` to the constructor. What should it inherit from? - -# Make a new waypoint "Catacombs", 41.70505, -121.51521 - -# Print it -# -# Without changing the following line, how can you make it print into something -# more human-readable? -print(w) - -# Make a new geocache "Newberry Views", diff 1.5, size 2, 44.052137, -121.41556 - -# Print it--also make this print more nicely -print(g) diff --git a/src/day-1-toy/printf.py b/src/day-1-toy/printf.py deleted file mode 100644 index d4bc9abb48..0000000000 --- a/src/day-1-toy/printf.py +++ /dev/null @@ -1,10 +0,0 @@ -x = 10 -y = 2.24552 -z = "I like turtles!" - -# Using the printf operator (%), print the following feeding in the values of x, -# y, and z: -# x is 10, y is 2.25, z is "I like turtles!" - - -# Use the 'format' string method to print the same thing \ No newline at end of file diff --git a/src/day-1-toy/slice.py b/src/day-1-toy/slice.py deleted file mode 100644 index 3c6cb38730..0000000000 --- a/src/day-1-toy/slice.py +++ /dev/null @@ -1,26 +0,0 @@ -a = [2, 4, 1, 7, 9, 6] - -# Output the second element: 4: -print() - -# Output the second-to-last element: 9 -print() - -# Output the last three elements in the array: [7, 9, 6] -print() - -# Output the two middle elements in the array: [1, 7] -print() - -# Output every element except the first one: [4, 1, 7, 9, 6] -print() - -# Output every element except the last one: [2, 4, 1, 7, 9] -print() - -# For string s... - -s = "Hello, world!" - -# Output just the 8th-12th characters: "world" -print() \ No newline at end of file diff --git a/src/day-1-toy/tuples.py b/src/day-1-toy/tuples.py deleted file mode 100644 index ec42b0cdf8..0000000000 --- a/src/day-1-toy/tuples.py +++ /dev/null @@ -1,32 +0,0 @@ -# Tuples are like lists, but are immutable and are usually used to hold -# heterogenous data. They use parens instead of square brackets. - -# Example: - -import math - -def dist(a, b): - """Compute the distance between two x,y points.""" - x0, y0 = a # Destructuring assignment - x1, y1 = b - - return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) - -a = (2, 7) # <-- x,y coordinates stored in tuples -b = (-14, 72) - -# Prints "Distance is 66.94" -print("Distance is: {:.2f}".format(dist(a, b))) - - - -# Write a function that prints all the values in a tuple - -# def print_tuple(... - -t = (1, 2, 5, 7, 99) -print_tuple(t) # Prints 1 2 5 7 99, one per line - -# Declare a tuple of 1 element then print it -u = (1) # What needs to be added to make this work? -print_tuple(u) diff --git a/src/days-2-4-adv/adv.py b/src/days-2-4-adv/adv.py deleted file mode 100644 index c9e26b0f85..0000000000 --- a/src/days-2-4-adv/adv.py +++ /dev/null @@ -1,51 +0,0 @@ -from room import Room - -# Declare all the rooms - -room = { - 'outside': Room("Outside Cave Entrance", - "North of you, the cave mount beckons"), - - 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty -passages run north and east."""), - - 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling -into the darkness. Ahead to the north, a light flickers in -the distance, but there is no way across the chasm."""), - - 'narrow': Room("Narrow Passage", """The narrow passage bends here from west -to north. The smell of gold permeates the air."""), - - 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure -chamber! Sadly, it has already been completely emptied by -earlier adventurers. The only exit is to the south."""), -} - - -# Link rooms together - -room['outside'].n_to = room['foyer'] -room['foyer'].s_to = room['outside'] -room['foyer'].n_to = room['overlook'] -room['foyer'].e_to = room['narrow'] -room['overlook'].s_to = room['foyer'] -room['narrow'].w_to = room['foyer'] -room['narrow'].n_to = room['treasure'] -room['treasure'].s_to = room['narrow'] - -# -# Main -# - -# Make a new player object that is currently in the 'outside' room. - -# Write a loop that: -# -# * Prints the current room name -# * Prints the current description (the textwrap module might be useful here). -# * Waits for user input and decides what to do. -# -# If the user enters a cardinal direction, attempt to move to the room there. -# Print an error message if the movement isn't allowed. -# -# If the user enters "q", quit the game. diff --git a/src/days-2-4-adv/player.py b/src/days-2-4-adv/player.py deleted file mode 100644 index d79a175029..0000000000 --- a/src/days-2-4-adv/player.py +++ /dev/null @@ -1,2 +0,0 @@ -# Write a class to hold player information, e.g. what room they are in -# currently. diff --git a/src/days-2-4-adv/room.py b/src/days-2-4-adv/room.py deleted file mode 100644 index 24c07ad4c8..0000000000 --- a/src/days-2-4-adv/room.py +++ /dev/null @@ -1,2 +0,0 @@ -# Implement a class to hold room information. This should have name and -# description attributes. \ No newline at end of file diff --git a/src/day-1-toy/foo.txt b/src/foo.txt similarity index 100% rename from src/day-1-toy/foo.txt rename to src/foo.txt diff --git a/src/python-example/history b/src/python-example/history deleted file mode 100644 index d9e0850ae2..0000000000 --- a/src/python-example/history +++ /dev/null @@ -1 +0,0 @@ -0, 0, 0 \ No newline at end of file diff --git a/src/python-example/history.txt b/src/python-example/history.txt deleted file mode 100644 index aa178b017c..0000000000 --- a/src/python-example/history.txt +++ /dev/null @@ -1 +0,0 @@ -3,3,0 \ No newline at end of file diff --git a/src/python-example/rock_paper_scissors b/src/python-example/rock_paper_scissors deleted file mode 100644 index 2cf502ffd0..0000000000 --- a/src/python-example/rock_paper_scissors +++ /dev/null @@ -1,76 +0,0 @@ -''' - - Online Python Compiler. - Code, Compile, Run and Debug python program online. -Write your code in this editor and press "Run" button to execute it. - -''' -#module that allows us to select a random number -import random - -#dictionary -options = { {1, "rock"}, -{2, "paper"}, -{3, "scissors"} } - -#load previous users from file into list -#TO-DO -text_file = open("results.txt", "rw") -lines = text_file.read().split(',') -print lines -print len(lines) -text_file.close() - -#welcome message -print("Welcome to Rock, Paper, Scissors!") -name = ("Please enter your name.") - -#initialize user, computer choices -print("Please choose to continue...") -computer = random.randint(1,3) -choice = int( input("[1] Rock [2] Paper [3] Scissors [9] Quit Game\n") ) -print( choice ) - -#game will continue as long as user does not chose 9 -while not choice == 9: - #user entered invalid option - if not(( choice == 1 ) or ( choice == 2 ) or ( choice == 3 )): - print( "Invalid selection. Choose again.") - choice = input("[1] Rock [2] Paper [3] Scissors [9] Quit Game\n") - - #user chose ROCK - elif choice == 1: - if( computer == 1 ): - print( "Computer chose rock. Tie!" ) - elif( computer == 2 ): - print( "Computer chose paper. You lose :( ") - else: - print( "Computer chose scissors. You win :)" ) - - #user chose PAPER - elif choice == 2: - if( computer == 1 ): - print( "Computer chose rock. You win :)" ) - elif( computer == 2 ): - print( "Computer chose paper. Tie! ") - else: - print( "Computer chose scissors. You lose :(" ) - - #user chose SCISSORS - else: - if( computer == 1 ): - print( "Computer chose rock. You lose :(" ) - elif( computer == 2 ): - print( "Computer chose paper. You win :) ") - else: - print( "Computer chose scissors. Tie! " ) - print("\nPlease choose to continue...") - - #prompt user to make another selection - computer = random.randint(1, 3) - choice = input("[1] Rock [2] Paper [3] Scissors [9] Quit Game\n") - - -#implement ??? as a function -#TO-DO - diff --git a/src/python-example/rock_paper_scissors.py b/src/python-example/rock_paper_scissors.py deleted file mode 100644 index 4a1899f900..0000000000 --- a/src/python-example/rock_paper_scissors.py +++ /dev/null @@ -1,79 +0,0 @@ -#import module we need -import random - -#file i/o functions for historical results -def load_results(): - text_file = open("history.txt", "r") - history = text_file.read().split(",") - text_file.close() - return history - -def save_results( w, t, l): - text_file = open("history.txt", "w") - text_file.write( str(w) + "," + str(t) + "," + str(l)) - text_file.close() - -#welcome message -results = load_results() -wins = int(results[0]) -ties = int( results[1]) -losses = int(results[2]) -print("Welcome to Rock, Paper, Scissors!") -print("Wins: %s, Ties: %s, Losses: %s" % (wins, ties, losses)) -print("Please choose to continue...") - - -#initialize user, computer choices -computer = random.randint(1,3) -user = int(input("[1] Rock [2] Paper [3] Scissors [9] Quit\n")) - -#gamplay loop -while not user == 9: - #user chooses ROCK - if user == 1: - if computer == 1: - print("Computer chose rock...tie!") - ties += 1 - elif computer == 2: - print("Computer chose paper...computer wins :(") - losses += 1 - else: - print("Computer chose scissors...you wins :)") - wins += 1 - - #user chooses PAPER - elif user == 2: - if computer == 1: - print("Computer chose rock...you win :)") - wins += 1 - elif computer == 2: - print("Computer chose paper...tie!") - ties += 1 - else: - print("Computer chose scissors...computer wins :(") - losses += 1 - - #user chooses SCISSORS - elif user == 3: - if computer == 1: - print("Computer chose rock...computer wins :(") - losses += 1 - elif computer == 2: - print("Computer chose paper...you win :)") - wins += 1 - else: - print("Computer chose scissors...tie!") - ties += 1 - else: - print("Invalid selection. Please try again.") - #print updated stats - print("Wins: %s, Ties: %s, Losses: %s" % (wins, ties, losses)) - - #prompt user to make another selection - print("Please choose to continue...") - #initialize user, computer choices - computer = random.randint(1,3) - user = int(input("[1] Rock [2] Paper [3] Scissors [9] Quit\n")) - -# #game over, save results -save_results(wins, ties, losses) \ No newline at end of file