├── exercises ├── exercise2.md ├── exercise3.md ├── exercise4.md ├── exercise5.md └── exercise1.md ├── docs ├── http_diagram_1.png ├── http_diagram_2.png ├── flowcharts │ ├── flowchart_images │ │ ├── circle.jpg │ │ ├── diamond.jpg │ │ ├── flowArrows.jpg │ │ ├── rectangle.jpg │ │ ├── parallelogram.jpg │ │ ├── flowchart_example_1.jpg │ │ ├── flowchart_example_2.jpg │ │ ├── flowchart_example_3.jpg │ │ └── flowchart_example_4.jpg │ ├── flowchart_example_5.md │ ├── flowchart_example_template.md │ ├── flowchart_example_1.md │ ├── flowchart_example_4.md │ ├── flowchart_example_2.md │ ├── flowchart_example_3.md │ └── README.md ├── terminal_cheatsheet.md ├── career_services.md ├── slack.md └── vocab.md ├── resources ├── troubleshooting.jpeg ├── example_lessons │ ├── unit_4 │ │ ├── examples │ │ │ ├── modules_example │ │ │ │ ├── helpers.py │ │ │ │ └── main.py │ │ │ ├── vending_machine_simple │ │ │ │ ├── utilities.py │ │ │ │ └── vending_machine.py │ │ │ └── web_api_example.py │ │ ├── unit_4_lesson.py │ │ ├── unit_3_review_template.py │ │ └── unit_3_review.py │ ├── unit_5 │ │ ├── count_words.py │ │ ├── web_api.py │ │ ├── count_words_AIO.py │ │ ├── utilities.py │ │ └── alice.txt │ ├── unit_1 │ │ └── unit_1_lesson.py │ ├── unit_2 │ │ ├── grading_with_functions.py │ │ └── unit_2_lesson.py │ └── unit_3 │ │ ├── unit_2_review_template.py │ │ └── unit_3_lesson.py ├── lessons │ ├── lesson_4 │ ├── lesson_1 │ ├── lesson_3 │ ├── lesson_2 │ └── lesson_3_review ├── troubleshoot.py └── countwords.txt ├── practice ├── README.md ├── unit_2 │ ├── solutions │ │ ├── exercise_3_solution.md │ │ ├── exercise_1_solution.md │ │ ├── exercise_2_solution.md │ │ └── exercise_4_solution.md │ ├── exercise_1.md │ ├── exercise_2.md │ ├── README.md │ ├── exercise_3.md │ └── exercise_4.md ├── unit_4 │ ├── README.md │ ├── solutions │ │ └── exercise_2 │ │ │ ├── README.md │ │ │ ├── exercise_2_1_solution.md │ │ │ ├── exercise_2_2_solution.md │ │ │ └── exercise_2_3_solution.md │ ├── exercise_1.md │ └── exercise_2.md ├── unit_1 │ ├── exercise_1.md │ ├── exercise_3.md │ ├── exercise_2.md │ ├── solutions │ │ ├── exercise_1_solution.md │ │ ├── exercise_3_solution.md │ │ └── exercise_2_solution.md │ └── README.md └── unit_3 │ ├── README.md │ ├── exercise_3.md │ ├── exercise_2.md │ ├── exercise_1.md │ └── solutions │ ├── exercise_3_solution.md │ ├── exercise_1_solution.md │ └── exercise_2_solution.md ├── labs ├── lab4.md ├── lab2.md ├── vending-machine.md ├── lab2_calc.md ├── count_words.md ├── lab3.md ├── lab1.md ├── turtle.md └── lab5.md ├── units ├── unit4.md ├── unit5.md ├── unit3.md ├── unit2.md └── unit1.md ├── .gitignore └── README.md /exercises/exercise2.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /exercises/exercise3.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /exercises/exercise4.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /exercises/exercise5.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/http_diagram_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/http_diagram_1.png -------------------------------------------------------------------------------- /docs/http_diagram_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/http_diagram_2.png -------------------------------------------------------------------------------- /resources/troubleshooting.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/resources/troubleshooting.jpeg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/circle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/circle.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/diamond.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/diamond.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/flowArrows.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/flowArrows.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/rectangle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/rectangle.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/parallelogram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/parallelogram.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/flowchart_example_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/flowchart_example_1.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/flowchart_example_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/flowchart_example_2.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/flowchart_example_3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/flowchart_example_3.jpg -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_images/flowchart_example_4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PdxCodeGuild/Programming102/HEAD/docs/flowcharts/flowchart_images/flowchart_example_4.jpg -------------------------------------------------------------------------------- /exercises/exercise1.md: -------------------------------------------------------------------------------- 1 | # Exercise 1 - Unit 1 review 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | ### Exercise: 8 | -------------------------------------------------------------------------------- /practice/README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 2 | 3 | ## Practice Problems 4 | 5 | ### [Unit 1](/unit_1/) 6 | 7 | ### [Unit 2](unit_2/) 8 | 9 | ### [Unit 3](unit_3/) 10 | 11 | ### [Unit 4](unit_4/) 12 | 13 | ### [Unit 5](unit_5/) 14 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/examples/modules_example/helpers.py: -------------------------------------------------------------------------------- 1 | # HELPERS module 2 | 3 | def add(a, b): 4 | '''return the sum of two numbers a and b''' 5 | return a + b 6 | 7 | def say_hello(): 8 | print('Hello from the HELPERS module') 9 | 10 | -------------------------------------------------------------------------------- /practice/unit_2/solutions/exercise_3_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice Solutions 2 | 3 | ## **Exercise 3** - Password Generator 4 | 5 | Sorry, since this is a lab from 101, no answer is provided. 6 | 7 | ## [< Exercise 3](../exercise_3.md) 8 | 9 | ### [<< Back to Unit 2 Practice Problems](/practice/unit_2/) 10 | -------------------------------------------------------------------------------- /practice/unit_4/README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 Practice 2 | 3 | ## **Unit 4** - Modules 4 | 5 | 6 | |Exercise|Solution| 7 | |------------------|-| 8 | |[01 - Clean Text](exercise_1.md) | In Progress ... | 9 | |[02 - Hero Battle](exercise_2.md) | [02 - Hero Battle](./solutions/exercise_2/) | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/examples/modules_example/main.py: -------------------------------------------------------------------------------- 1 | # MAIN module 2 | import helpers 3 | 4 | # define main function to add two numbers using function in helpers module 5 | def main(): 6 | number1 = float(input('Enter the first number: ')) 7 | number2 = float(input('Enter the second number: ')) 8 | 9 | print(helpers.add(number1, number2)) 10 | 11 | main() -------------------------------------------------------------------------------- /practice/unit_4/solutions/exercise_2/README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 2 | 3 | ## Unit 4 4 | 5 | ### Exercise 2 Solutions 6 | 7 | ### [2.1](./exercise_2_1_solution.md) 8 | 9 | ### [2.2](./exercise_2_2_solution.md) 10 | 11 | ### [2.3](./exercise_2_3_solution.md) 12 | 13 | 14 | ## [< Exercise 2](../../exercise_2.md/) 15 | --- 16 | 17 | ### [<< Back to Unit 4 Practice](/practice/unit_4/) 18 | -------------------------------------------------------------------------------- /practice/unit_1/exercise_1.md: -------------------------------------------------------------------------------- 1 | # Unit 1 Practice 2 | 3 | ## **Exercise 1** 4 | 5 | Find and correct all errors in the following: 6 | 7 | ```python 8 | print("Hello World! 9 | ``` 10 | 11 | Output: 12 | 13 | Hello World! 14 | 15 | ### Exercise 1 [solution](solutions/exercise_1_solution.md) 16 | 17 | --- 18 | 19 | ## [Exercise 2 >](exercise_2.md) 20 | 21 | ### [<< Back to Unit 1 Practice](/practice/unit_1/) 22 | -------------------------------------------------------------------------------- /practice/unit_1/exercise_3.md: -------------------------------------------------------------------------------- 1 | # Unit 1 Practice 2 | 3 | ## **Exercise 3** 4 | 5 | ```python 6 | print 'The last letter of 'elephant' is: {'elephant'[8]}') 7 | ``` 8 | 9 | Output: 10 | 11 | The last letter of "elephant" is: t 12 | 13 | ### Exercise 3 [solution](solutions/exercise_3_solution.md) 14 | 15 | --- 16 | 17 | ## [< Exercise 2](exercise_2.md) 18 | 19 | ### [<< Back to Unit 1 Practice](/practice/unit_1/) 20 | -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_example_5.md: -------------------------------------------------------------------------------- 1 | # Flowchart Example 5 - 2 | 3 | In this example... 4 | 5 | ![Flowchart Example 3](./flowchart_images/flowchart_example_3.jpg) 6 | 7 | ### Code: 8 | 9 | ```python 10 | # begin program 11 | 12 | 13 | 14 | # end program 15 | ``` 16 | 17 | --- 18 | 19 | ## [< Example 1](./flowchart_example_1.md)| [Example 3 >](./flowchart_example_3.md) 20 | 21 | ### [<< Back to Flowcharts](/docs/flowcharts/) 22 | -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_example_template.md: -------------------------------------------------------------------------------- 1 | # Flowchart Example 2 | 3 | In this example... 4 | 5 | ![Flowchart Example 3](./flowchart_images/flowchart_example_3.jpg) 6 | 7 | ### Code: 8 | 9 | ```python 10 | # begin program 11 | 12 | 13 | 14 | # end program 15 | ``` 16 | 17 | --- 18 | 19 | ## [< Example 1](./flowchart_example_1.md)| [Example 3 >](./flowchart_example_3.md) 20 | 21 | ### [<< Back to Flowcharts](/docs/flowcharts/) 22 | -------------------------------------------------------------------------------- /practice/unit_3/README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 Practice 2 | 3 | ## **Unit 3 - Dictionaries** 4 | 5 | | Exercise| Solution| 6 | | ------- | ------- | 7 | | [01 - Fruit Shopping](exercise_1.md) | [01 - Fruit Shopping](solutions/exercise_1_solution.md) | 8 | | [02 - Max Scrabble Score](exercise_2.md) | [02 - Max Scrabble Score](solutions/exercise_2_solution.md) | 9 | | [03 - Days in a Month](exercise_3.md) | [03 - Days in a Month](solutions/exercise_3_solution.md) | 10 | -------------------------------------------------------------------------------- /practice/unit_1/exercise_2.md: -------------------------------------------------------------------------------- 1 | # Unit 1 Practice 2 | 3 | ## **Exercise 2** 4 | 5 | ```python 6 | if num < 3 7 | print('The number is ' + num) 8 | print(f'{num is less than three') 9 | prin('thanks for playing!") 10 | ``` 11 | 12 | Output: 13 | 14 | The number is 1 15 | 1 is less than three 16 | Thanks for playing! 17 | 18 | ### Exercise 2 [solution](solutions/exercise_2_solution.md) 19 | 20 | --- 21 | 22 | ## [< Exercise 1](exercise_1.md) | [Exercise 3 >](exercise_3.md) 23 | 24 | ### [<< Back to Unit 1 Practice](/practice/unit_1/) 25 | -------------------------------------------------------------------------------- /practice/unit_4/exercise_1.md: -------------------------------------------------------------------------------- 1 | ## Clean Text 2 | 3 | Define a function called `clean_text()` that takes in some `text` as a parameter. 4 | 5 | - remove all new line characters `\n` from the text 6 | - remove all `punctuation` from the `text` 7 | - convert the entire `text` to `lowercase` 8 | - use the `.split()` method to split the `text` at every space, creating a list of individual words 9 | 10 | Finally, `return` the list of lower case words with no punctuation. 11 | 12 | clean_text("How now, Brown Cow?") 13 | 14 | output: 15 | ['how', 'now', 'brown', 'cow'] 16 | 17 | ### [<< Back to Unit 4 Practice Problems](/practice/unit_4/) 18 | -------------------------------------------------------------------------------- /practice/unit_1/solutions/exercise_1_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 1 Practice Solutions 2 | 3 | ## **Exercise 1** 4 | 5 | **Problem:** 6 | 7 | ```python 8 | print("Hello World! 9 | ``` 10 | 11 | **Solution:** 12 | 13 | 1. `SyntaxError: EOL while scanning string literal` 14 | 15 | A closing quotation mark is missing in `"Hello World!"` 16 | 17 | 2. `SyntaxError: unexpected EOF while parsing` 18 | 19 | A closing parenthesis is missing on `print()` 20 | 21 | **Final code:** 22 | 23 | ```python 24 | print("Hello World!") 25 | ``` 26 | 27 | **Final output:** 28 | 29 | Hello World! 30 | 31 | --- 32 | 33 | ## [< Exercise 1](../exercise_1.md) 34 | 35 | ### [<< Back to Unit 1 Practice Problems](/practice/unit_1/) 36 | -------------------------------------------------------------------------------- /practice/unit_1/README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 Practice 2 | 3 | ## **Unit 1** - Troubleshooting 4 | 5 | For each of the Troubleshooting exercises: 6 | 7 | - **Copy the code** 8 | 9 | Copy the code in the following exercises into **Visual Studio Code**. 10 | 11 | - **Run the code** 12 | 13 | Correct *one error message at a time* until the output matches that which is given with each exercise. 14 | 15 | |Exercise|Solution 16 | |------------------|--------------------------------------| 17 | [01](exercise_1.md)|[01](solutions/exercise_1_solution.md)| 18 | [02](exercise_2.md)|[02](solutions/exercise_2_solution.md)| 19 | [03](exercise_3.md)|[03](solutions/exercise_3_solution.md)| 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_example_1.md: -------------------------------------------------------------------------------- 1 | # Flowchart Example 1 - Output a value 2 | 3 | In this example a variable will be defined containing a string representing a color and then displayed in the terminal. 4 | 5 | ![Flowchart Example 1](flowchart_images/flowchart_example_1.jpg) 6 | 7 | Notice: 8 | 9 | - A rectangle is used when defining the variable 10 | - A parallelogram is used when outputting to the terminal 11 | 12 | ### Code: 13 | 14 | ```python 15 | # begin program 16 | 17 | # set color to 'blue' 18 | color = 'blue' 19 | 20 | # print color to the terminal 21 | print(color) 22 | 23 | # end program 24 | ``` 25 | 26 | --- 27 | 28 | ## [Example 2 >](./flowchart_example_2.md) 29 | 30 | ### [<< Back to Flowcharts]/docs/flowcharts/) 31 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_5/count_words.py: -------------------------------------------------------------------------------- 1 | from utilities import ( 2 | read_text_file, 3 | scrub_text, 4 | tally_words, 5 | find_most_frequent, 6 | write_text_file 7 | ) 8 | 9 | def main(): 10 | # open a text file 11 | dirty_text = read_text_file('alice.txt') 12 | 13 | # clean the text and create list of words 14 | word_list = scrub_text(dirty_text) 15 | 16 | # loop through the list of words and count the number of occurances of each 17 | word_counts = tally_words(word_list) 18 | 19 | # number of words to show 20 | n = 15 21 | 22 | # find the top n most frequent words and their counts 23 | top_n = find_most_frequent(word_counts, n) 24 | 25 | 26 | # write the top n words to a text file 27 | print(write_text_file('top_n_words.txt', top_n, n)) 28 | 29 | main() -------------------------------------------------------------------------------- /practice/unit_2/exercise_1.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice 2 | 3 | ## **Exercise 1 - Count the loops** 4 | 5 | ### **1.1** 6 | 7 | Construct a Read, Evaluate, Print, Loop (REPL) which performs the following on each iteration of the loop: 8 | 9 | - Increment a `counter` variable to keep track of the number of loops. 10 | - Ask the user if they would like to loop again. 11 | - If the user enters 'yes', repeat the loop 12 | - If the user enters 'no', end the loop and display the number of loops performed. 13 | 14 | **Output:** 15 | 16 | Again? yes/no: yes 17 | Again? yes/no: yes 18 | Again? yes/no: yes 19 | Again? yes/no: no 20 | 21 | The loop ran 4 times. 22 | 23 | ### Exercise 1 [solution](solutions/exercise_1_solution.md) 24 | 25 | --- 26 | 27 | ## [Exercise 2 >](exercise_2.md) 28 | 29 | ### [<< Back to Unit 2 Practice](/practice/unit_2/) -------------------------------------------------------------------------------- /practice/unit_2/solutions/exercise_1_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice Solutions 2 | 3 | ## **Exercise 1** 4 | 5 | ### **1.1 Solution** 6 | 7 | ```python 8 | # create a counter variable to 9 | # to count loop iterations 10 | counter = 0 11 | 12 | # begin a REPL 13 | while True: 14 | # count the current iteration 15 | counter += 1 16 | 17 | # ask the user if they want the run the loop again? 18 | again = input('Again? yes/no: ') 19 | 20 | # if the user enters 'no' 21 | if again == 'no': 22 | # tell the user how many times the loop ran 23 | print(f'The loop ran {counter} times.') 24 | 25 | # end the loop 26 | break 27 | ``` 28 | 29 | ## Keep in mind that this is just one potential solution. 30 | 31 | ## [< Exercise 1](../exercise_1.md) | [Exercise 2 >](../exercise_2.md) 32 | 33 | ### [<< Back to Unit 2 Practice Problems](/practice/unit_2/) 34 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/examples/vending_machine_simple/utilities.py: -------------------------------------------------------------------------------- 1 | inventory = { 2 | 'crackers': .5, 3 | 'cookies': .75, 4 | 'mints': .10, 5 | } 6 | 7 | def display_menu(): 8 | '''display the inventory in a nice way''' 9 | for item in inventory: 10 | # get the item's price 11 | price = inventory[item] 12 | 13 | print(f'{item} - ${price:.2f}') 14 | 15 | 16 | def get_total(quantity, price_per): 17 | ''' 18 | Return the total of quantity * price_per 19 | ''' 20 | return quantity * price_per 21 | 22 | def item_in_inventory(item): 23 | ''' 24 | Return True if the item is in the inventory, 25 | ''' 26 | return item in inventory 27 | 28 | 29 | # only run code if a file is run directly 30 | # if __name__ == '__main__': 31 | # print(__name__) 32 | # print('You just ran utilities.py!!!') -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_example_4.md: -------------------------------------------------------------------------------- 1 | # Flowchart Example 4 - Square the Numbers 2 | 3 | In this example we will loop through a list of integers and print the square of each number. 4 | 5 | ![Flowchart Example 4](./flowchart_images/flowchart_example_4.jpg) 6 | 7 | Notice: 8 | 9 | The loop is running until it gets through the last number in the list. Once the last in the list is squared and added to the list, the loop ends. 10 | 11 | ### Code: 12 | 13 | ```python 14 | # begin program 15 | 16 | # create list of numbers 17 | numbers = [11, 22, 33, 44, 55] 18 | 19 | # create empty list for squares 20 | squares = [] 21 | 22 | # loop through all numbers 23 | for num in numbers: 24 | # square the number 25 | num_squared = num ** 2 26 | 27 | # add the square to the list of squares 28 | squares.append(num_squared) 29 | 30 | # print the list of squares 31 | print(squares) 32 | ``` 33 | 34 | --- 35 | 36 | ## [< Example 3](./flowchart_example_3.md) 37 | 38 | ### [<< Back to Flowcharts](/docs/flowcharts/) 39 | -------------------------------------------------------------------------------- /practice/unit_3/exercise_3.md: -------------------------------------------------------------------------------- 1 | ## Unit 3 Practice 2 | 3 | ## **Exercise 3 - Days in a Month** 4 | 5 | ### **3.1** 6 | 7 | Write a function which takes in the full name of a month and returns the number of days in that month. Use a dictionary to store the months and how many days they have in them. 8 | 9 | Loop the code until the user chooses to exit. 10 | 11 | **Output:** 12 | 13 | ``` 14 | Enter the full name of a month to see how many days are in it 15 | or 'q' to quit: september 16 | 17 | September has 30 days in it. 18 | 19 | Enter the full name of a month to see how many days are in it 20 | or 'q' to quit: february 21 | 22 | February has 28 days in it. 23 | 24 | Enter the full name of a month to see how many days are in it 25 | or 'q' to quit: march 26 | 27 | March has 31 days in it. 28 | 29 | Enter the full name of a month to see how many days are in it 30 | or 'q' to quit: q 31 | 32 | Have a lovely day! 33 | ``` 34 | 35 | ### Exercise 3 [solution](solutions/exercise_3_solution.md) 36 | 37 | --- 38 | 39 | ### [<< Back to Unit 3 Practice](/practice/unit_3/) 40 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_5/web_api.py: -------------------------------------------------------------------------------- 1 | # API - application programming interface 2 | 3 | # requests module is used to make HTTP requests to websites 4 | import requests, json 5 | 6 | 7 | 8 | # ask user for their search term 9 | joke = input('Enter a joke topic: ') 10 | 11 | # url to access a list of dad jokes 12 | url = 'https://icanhazdadjoke.com/search' 13 | payload = {'term': joke} 14 | 15 | # make an HTTP GET request to the url and save the HTTP response in a variable 16 | response = requests.get( 17 | url, headers={'Accept': 'application/json'}, params=payload) 18 | 19 | # JSON - JavaScript Object Notation (JS's version of a dictionary) 20 | # convert the response data from JSON to Python dictionary 21 | # using the .json() method of the response object 22 | 23 | data = json.loads(response.text) 24 | 25 | # display the data 26 | # print(data['results'][0]) 27 | # print(data['results'][0]['joke']) 28 | 29 | 30 | num_of_jokes = int(input('\nHow may jokes do you want to hear? ')) 31 | for x in range(num_of_jokes): 32 | if x < len(data['results']): 33 | print('\n' + data['results'][x]['joke']) 34 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/examples/vending_machine_simple/vending_machine.py: -------------------------------------------------------------------------------- 1 | from utilities import inventory, display_menu, get_total, item_in_inventory 2 | 3 | def main(): 4 | while True: 5 | 6 | # display the inventory in a nice way 7 | display_menu() 8 | 9 | item = input('Enter the name of the item you want: ') 10 | 11 | # ask again if the item isn't in the inventory 12 | while not item_in_inventory(item): 13 | print(f'{item} is not in the inventory') 14 | item = input('Enter the name of the item you want: ') 15 | 16 | item_price = inventory[item] 17 | 18 | # ask how many 19 | quantity = input(f'Enter how many {item} you want: ') 20 | 21 | # convert quantity to integer 22 | quantity = int(quantity) 23 | 24 | # get the total cost 25 | total = get_total(quantity, item_price) 26 | 27 | print(f'{quantity} {item} @ ${item_price:.2f} each: ${total:.2f}') 28 | 29 | # print(__name__) 30 | 31 | # only run main() if this file is run directly 32 | if __name__ == '__main__': 33 | main() -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/examples/web_api_example.py: -------------------------------------------------------------------------------- 1 | # API = Application Programming Interface 2 | 3 | # the requests module can be installed by running the following command in the terminal 4 | # pip install requests 5 | import requests 6 | 7 | # request the first todo item 8 | url = 'https://jsonplaceholder.typicode.com/todos/1' 9 | 10 | # ping the url for data, save data in response variable 11 | response = requests.get(url) 12 | 13 | # save response as dictionary (JSON = JavaScript Object Notation) 14 | to_do = response.json() 15 | 16 | display = f""" 17 | Created by: {to_do['userId']} 18 | Todo #{to_do['id']} - {to_do['title']} 19 | Completed: {to_do['completed']} 20 | """ 21 | 22 | # print(display) 23 | 24 | # -------------------------------------- # 25 | 26 | # Then ping /todos for a list of todos and loop 27 | # loop through first 10 todos and display data for each 28 | for index in range(10): 29 | # grab the todo dictionary at the current index 30 | todo = todos[index] 31 | ​ 32 | # print(todo) 33 | ​ 34 | print(f''' 35 | {todo['id']}. {todo['title']} 36 | Created by: {todo['userId']} 37 | Completed: {todo['completed']} 38 | ''') 39 | -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_example_2.md: -------------------------------------------------------------------------------- 1 | # Flowchart Example 2 - Even or Odd? 2 | 3 | In this example the user will be asked to enter a number, which will be converted from a string to an integer. Then the program will output whether the number is even or odd. 4 | 5 | ![Flowchart Example 2](./flowchart_images/flowchart_example_2.jpg) 6 | 7 | Notice: 8 | 9 | - A rectangle is used when converting the number from string to integer 10 | - A diamond shape is used when making the decision whether or not the user's number is even or odd. Two different paths diverge from it to represent the different outcomes of the decision. 11 | 12 | ### Code: 13 | 14 | ```python 15 | # begin program 16 | 17 | # ask the user for a number 18 | number = input('Please enter a number: ') 19 | 20 | # convert the number from string to integer 21 | number = int(number) 22 | 23 | # number is odd? 24 | if number % 2 == 1: 25 | # print number is odd 26 | print(f'{number} is odd.') 27 | 28 | else: 29 | # print number is even 30 | print(f'{number} is even.') 31 | 32 | # end program 33 | ``` 34 | 35 | --- 36 | 37 | ## [< Example 1](./flowchart_example_1.md)| [Example 3 >](./flowchart_example_3.md) 38 | 39 | ### [<< Back to Flowcharts](/docs/flowcharts/) 40 | -------------------------------------------------------------------------------- /docs/flowcharts/flowchart_example_3.md: -------------------------------------------------------------------------------- 1 | # Flowchart Example 3 - Guess the Number 2 | 3 | In this example a variable will be defined to represent a secret number. The user will be asked to guess a number between 1 and 10, which will be converted from a string to an integer. Then the program will output whether the number is greater than, less than or equal to the secret number. 4 | 5 | ![Flowchart Example 3](./flowchart_images/flowchart_example_3.jpg) 6 | 7 | ### Code: 8 | 9 | ```python 10 | # begin program 11 | 12 | # set secret number 13 | secret = 5 14 | 15 | # ask the user for a guess 16 | guess = input('Please guess a number 1-10: ') 17 | 18 | # convert the number to an integer 19 | guess = int(number) 20 | 21 | # guess equals secret? 22 | if guess == secret: 23 | # print you guessed the secret! 24 | print(f'You guessed the secret number: {secret}') 25 | 26 | # guess less than secret? 27 | elif guess < secret: 28 | # print guess was too low 29 | print(f'Your guess of {guess} was too low!') 30 | 31 | # guess greater than secret? 32 | elif guess > secret: 33 | # print guess was too high 34 | print(f'Your guess of {guess} was too high!') 35 | 36 | # end program 37 | ``` 38 | 39 | --- 40 | 41 | ## [< Example 2](./flowchart_example_2.md)| [Example 4 >](./flowchart_example_4.md) 42 | 43 | ### [<< Back to Flowcharts](/docs/flowcharts/) 44 | -------------------------------------------------------------------------------- /labs/lab4.md: -------------------------------------------------------------------------------- 1 | # Lab 4 - Anagram Checker 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | Let's write an anagram checker. 6 | 7 | ## Anagram 8 | 9 | Two words are anagrams of each other if the letters of one can be rearranged to fit the other. e.g. `dormitory` and `dirtyroom`. 10 | 11 | Write a program that lets the user enter two strings, and tells them if they are anagrams of each other. 12 | 13 | 1. Convert the strings into lists 14 | 2. Sort the letters of each list 15 | 3. Check if the two lists are equal 16 | 17 | ``` 18 | >>> enter the first word: dormitory 19 | >>> enter the second word: dirtyroom 20 | >>> 'dormitory' and 'dirtyroom' are anagrams 21 | ``` 22 | 23 | One potential solution to this lab involves Python's built-in function `sorted()`, which will sort list items as well as characters in a string. However, please use the **list method** for sorting the lists in this lab instead. 24 | 25 | # Extra Challenge 1 26 | 27 | 1. Convert each word to lower case 28 | 2. Remove all the spaces from each word by replacing them with empty strings 29 | 30 | # Extra Challenge 2 31 | 32 | Make your program ignore punctuation when checking anagrams. 33 | 34 | # Extra Challenge 3 35 | 36 | Let the user enter as many words as they choose. If every word is an anagram of every other word, let the user know. 37 | -------------------------------------------------------------------------------- /docs/terminal_cheatsheet.md: -------------------------------------------------------------------------------- 1 | # Terminal Cheatsheet 2 | 3 | [Back to Syllabus](../README.md) 4 | 5 | The following commands will work in Mac and Linux terminals as well as Windows PowerShell. 6 | 7 | ## Terminal Navigation 8 | 9 | | Action | Command | 10 | | ------------------------- | ----------------------------- | 11 | | Display current directory | `pwd` | 12 | | Show directory contents | `ls` | 13 | | Change directory | `cd ` | 14 | | Go up a directory | `cd ..` | 15 | | Create a directory | `mkdir ` | 16 | | Delete a directory | `rm -r ` | 17 | | Move a file or folder | `mv ` | 18 | | Cancel current operation | `ctrl + C` / `Command + C` | 19 | 20 | ## Python in the Terminal 21 | 22 | Each operating system has a different shortcut for running Python's `.py` files in the terminal. 23 | 24 | | Command | Mac | Linux | Windows | 25 | | ----------------------- | -------- | -------- | -------- | 26 | | `py .py` | ✗ | ✗ | ✓ | 27 | | `python3 .py` | ✓ | ✓ | ✗ | 28 | | `python .py` | ✗ | ✓ | ✗ | 29 | 30 | When these commands are run without a `filename`, the **Python** **_interpreter_** will run in the terminal. 31 | 32 | [Back to Syllabus](/README.md) 33 | -------------------------------------------------------------------------------- /practice/unit_2/exercise_2.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice 2 | 3 | ## Exercise 2 - Get Colors 4 | 5 | ### **2.1** 6 | 7 | Create a blank list called `colors`. 8 | 9 | Construct a Read, Evaluate, Print, Loop (REPL) which performs the following on each iteration of the loop: 10 | 11 | - Prompt the user for a `color` 12 | - If the user enters 'done' instead of a `color`, exit the loop. 13 | - If the `color` is already in the `colors` list, inform the user that the color is already in the list and repeat the loop. 14 | - If the color is not already in the `colors` list, add it and tell the user it was added. 15 | 16 | When the loop ends, display the list of `colors` back to the user. 17 | 18 | Enter a color or 'done' to quit: blue 19 | 20 | 'blue' added to the colors list! 21 | 22 | Enter a color or 'done' to quit: red 23 | 24 | 'red' added to the colors list! 25 | 26 | Enter a color or 'done' to quit: purple 27 | 28 | 'purple' added to the colors list! 29 | 30 | Enter a color or 'done' to quit: blue 31 | 32 | Oops! 'blue' is already in the colors list! 33 | 34 | output: 35 | The colors you entered were: blue, red, purple 36 | 37 | ### **2.2** 38 | 39 | Define a function `get_color()` which prompts the user for a `color` and then `returns` that `color`. 40 | 41 | Use `get_color()` in your REPL to get the colors from the user. 42 | 43 | ### Exercise 2 [solution](solutions/exercise_2_solution.md) 44 | 45 | --- 46 | 47 | ## [< Exercise 1](exercise_1.md) | [Exercise 3 >](exercise_3.md) 48 | 49 | ### [<< Back to Unit 2 Practice](/practice/unit_2/) -------------------------------------------------------------------------------- /docs/career_services.md: -------------------------------------------------------------------------------- 1 | # Career Services 2 | 3 | Between setting up informational interviews, continuing to learn new skills, building projects, and conquering imposter syndrome, the job search can become quite daunting. However, this is exactly when we need to lean on our friends and colleagues at the PDX Code Guild to find the support we need to persevere. 4 | 5 | We offer a variety of services to our students and alumni both during and after the bootcamp which may include: 6 | 7 | - Resume review 8 | - LinkedIn & Github profile setup, customization and optimization 9 | - Mock behavioral and technical interviews 10 | - Job search organization and accountability 11 | - Community outreach to increase access to potential job opportunities 12 | - Continued skill-building guidance 13 | - Morale maintenance and battling impostor syndrome (we’ve all been there) 14 | 15 | 16 | Our goal is to help everyone who is serious about finding a job in tech to find one as quickly as humanly possible by keeping you organized and on track toward success. 17 | 18 | We will consistently work to compile new resources and to provide clear and concise guidelines for making your job search feel productive and worthwhile. We also provide behavioral and tech interview prep and practice sessions where students can practice interviewing in a low-pressure environment to build their confidence for the many real-life interviews they will encounter. 19 | 20 | If you have questions about transitioning into a career in tech, we're here for you! 21 | 22 | We look forward to working with each and every one of you. You’ve got the skills, now let’s put them to work! 23 | -------------------------------------------------------------------------------- /practice/unit_3/exercise_2.md: -------------------------------------------------------------------------------- 1 | ## Unit 3 Practice 2 | 3 | ## **Exercise 2 - Max Scrabble Score** 4 | 5 | Create a dictionary that contains all the Scrabble letters as keys and their point values as values. 6 | 7 | ### **1.1** 8 | 9 | Ask the user for up to seven letters that will represent a Scrabble hand. Calculate the maximum possible score that could be acheived if all the letters in the hand were played. 10 | 11 | ### Scrabble point values 12 | 13 | | Point Value | Letter | 14 | | ----------- | ------------------------------- | 15 | | 0 | Blank tile | 16 | | 1 | A, E, I, L, N, O, R, S, T and U | 17 | | 2 | D and G | 18 | | 3 | B, C, M and P | 19 | | 4 | F, H, V, W and Y | 20 | | 5 | K | 21 | | 8 | J and X | 22 | | 10 | Q and Z | 23 | 24 | **Output:** 25 | 26 | ``` 27 | Please enter the letters on your tiles, separated by commas: K,B,D,A,E,V,M 28 | 29 | With the letters K, B, D, A, E, V, M the maximum possible score is 19 if all the tiles are played. 30 | ``` 31 | 32 | ### **1.2** 33 | 34 | There are only a certain number of tile with each letter in the game of Scrabble. Create another dictionary with the quantities of each letter tile. 35 | 36 | As the user is entering their tiles, if the tile their entering would exceed the number available, prevent them from entering that letter and ask for another. 37 | 38 | ### Exercise 2 [solution](solutions/exercise_2_solution.md) 39 | 40 | --- 41 | 42 | ### [<< Back to Unit 3 Practice](/practice/unit_3/) 43 | -------------------------------------------------------------------------------- /practice/unit_3/exercise_1.md: -------------------------------------------------------------------------------- 1 | ## Unit 3 Practice 2 | 3 | ## **Exercise 1** 4 | 5 | Create a dictionary of `fruits`. The `name` of each `fruit` will be the **key** and the **value** will be its `price`. 6 | 7 | ### **1.1** 8 | 9 | Using the `fruits` dictionary: 10 | 11 | - Display the `price` of a `fruit` 12 | - Add a `fruit` to the dictionary, print the dictionary to verify its creation 13 | - Remove a `fruit` from the dictionary, print the dictionary to verify its deletion 14 | 15 | Output: 16 | 17 | Apples cost $0.65 each 18 | Added 'grapes': {'apple': 0.65, 'banana': 0.5, 'guava': 0.33, 'grapes': 0.99} 19 | Removed 'banana': {'apple': 0.65, 'guava': 0.33, 'grapes': 0.99} 20 | 21 | ### **1.2** 22 | 23 | Loop through the dictionary and display each item and its price. 24 | 25 | **Output:** 26 | 27 | Fruit Prices 28 | ------------ 29 | Apple: 0.65 30 | Banana: 0.5 31 | Guava: 0.33 32 | 33 | ### **1.3** 34 | 35 | Create another dictionary to represent a `shopping_basket`. 36 | 37 | The keys of this dictionary will be `fruit` names and the values will be the `quantity` of each item in the `shopping_basket`. 38 | 39 | Loop through the `shopping_basket` and add up the `grand_total`. With each iteration of the loop, also print out how many of each `fruit` are in the `shopping_basket` and the `sub_total` for that `fruit`. 40 | 41 | Display all the `sub_totals` and the `grand_total` to look like a receipt in the terminal. 42 | 43 | **Output:** 44 | 45 | 4 Apples: $2.6 46 | 6 Bananas: $3.0 47 | 8 Guavas: $2.64 48 | ------------- 49 | Grand Total: $8.24 50 | 51 | ### Exercise 1 [solution](solutions/exercise_1_solution.md) 52 | 53 | --- 54 | ### [<< Back to Unit 3 Practice](/practice/unit_3/) -------------------------------------------------------------------------------- /resources/lessons/lesson_4: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit 4 - Modules 3 | ''' 4 | 5 | """ 6 | Modules are just Python files. 7 | 8 | As programs grow larger, it makes sense to break them up 9 | into separate files (modules). Modules can then be imported 10 | into other modules using the keyword import 11 | """ 12 | 13 | # import the ENTIRE contents of a module into a variable 14 | # import 15 | import random 16 | import string 17 | 18 | # all attributes of the modules are now 19 | # available through the variable using a dot 20 | letters = string.ascii_letters 21 | random_number = random.randint(1, 100) 22 | random_letter = random.choice(letters) 23 | 24 | # print(random_number, random_letter, letters) 25 | # ------------------------------------------------ # 26 | 27 | # import SPECEFIC attributes from a module 28 | # keywords: from / import 29 | # from import , , ..... 30 | 31 | from string import ascii_letters # only import ascii_letters from string module 32 | from random import randint, choice # only import randint() and choice() from random 33 | 34 | letters = ascii_letters # shorten variable name 35 | random_number = randint(1, 100) # don't need random.randint() anymore 36 | random_letter = choice(letters) 37 | 38 | # print(random_number, random_letter, letters) 39 | # ------------------------------------------------ # 40 | 41 | # import SPECIFIC attributes from a module 42 | # and change their variable name 43 | # keywords: from / import / as 44 | # from import as 45 | 46 | from string import ascii_letters as letters 47 | from random import randint as r_int, choice as r_ch 48 | 49 | random_number = r_int(1, 100) 50 | random_letter = r_ch(letters) 51 | 52 | # print(random_number, random_letter, letters) 53 | -------------------------------------------------------------------------------- /practice/unit_1/solutions/exercise_3_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 1 Practice Solutions 2 | 3 | ## **Exercise 3** 4 | 5 | **Problem:** 6 | 7 | ```python 8 | print 'The last letter of 'elephant' is: {'elephant'[8]}') 9 | ``` 10 | 11 | **Solution:** 12 | 13 | 1. `SyntaxError: Missing parentheses in call to 'print'. Did you mean print('The last letter of 'elephant' is: {'elephant'[8]}'))?` 14 | 15 | Missing open parenthesis on `print()` 16 | 17 | 2. `SyntaxError: invalid syntax` 18 | 19 | Python is having trouble processing the single quotes around `'elephant'` because the string is created using single quotes. This can be solved by either switching the quotes around elephant to double quotes `"elephant"` or by using _escape characters_ to include the single quotes. 20 | 21 | 3. `SyntaxError: invalid syntax` 22 | 23 | This problem is the same as **2.**, except with the next `'elephant'` string. Use double quotes instead. 24 | 25 | 4. No error message is raised, but the output is not correct 26 | 27 | The last letter of "elephant" is: {"elephant"[8]} 28 | 29 | In order to have the value for `"elephant"[8]` print in the output, the string in the `print()` needs to be an f-string. Simply add a 'f' before the opening quotation mark. 30 | 31 | 5. `IndexError: string index out of range` 32 | 33 | 'Elephant' is 8 letters long, but the positions of letters in a string start at 0. Therefore, the characters in 'elephant' are 0 - 7, making the last letter of 'elephant' at position 7. 34 | 35 | **Final code:** 36 | 37 | ```python 38 | print (f'The last letter of "elephant" is: {"elephant"[7]}') 39 | ``` 40 | 41 | **Output:** 42 | 43 | The last letter of "elephant" is: t 44 | 45 | --- 46 | 47 | ## [< Exercise 3](../exercise_3.md) 48 | 49 | ### [<< Back to Unit 1 Practice Problems](/practice/unit_1/) 50 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/unit_4_lesson.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit 4 - Modules 3 | ''' 4 | 5 | """ 6 | Modules are just Python files. 7 | 8 | As programs grow larger, it makes sense to break them up 9 | into separate files (modules). Modules can then be imported 10 | into other modules using the keyword import 11 | """ 12 | 13 | # import the ENTIRE contents of a module into a variable 14 | # import 15 | import random 16 | import string 17 | 18 | # all attributes of the modules are now 19 | # available through the variable using a dot 20 | letters = string.ascii_letters 21 | random_number = random.randint(1, 100) 22 | random_letter = random.choice(letters) 23 | 24 | # print(random_number, random_letter, letters) 25 | 26 | # ------------------------------------------------ # 27 | 28 | # import SPECIFIC attributes from a module 29 | # keywords: from / import 30 | # from import , , ... 31 | 32 | from string import ascii_letters # only import ascii_letters from string module 33 | from random import randint, choice # only import randint() and choice() from random 34 | 35 | letters = ascii_letters # shorten variable name 36 | random_number = randint(1, 100) # don't need random.randint() anymore 37 | random_letter = choice(letters) 38 | 39 | # print(random_number, random_letter, letters) 40 | 41 | # ------------------------------------------------- # 42 | 43 | # import SPECIFIC attributes from a module 44 | # and change their variable name 45 | # keywords: from / import / as 46 | # from import as 47 | 48 | from string import ascii_letters as letters 49 | from random import randint as r_int, choice as r_ch 50 | 51 | random_number = r_int(1, 100) 52 | random_letter = r_ch(letters) 53 | # print(random_number, random_letter, letters) 54 | -------------------------------------------------------------------------------- /resources/lessons/lesson_1: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 1 4 | ''' 5 | 6 | 7 | """ 8 | Anatomy of an Error Message 9 | --------------------------- 10 | 11 | Traceback (most recent call last): 12 | File ".py", line number (approximate) 13 | troublesome code (approximate) 14 | ^ 15 | ErrorType: specific error message 16 | """ 17 | 18 | # syntaxError - a piece of code is missing or misused 19 | # 4 + # SyntaxError: invalid syntax 20 | # 'hello # SyntaxError: unterminated string literal (detected at line 20) 21 | 22 | # print('hello' # SyntaxError: '(' was never closed 23 | 24 | # if the carrot is at the beginning of a line, chances are the rror is above that line 25 | 26 | # ------------------------------------------------------------------------------------------ # 27 | 28 | 29 | # NameError - a variable or function name is used but isn't defined 30 | # xylophone # NameError: name 'xylophone' is not defined 31 | # imaginary_function() # NameError: name 'imaginary_function' is not defined 32 | # typE() # NameError: name 'typE' is not defined. Did you mean: 'type'? 33 | # ------------------------------------------------------------------------------------------ # 34 | 35 | # IndentationError - inconsistent horizontal placement 36 | 37 | # too far right - "unexpected indent" 38 | # too far left - "unindent does not match any outer indentation level" 39 | ''' 40 | x = 5 # IndentationError: unexpected indent 41 | 42 | if x < 10: 43 | print('hello') 44 | print('hello') # IndentationError: unexpected indent 45 | print('hello') # IndentationError: unindent does not match any outer indentation level 46 | 47 | 48 | for x in range(10): 49 | # blank code block 50 | # keyword 'pass' to avoid a blank block error 51 | # pass 52 | 53 | print(x) # IndentationError: expected an indented block after 54 | ''' 55 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_1/unit_1_lesson.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 1 4 | ''' 5 | 6 | """ 7 | Anatomy of an Error Message 8 | --------------------------- 9 | 10 | Traceback (most recent call last): 11 | File ".py", line number (approximate) 12 | troublesome code (approximate) 13 | ^ 14 | 15 | ErrorType: specific error message 16 | """ 17 | 18 | # SyntaxError - a piece of code is missing or misused 19 | # 4 + # SyntaxError: invalid syntax 20 | # 'hello # SyntaxError: unterminated string literal (missing closing quote) 21 | """ 22 | print('hello' # missing closing parenthesis 23 | 24 | 25 | x = 3 26 | y = 4 27 | """ 28 | 29 | # if the carrot is at the beginning of a line, chances are the error is above that line 30 | 31 | # ------------------------------------------------------------------------------------------ # 32 | 33 | # NameError - a variable or function name is used but isn't defined 34 | # xylophone # NameError: name 'xylophone' is not defined 35 | # imaginary_function() # NameError: name 'imaginary_function' is not defined 36 | # typE() # NameError: name 'typE' is not defined 37 | 38 | # ------------------------------------------------------------------------------------------ # 39 | 40 | # IndentationError - inconsistent horizontal placement 41 | 42 | # too far right - "unexpected indent" 43 | # too far left - "unindent does not match any outer indentation level" 44 | 45 | ''' 46 | x = 5 # IndentationError: unexpected indent 47 | 48 | if x < 10: 49 | print('hello') 50 | print('hello') # IndentationError: unexpected indent 51 | print('hello') # IndentationError: unindent does not match any outer indentation level 52 | 53 | for x in range(10): 54 | # blank code block 55 | # keyword 'pass' to avoid a blank code block error 56 | # pass 57 | 58 | print(x) # IndentationError: expected an indented block 59 | ''' 60 | -------------------------------------------------------------------------------- /labs/lab2.md: -------------------------------------------------------------------------------- 1 | # Lab 2 - Number Lists 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | ## 2.1 6 | 7 | We're going to write Python's built-in function, `sum()`, from scratch. 8 | 9 | Create a function called `sum` with a single parameter, `numbers`. Call the function and pass a list of numbers as an argument. 10 | 11 | The function will add up all the `numbers` in the list and `return` the sum of the `numbers`. 12 | 13 | Note: Please do ***not*** use the built-in function `sum()`. The goal is to write that function from scratch. 14 | 15 | ``` 16 | Numbers: [4, 5, 4, 2, 7, 4, 4, 5, 8, 10] 17 | 18 | Sum: 53 19 | ``` 20 | --- 21 | 22 | ## 2.2 23 | 24 | Using a Read, Evaluate, Print, Loop (REPL), build a list of numbers by asking the user to enter them one at a time. Add each number to a list. 25 | 26 | Once the user enters 'done', pass the list to the `sum` function from version 2.1 and display the sum that's returned. 27 | 28 | ``` 29 | Enter a number or 'done' to quit: 30 | > 4 31 | 32 | Enter a number or 'done' to quit: 33 | > 5 34 | 35 | Enter a number or 'done' to quit: 36 | > 4 37 | 38 | Enter a number or 'done' to quit: 39 | > 7 40 | 41 | Enter a number or 'done' to quit: 42 | > 4 43 | 44 | Enter a number or 'done' to quit: 45 | > 9 46 | 47 | Enter a number or 'done' to quit: 48 | > done 49 | 50 | You entered [4, 5, 4, 7, 4, 9] 51 | 52 | The sum of the numbers is 33 53 | ``` 54 | --- 55 | 56 | ## Extra Challenge 57 | 58 | Create a function called `remove_all` which takes in two parameters, `numbers` & `target`. 59 | 60 | The `numbers` parameter will be passed a list of numbers and the `target` parameter will be passed the number to remove from the list. 61 | 62 | The function will return a new list containing only the numbers that are not the `target` number. 63 | 64 | ``` 65 | Numbers: [4, 5, 4, 2, 7, 4, 4, 5, 8, 10] 66 | 67 | Remove: 4 68 | Numbers: [5, 2, 10, 5, 8, 10] 69 | 70 | ``` 71 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_2/grading_with_functions.py: -------------------------------------------------------------------------------- 1 | import random # for randint() 2 | 3 | #### add this function if there's time 4 | """# return True if the number is between 1 and 100 5 | # return False otherwise 6 | def get_modifier(score): 7 | ''' 8 | return a grade modifier based on a score 9 | ''' 10 | # isolate the ones digit of the score with % 10 11 | ones = score % 10 12 | 13 | modifier = '' 14 | if ones <= 3: 15 | modifier = '-' 16 | elif ones >= 7: 17 | modifier = '+' 18 | 19 | return modifier 20 | """ 21 | 22 | # define a function to convert scores to letter grades 23 | def get_grade(score): 24 | # convert to letter grade 25 | if score >= 90 and score <= 100: 26 | grade = 'A' 27 | elif score >= 80: 28 | grade = 'B' 29 | elif score >= 70: 30 | grade = 'C' 31 | elif score >= 60: 32 | grade = 'D' 33 | elif score >= 0: 34 | grade = 'F' 35 | 36 | # return the letter grade 37 | return grade 38 | 39 | while True: 40 | # ask the user for their score 41 | user_score = input("Please enter your score 1-100 or 'q' to quit: ") 42 | 43 | # exit if the user entered 'q' 44 | if user_score == 'q': 45 | print('Goodbye') 46 | break # end the loop 47 | 48 | # convert the score to an integer 49 | user_score = int(user_score) 50 | 51 | # generate a random rival score 52 | rival_score = random.randint(0, 100) 53 | 54 | # convert the user score with the function 55 | user_grade = get_grade(user_score) 56 | 57 | # convert the rival score with the function 58 | rival_grade = get_grade(rival_score) 59 | 60 | ''' 61 | # get the user's grade modifier 62 | user_mod = get_modifier(user_score) 63 | 64 | # get the user's grade modifier 65 | rival_mod = get_modifier(rival_score) 66 | ''' 67 | 68 | 69 | 70 | print(f'user: {user_score} - {user_grade}') #{user_mod}') 71 | print(f'rival: {rival_score} - {rival_grade}') # {rival_mod}') 72 | -------------------------------------------------------------------------------- /labs/vending-machine.md: -------------------------------------------------------------------------------- 1 | # Lab 5 - Vending Machine 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | Let's create a REPL style Vending Machine in Python. 6 | 7 | You will need to have a main menu, that displays the options to the user: 8 | 9 | - Display Items 10 | - Insert Money 11 | - Purchase Item 12 | - Return unspent money 13 | 14 | For displaying, we will store all of our items in a dictionary where the key is the item and the value is a list where first item is the price and the second item is the quantity. 15 | 16 | ```python 17 | vending_items = { 18 | "chips": [.75, 5], 19 | "candy": [.75, 8], 20 | "water": [1.0, 2], 21 | "soda": [1.25, 0] 22 | } 23 | ``` 24 | 25 | You can change out the items, prices or quantities to your liking, this is just an example. 26 | 27 | To display all of the options in our vending machine, we can just use the keys 28 | 29 | Our next step is to allow the user to enter money, this will need to be a float, with 1 being a dollar and any decimals being cents. 30 | 31 | After the user enters their amount, allow them to pick an item. If they entered enough money, subtract one from the total remaing items. 32 | 33 | Do not allow them to buy an item if 0 are remaining. 34 | 35 | Do not allow them to buy an item if they do not have enough money. 36 | 37 | To access the price of "chips" we can use the following syntax: 38 | 39 | ```python 40 | price = vending_items["chips"][0] 41 | ``` 42 | 43 | By saying `vending_items["chips"]` it will return that list, then we just need to specify the index 44 | 45 | Lastly give the user an option to 'return' any unspent money. 46 | 47 | ## Recomendations: 48 | 49 | - Break this lab down one step at a time, maybe focus on just the menu first, then move on to another part 50 | - Test as you go, you are more likely to find an error sooner if you test your code frequently 51 | - Use functions to help break up code 52 | - Leave comments to explain your code 53 | -------------------------------------------------------------------------------- /practice/unit_2/README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 Practice 2 | 3 | ## **Unit 2** - REPL / Functions 4 | 5 | 6 | |Exercise|Solution 7 | |------------------|--------------------------------------| 8 | [01 - Count the Loops](exercise_1.md)|[01 - Count the Loops](solutions/exercise_1_solution.md)| 9 | [02 - Get Colors](exercise_2.md)|[02 - Get Colors](solutions/exercise_2_solution.md)| 10 | [03 - Password Generator](exercise_3.md)|[03 - Password Generator](solutions/exercise_3_solution.md)| 11 | [04 - Calculator](exercise_4.md)|[04 - Calculator](solutions/exercise_4_solution.md)| 12 | 13 | --- 14 | 15 | ## Miscellaneous 16 | Create function which takes in a list of numbers and returns a list of the squares of those numbers. 17 | 18 | ```python 19 | print(get_squares([3, 4, 5])) # [9, 16, 25] 20 | print(get_squares([7, 8, 9])) # [49, 64, 81] 21 | ``` 22 | 23 | Create a function which takes in a string and returns a string in which each character of the first string is doubled. 24 | 25 | ```python 26 | print(double_string('abc')) # aabbcc 27 | print(double_string('hello')) # hheelllloo 28 | ``` 29 | 30 | Create a function that uses a loop to build a list of `n` random single letters from A-Z, where `n` is a positive integer. 31 | 32 | ```python 33 | print(random_letters(10)) # ['H', 'M', 'E', 'D', 'M', 'Q', 'V', 'E', 'U', 'G'] 34 | ``` 35 | 36 | Create a function that returns an integer representing the number of vowels in a list or string. 37 | 38 | ```python 39 | print(count_vowels(['A', 'X', 'C', 'E', 'M', 'I'])) # 3 40 | print(count_vowels('CONCATENATE')) # 5 41 | ``` 42 | 43 | Create a function that returns a list of `n` random integers between 1 and 100, where `n` is a positive integer. 44 | 45 | ```python 46 | print(random_numbers(10)) # [12, 87, 62, 11, 36, 99, 35, 80, 38, 52] 47 | ``` 48 | 49 | Create a function that returns an integer representing the number of positive numbers in a list of numbers. 50 | 51 | ```python 52 | print(count_positives([7, -5, 1, -5, -9, -10, -7, 9, -2, 2])) # 4 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /practice/unit_1/solutions/exercise_2_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 1 Practice Solutions 2 | 3 | ## **Exercise 2** 4 | 5 | **Problem:** 6 | 7 | ```python 8 | if num < 3 9 | print('The number is ' + num) 10 | print(f'{num is less than three') 11 | prin('thanks for playing!") 12 | ``` 13 | 14 | **Solution:** 15 | 16 | 1. `SyntaxError: invalid syntax` 17 | 18 | Missing `:` after `if num < 3`. 19 | 20 | 2. `IndentationError: unexpected indent` 21 | 22 | `prin('thanks for playing!")` is one space too far to the right. 23 | 24 | 3. `SyntaxError: EOL while scanning string literal` 25 | 26 | Mismatched quotes in `prin('thanks for playing!")`. String starts with a single quote and ends with a double 27 | 28 | 4. `SyntaxError: f-string: expecting '}'` 29 | 30 | The f-string in the line: `print(f'{num is less than three')` is missing a closing curly bracket after the variable num 31 | 32 | 5. `NameError: name 'num' is not defined` 33 | 34 | There is no value set for `num`. Define `num` and assign a number to it that will satisfy the condition in the `if` statment 35 | 36 | 6. `TypeError: can only concatenate str (not "int") to str` 37 | 38 | The value of `num` is an integer, which cannot be concatenated to a string. We need to convert `num` to a string using the `str()` function or by converting the string to an f-string. 39 | 40 | 7. `NameError: name 'prin' is not defined` 41 | 42 | A 't' is missing from the end of `print()`, preventing the function from being found. 43 | 44 | **Final code:** 45 | 46 | ```python 47 | num = 1 48 | if num < 3: 49 | # using an f-string 50 | print(f'The number is {num}') 51 | 52 | # using str() 53 | # print('The number is ' + str(num)) 54 | 55 | print(f'{num} is less than three') 56 | 57 | print('thanks for playing!') 58 | ``` 59 | 60 | **Final output:** 61 | 62 | The number is 1 63 | 1 is less than three 64 | thanks for playing! 65 | 66 | --- 67 | 68 | ## [< Exercise 2](../exercise_2.md) 69 | 70 | ### [<< Back to Unit 1 Practice Problems](/practice/unit_1/) 71 | -------------------------------------------------------------------------------- /labs/lab2_calc.md: -------------------------------------------------------------------------------- 1 | # Lab 2 - Simple Calculator 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | ## Version 1 6 | 7 | --- 8 | 9 | Let's write a simple REPL (read, evaluate, print, loop) calculator that can handle addition and subtraction. 10 | 11 | Ask the user for an `operator` and each `operand`. Don't forget that `input` returns a `string`, which you can convert to a float using `float(user_input)` where `user_input` is the string you got from `input`. 12 | 13 | Create a separate function for each operation which takes in both `operands` and `returns` the `result` of its operation. 14 | 15 | Pass the user's `operands` to the appropriate function based on the user's selected `operator` and use the value the function returns as your `result`. 16 | 17 | Below is some sample input/output. 18 | 19 | ``` 20 | > what is the operation you would like to perform? + 21 | > what is the first number? 5 22 | > what is the second number? 7 23 | > 5 + 7 = 12 24 | > what is the operation you would like to perform? done 25 | > goodbye 26 | ``` 27 | --- 28 | ## Version 2 29 | 30 | Add functionality for multiplication `*` and division `/` 31 | 32 | --- 33 | ## Extra Challenge 1 34 | 35 | Allow the user to have a running total, each command will perform an operation on that number. 36 | 37 | ``` 38 | > what is the starting number? 15 39 | > enter an operation: + 5 40 | > 20 41 | > enter an operation: * 3 42 | > 60 43 | > enter an operation: done 44 | > Your total is 60. Goodbye. 45 | ``` 46 | 47 | --- 48 | ## Extra Challenge 2 49 | 50 | Allow the user to write an expression, alternating the numbers and operators. Evaluate the expression from left-to-right. 51 | 52 | ``` 53 | > What is the expression? 5 + 2 * 2 54 | > 14 55 | ``` 56 | 57 | ## Extra Challenge 3 58 | 59 | --- 60 | 61 | Allow the user to write an expression, alternating the numbers and operators. Follow the proper order of operations, evaluating first the exponential, them multiplication and division, then addition and subtraction. 62 | 63 | ``` 64 | > What is the expression? 5 + 2 * 2 65 | > 9 66 | ``` 67 | -------------------------------------------------------------------------------- /practice/unit_3/solutions/exercise_3_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 3 Practice Solutions 2 | 3 | ## **Exercise 1 Solution** 4 | 5 | ```python 6 | def days_in_month(month): 7 | '''Return the number of days in the month''' 8 | months = { 9 | 'january': 31, 10 | 'february': 28, 11 | 'march': 31, 12 | 'april': 30, 13 | 'may': 31, 14 | 'june': 30, 15 | 'july': 31, 16 | 'august': 31, 17 | 'september': 30, 18 | 'october': 31, 19 | 'november': 30, 20 | 'december': 31 21 | } 22 | 23 | # return the value at the given month 24 | return months[month] 25 | 26 | 27 | def main(): 28 | 29 | while True: 30 | # ask the user which month 31 | print("\nEnter the full name of a month to see how many days are in it") 32 | month = input("or 'q' to quit: ") 33 | 34 | # check if the user wants to quit 35 | if month == 'q': 36 | print('\n\tHave a lovely day!') 37 | break # end the loop 38 | 39 | # call the function to receive the number of days. lowercase the month to match dict keys 40 | days = days_in_month(month.lower()) 41 | 42 | # display the result 43 | print(f'\n\t{month.capitalize()} has {days} days in it.') 44 | 45 | 46 | main() 47 | ``` 48 | 49 | 50 | **Output:** 51 | 52 | ``` 53 | Enter the full name of a month to see how many days are in it 54 | or 'q' to quit: september 55 | 56 | September has 30 days in it. 57 | 58 | Enter the full name of a month to see how many days are in it 59 | or 'q' to quit: february 60 | 61 | February has 28 days in it. 62 | 63 | Enter the full name of a month to see how many days are in it 64 | or 'q' to quit: march 65 | 66 | March has 31 days in it. 67 | 68 | Enter the full name of a month to see how many days are in it 69 | or 'q' to quit: q 70 | 71 | Have a lovely day! 72 | ``` 73 | Keep in mind that this is just one potential solution. 74 | 75 | ## [< Exercise 3](../exercise_3.md) 76 | 77 | --- 78 | 79 | ### [<< Back to Unit 3 Practice](/practice/unit_3/) 80 | -------------------------------------------------------------------------------- /units/unit4.md: -------------------------------------------------------------------------------- 1 | # Unit 4 - Modules 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | ### Table of Contents 8 | 9 | - [What is a Module](#whatis) 10 | - [Importing Modules](#import) 11 | - [Creating our own Module](#create) 12 | - [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_4/) 13 | - [Lab 4](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab4.md) 14 | 15 | --- 16 | 17 | ## What is a Module? 18 | 19 | - Once our programs start to get larger, it makes sense to break them up in to smaller pieces or multiple files. 20 | - These other python files are modules. 21 | - Modules are just python files that we can import into our code. 22 | 23 | --- 24 | 25 | ## Importing 26 | 27 | - Importing a module is super easy, we just need to use the `import` keyword followed by the file name. 28 | 29 | ```python 30 | import random 31 | ``` 32 | 33 | - In this example we are importing random, which is a random.py file on our system. 34 | - We can import any of our python files this way. 35 | - To call a function from that module we use the module_name.function_name 36 | 37 | ```python 38 | random.choice() 39 | ``` 40 | 41 | - Alternatively we can impor only the functions we want from a module 42 | 43 | ```python 44 | from random import choice, randint 45 | ``` 46 | 47 | - If we import this way, we no longer need the module name to use the function 48 | 49 | ```python 50 | num = randint(1, 100) 51 | ``` 52 | 53 | - We can also rename the module within our file by using the `as` keyword 54 | 55 | ```python 56 | import random as super_random_file 57 | ``` 58 | 59 | - Or we could just rename the functions from a module 60 | 61 | ```python 62 | from random import choice as choosy_mc_chooserson 63 | ``` 64 | 65 | --- 66 | 67 | ## Let's create our own module! 68 | 69 | ### [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_4/) 70 | 71 | ### [Lab 4](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab4.md) 72 | 73 | [Back to top](#top) 74 | -------------------------------------------------------------------------------- /practice/unit_2/exercise_3.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice 2 | 3 | ## Exercise 3 - Password Generator 4 | 5 | Let's create a password generator. This will be just like the **[Password Generator](https://github.com/PdxCodeGuild/Programming101/blob/master/labs/password_generator.md)** from *Programming 101*, except this time we will write some functions to execute some of the repeated logic. 6 | 7 | ### **3.1** 8 | 9 | Define a function called `generate_password()`. 10 | 11 | The function will require one parameter representing the desired length of the password and will `return` a ten-character password. 12 | 13 | The character pool from which the ten characters are selected should contain uppercase letters, lowercase letters, digits (0-9) and some kind of special characters. 14 | 15 | **Output** 16 | 17 | Your password: 18 | LV!uvg2mu5 19 | 20 | ### **3.2** 21 | 22 | Allow the user to choose the number of characters they want in their password. Require a minimum of 8. 23 | 24 | If the user enters less than 8 for the character count, display a message and tell them they need at least 8 characters. 25 | 26 | **Output** 27 | 28 | Enter desired password length: 6 29 | 30 | ** Your password must be at least 8 characters long ** 31 | 32 | Enter desired password length: 15 33 | 34 | Your password: 35 | 36 | ### **3.3** 37 | 38 | Allow the user to choose how many letters, numbers, and punctuation characters they want in their password. Mix everything up using `list()`, `random.shuffle()`, and `''.join()`. 39 | 40 | Your function might require an additional parameter in this version. 41 | 42 | **Output** 43 | 44 | Number of letters: 2 45 | Number of digits: 2 46 | Number of special characters: 2 47 | 48 | ** Your password must be at least 8 characters long ** 49 | 50 | Number of letters: 6 51 | Number of digits: 10 52 | Number of special characters: 5 53 | 54 | Your password: 55 | 68P?Z3036*02@Xl!$b35b 56 | 57 | No [**solution**](solutions/exercise_3_solution.md) provided because this is a 101 lab. 58 | 59 | --- 60 | 61 | ## [< Exercise 2](exercise_2.md) | [Exercise 4 >](exercise_4.md) 62 | 63 | ### [<< Back to Unit 2 Practice](/practice/unit_2/) -------------------------------------------------------------------------------- /resources/troubleshoot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Rock, Paper, Scissors 3 | Description: Let's play rock, paper scissors 4 | Author: Anthony 5 | """ 6 | import random # We need to import random before we can use it 7 | 8 | 9 | # These are the available choices, we can use this for both the user and computer 10 | choices = ["rock", "paper", "scissors"] 11 | 12 | # This is our main loop, It will continue to run our game until we break out of it 13 | while True: 14 | # Printing a welcome message everytime our game loops 15 | print("Welcome to Rock, Paper, Scissors. Type 'done' at any time to exit") 16 | 17 | # Choosing a random option from our choices for the computer 18 | computer = random.choice(choices) 19 | 20 | user = "" 21 | # Continue looping while the user has not made a valid selection 22 | while user not in choices: 23 | user = input("Choose either 'rock', 'paper', or 'scissors'").lower() 24 | 25 | # if the user types done, we want to stop asking them 26 | if user == "done": 27 | break 28 | 29 | # if user equals done, we want to end the game 30 | if user == "done": 31 | break 32 | 33 | # if the user and computer are the same it is a tie 34 | if users == computer: 35 | print("Looks like a tie" 36 | 37 | # check all cases if user is rock 38 | elif user == "rock": 39 | 40 | # check winning case 41 | if computer == "scissors": 42 | print("You win!") 43 | 44 | # check losing case 45 | elif computer == "rock": 46 | print("Sorry, You lose.") 47 | 48 | # check all cases if user is paper 49 | elif user == "paper": 50 | 51 | # check winning case 52 | if computer == "rock" 53 | print("You win!") 54 | 55 | # check losing case 56 | elif computer == "scissors": 57 | print("Sorry, You lose.") 58 | 59 | # check all cases if user is scissors 60 | elif user == "scissors": 61 | 62 | # check winning case 63 | if computer == "paper": 64 | print("You win!") 65 | 66 | # check losing case 67 | elif computer == "rock": 68 | Print("Sorry, You lose.") 69 | -------------------------------------------------------------------------------- /labs/count_words.md: -------------------------------------------------------------------------------- 1 | # Lab 5 - Count Words 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | Let's write a python module to analyze a given text file and display the most frequently used words in the terminal. 6 | 7 | You can get sample text [Here](/resources/countwords.txt) 8 | 9 | 1. Pass your file name as a string to get_text(file_name). 10 | 2. Using the string of text that's returned, 11 | 1. Replace all new line characters with single spaces `' '` 12 | 2. Make everything lowercase 13 | 3. Remove all punctuation 14 | 4. Split your text file at each space character into a list of words 15 | 3. Use a dictionary to keep track of each word and how many times it occurs. You can use the word as a key, and the count as the value. 16 | 4. As you loop over you list of words, if the word is not in your dictionary, add it with the value of 1. 17 | 5. If the word already exists in your dictionary add 1 to the count. 18 | 6. Once you have counted all your words, display the top 10 in the terminal. You can use the following code to accomplish this: 19 | 20 | ```python 21 | def get_text(file_name): 22 | ''' 23 | This function will read file_name 24 | and return its contents as a string. 25 | ''' 26 | with open(file_name, "r") as file: 27 | text = file.read() 28 | return text 29 | 30 | def most_frequent(word_dict): 31 | ''' 32 | This function takes in a dictionary and sorts the words 33 | by their value, then returns a dictionary with the ten most 34 | frequently occuring words 35 | ''' 36 | # word_dict is a dictionary where the key is the word and the value is the count 37 | words = list(word_dict.items()) # .items() returns a list of tuples 38 | words.sort(key=lambda tup: tup[1], reverse=True) # sort largest to smallest, based on count 39 | 40 | top_ten = [] 41 | 42 | for i in range(min(10, len(words))): # print the top 10 words, or all of them, whichever is smaller 43 | top_ten.append(words[i]) 44 | 45 | top_ten = dict(top_ten) # convert list of tuples into a dictionary 46 | 47 | return top_ten 48 | 49 | def main(): 50 | # Your code goes here 51 | 52 | 53 | main() 54 | 55 | ``` 56 | -------------------------------------------------------------------------------- /units/unit5.md: -------------------------------------------------------------------------------- 1 | # Unit 5 - Final 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | ### Table of Contents 8 | 9 | - [Final Project](#final) 10 | - [What Now?](#what-now) 11 | - [Thanks!](#thanks) 12 | - [Lab 5](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab5.md) 13 | 14 | --- 15 | 16 | ### Congratulations, You made it! 17 | 18 | The last day of class is finally here! We hope you've enjoyed yourself! Please help us make Programming 101/102 better by taking this [anonymous survey](https://forms.gle/D7vCyctcqUQFvSeA9). 19 | 20 | 21 | ## What Now? 22 | 23 | PDX Code Guild's Full Stack Boot Camps cover a wide variety of subject matter in addition to Python. If you're looking for something to study in the time until your boot camp begins, consider taking a look at the following subjects: 24 | 25 | - HyperText Markup Language (HTML) 26 | - used for layout out web pages 27 | - Cascading Style Sheets (CSS) 28 | - used to style web pages 29 | - HTTP Request/Response Cycle 30 | - The process of passing data from a website to a web server and back again 31 | - Beginner Javascript 32 | - code that runs in the browser to make your web pages do cool stuff 33 | 34 | ## Python Practice 35 | 36 | If you haven't done so already, go back through the Programming 101 and Programming 102 syllabi and rework all the labs and exercises, attempting each one with a REPL and functions. Also, work through all the exercises provided for all units. 37 | 38 | If you've made it through all that and are still looking for more, check out the following sites for additional challenges 39 | 40 | - [codewars.com](http://www.codewars.com) 41 | - [practicepython.org](http://www.practicepython.org) 42 | - [edabit.com](http://www.edabit.com) 43 | - [hackerrank.com](http://www.hackerrank.com) 44 | 45 | ## Thanks! 46 | 47 | Thank you for participating in the Programming 101 and 102 program at the PDX Code Guild. We love helping you learn code and we couldn't do what we do without you! You're amazing and your journey is just beginning. Be patient with yourself and don't give up! See you in the boot camp! 48 | 49 | ## [Lab 5](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab5.md) 50 | [Back to top](#top) 51 | -------------------------------------------------------------------------------- /practice/unit_2/exercise_4.md: -------------------------------------------------------------------------------- 1 | # Exercise 4 - Calculator 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | ## 4.1 6 | 7 | --- 8 | 9 | Let's write a REPL (read, evaluate, print, loop) calculator that can handle addition and subtraction. 10 | 11 | Ask the user for an `operator` and each `operand`. Don't forget that `input` returns a `string`, which you can convert to a float using `float(user_input)` where `user_input` is the string you got from `input`. 12 | 13 | Create a separate function for each operation which takes in both `operands` and `returns` the `result` of its operation. 14 | 15 | Pass the user's `operands` to the appropriate function based on the user's selected `operator` and use the value the function returns as your `result`. 16 | 17 | Below is some sample input/output. 18 | 19 | ``` 20 | Enter the operation you would like to perform or 'done' to quit: + 21 | Enter the first operand: 1 22 | Enter the second operand: 2 23 | 24 | 1.0 + 2.0 = 3.0 25 | 26 | Enter the operation you would like to perform or 'done' to quit: - 27 | Enter the first operand: 100 28 | Enter the second operand: 25 29 | 30 | 100.0 - 25.0 = 75.0 31 | 32 | Enter the operation you would like to perform or 'done' to quit: done 33 | 34 | Goodbye! 35 | ``` 36 | --- 37 | ## 4.2 38 | 39 | Add functionality for multiplication `*` and division `/` 40 | 41 | --- 42 | ## 4.3 43 | 44 | Allow the user to have a running total, each command will perform an operation on that number. 45 | 46 | ``` 47 | Enter the operation you would like to perform or 'done' to quit: + 48 | Enter the first operand: 1 49 | Enter the second operand: 02 50 | 1.0 + 2.0 = 3.0 51 | 52 | Enter the operation you would like to perform or 'done' to quit: + 53 | 54 | 3.0 + x: 55 | 56 | Enter x: 50 57 | 58 | 3.0 + 50.0 = 53.0 59 | 60 | 61 | Enter the operation you would like to perform or 'done' to quit: - 62 | 63 | 53.0 - x: 64 | 65 | Enter x: 7 66 | 67 | 53.0 - 7.0 = 46.0 68 | 69 | 70 | Enter the operation you would like to perform or 'done' to quit: done 71 | 72 | Your final total was: 46.0 73 | 74 | Goodbye! 75 | ``` 76 | 77 | ## 4.4 78 | 79 | Use a dictionary rather than if/elif to decide which function should be called. 80 | 81 | ### Exercise 4 [solution](solutions/exercise_4_solution.md) 82 | 83 | --- 84 | 85 | ## [< Exercise 3](exercise_3.md) 86 | 87 | ### [<< Back to Unit 2 Practice](/practice/unit_2/) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # vs code 132 | .vscode/ -------------------------------------------------------------------------------- /resources/example_lessons/unit_5/count_words_AIO.py: -------------------------------------------------------------------------------- 1 | from string import punctuation 2 | 3 | def sort_by_value(tup): 4 | '''return the first item of the tuple for sorting''' 5 | return tup[1] 6 | 7 | # open a text file 8 | with open('alice.txt', 'r') as text_file: 9 | # alice.txt is open ONLY in this code block 10 | 11 | # read the file's contents and save to a variable as a giant string 12 | dirty_text = text_file.read() 13 | 14 | # text file is closed here 15 | 16 | # clean the text 17 | # lowercase everything 18 | clean_text = dirty_text.lower() 19 | 20 | # remove all newline characters 21 | clean_text = clean_text.replace('\n', ' ') 22 | 23 | # remove all punctuation 24 | # loop through each punctuation character and remove it from the text 25 | for punct in punctuation: 26 | clean_text = clean_text.replace(punct, '') 27 | 28 | 29 | # split the text at each space to form a list of words 30 | word_list = clean_text.split(' ') 31 | 32 | 33 | # loop through the list of words and count the number of occurance of each 34 | 35 | # store the words and their counts in a dictionary 36 | word_counts = {} 37 | 38 | # loop through the list of words 39 | for word in word_list: 40 | 41 | # skip all blank strings 42 | if word == '': 43 | continue 44 | 45 | # if the word is not a key in the dictionary, 46 | if word not in word_counts: 47 | # add it with a value of 1 48 | word_counts[word] = 1 49 | 50 | # if the word IS ALREADY a key in the dictionary, 51 | elif word in word_counts: 52 | # add 1 to its value 53 | word_counts[word] += 1 54 | 55 | words = list(word_counts.items()) 56 | 57 | # sort the list of tuple items by value in descending order 58 | words.sort(key=sort_by_value, reverse=True) 59 | 60 | # empty list for top ten words 61 | top_ten = [] # list slicing - words[0:10] # list_name[start_index:stop_index] 62 | 63 | # loop 0 - 9 64 | for index in range(10): 65 | # add each of the top ten words to the list 66 | top_ten.append(words[index]) 67 | 68 | top_ten = dict(top_ten) 69 | 70 | # label for output 71 | output = 'Top Ten Words\n-------------\n' 72 | 73 | # 'unpack' the word and count for each item into two variables 74 | for word, count in top_ten.items(): 75 | # add the current word and its count to the output string with a new line after 76 | output += f'{word} - {count}\n' 77 | 78 | 79 | # write the top ten words to a text file 80 | # open new text file in WRITE mode ('w') 81 | with open('most_frequent_words.txt', 'w') as text_file: 82 | # write the output string to the text file 83 | text_file.write(output) -------------------------------------------------------------------------------- /docs/slack.md: -------------------------------------------------------------------------------- 1 | # Slack 2 | 3 | [Back to Syllabus](../README.md) 4 | 5 | Slack is a communication tool we will be using in Programming 101 and 102, as well as the PDX Code Guild's boot camps. 6 | 7 | By the first day of class, you will be added to a channel, or chatroom. The channel's name will include the start date for the course. 8 | 9 | For example, if your **Programming 101** class starts on **Aug 31, 2020**, the channel name will be **101_20-08-31** (class_YY-MM-DD). 10 | 11 | ## Turning in Labs 12 | 13 | ### 1. Search for recipient 14 | 15 | At the top of the Slack window, you'll find a search bar that says `Search PDX Code Guild Intro Classes`. 16 | 17 | ![search bar](/resources/slack/search_bar.png) 18 | 19 | Click the search bar and begin typing the name of the recipient 20 | 21 | ![search recipient](/resources/slack/search_keegan.png) 22 | 23 | Click the recipient's name to open a Direct Message with them. 24 | 25 | ![recipient dm](/resources/slack/keegan_dm.png) 26 | 27 | ### 2. Create a code snippet. 28 | 29 | Code must be submitted as a Slack code snippet, otherwise the code's formatting may get lost in translation. 30 | 31 | Click the icon shaped like a **lightning bolt** on the bottom left of the chat box. 32 | 33 | ![shortcuts icon](/resources/slack/shortcuts_icon.png) 34 | 35 | Select **Create code or text snippet** 36 | 37 | ![create snippet](/resources/slack/create_code_snippet.png) 38 | 39 | Enter your code in the box labeled **Content**. You can optionally give your file a name and specify the language as **Python** using the dropdown in the upper right. 40 | 41 | ![snippet popup](/resources/slack/snippet_popup.png) 42 | 43 | Once you've pasted your code, click the green **Create Snippet** button and your file will be uploaded. 44 | 45 | ![uploaded file](/resources/slack/uploaded_file.png) 46 | 47 | ### 3. Copying code from Slack 48 | 49 | The instructor will be posting all class code into Slack. 50 | 51 | If you want to copy code from Slack into VS Code, it is advisable to copy the code in the following way: 52 | 53 | Hover over the code and find the icon with the **three horizontal dots**. 54 | 55 | ![file options icon](/resources/slack/file_options_icon.png) 56 | 57 | Click the icon and select **View Raw** 58 | 59 | ![view raw dropdown](/resources/slack/view_raw_dropdown.png) 60 | 61 | This will open a plain text version of the code. 62 | 63 | Note: 64 | 65 | If you copy and paste directly from the Slack chat, you may encounter strange errors when the code is run. 66 | 67 | This is due to invisible whitespace characters that are present in the rendered version of the code in Slack. 68 | 69 | Copying the 'raw' version will avoid such errors. 70 | -------------------------------------------------------------------------------- /labs/lab3.md: -------------------------------------------------------------------------------- 1 | # Lab 3: Unit Converter 2 | 3 | This lab will involve writing a program that allows the user to convert a number between units. 4 | 5 | Each version should be accomplished using a **dictionary** and each must be completed without the use of `if`/`elif` statements. 6 | 7 | You do NOT need to use a while loop 8 | 9 | ## Version 1 10 | 11 | Ask the user for the number of feet, and print out the equivalent distance in meters. 12 | 13 | Hint: 1 ft is 0.3048 m. 14 | 15 | So we can get the output in meters by **multiplying the input distance by 0.3048**. Below is some sample input/output. 16 | 17 | ``` 18 | > what is the distance in feet? 12 19 | > 12 ft is 3.6576 m 20 | ``` 21 | 22 | ## Version 2 23 | 24 | Allow the user to also enter the units. Then depending on the units, convert the distance into meters. The units we'll allow are feet, miles, meters, and kilometers. 25 | 26 | **Hint:** Try using the unit as the key and the conversion as the value. 27 | 28 | ``` 29 | 1 ft is 0.3048 m 30 | 1 mi is 1609.34 m 31 | 1 m is 1 m 32 | 1 km is 1000 m 33 | ``` 34 | 35 | Below is some sample input/output: 36 | 37 | ``` 38 | > what is the distance? 100 39 | > what are the units? mi 40 | > 100 mi is 160934 m 41 | ``` 42 | 43 | ## Version 3 44 | 45 | Add support for yards, and inches. 46 | 47 | ``` 48 | 1 yard is 0.9144 m 49 | 1 inch is 0.0254 m 50 | ``` 51 | 52 | ## Extra Challenge 53 | 54 | Now we'll ask the user for the distance, the starting units, and the units to convert to. 55 | 56 | You can think of the values for the conversions as elements in a matrix, where the rows will be the units you're converting from, and the columns will be the units you're converting to. Along the horizontal, the values will be 1 (1 meter is 1 meter, 1 foot is 1 foot, etc). 57 | 58 | | | ft | mi | m | km | 59 | | --- | -------- | --------- | ------- | ------ | 60 | | ft | 1 | | 0.3048 | | 61 | | mi | | 1 | 1609.34 | | 62 | | m | 1/0.3048 | 1/1609.34 | 1 | 1/1000 | 63 | | km | | | 1000 | 1 | 64 | 65 | But instead of filling out that matrix, and checking for each pair of units (`if from_units == 'mi' and to_units == 'km'`), we can just convert any unit to meters, then convert the distance in meters to any other unit. 66 | 67 | Furthermore you can convert them from meters by dividing a distance (in meters) by those same values used above. So first convert from the input units **_to_** meters, then convert **_from_** meters to the output units. 68 | 69 | Below is some sample input/output: 70 | 71 | ``` 72 | > what is the distance? 100 73 | > what are the input units? ft 74 | > what are the output units? mi 75 | 100 ft is 0.0189394 mi 76 | ``` 77 | -------------------------------------------------------------------------------- /docs/flowcharts/README.md: -------------------------------------------------------------------------------- 1 | # Flowcharts 2 | 3 | [Back to Syllabus](../README.md) 4 | 5 | ## Table of Contents 6 | 7 | - [Introduction](#intro) 8 | - [Symbols](#symbols) 9 | - [Examples](#examples) 10 | 11 | ### Introduction 12 | 13 | When first examining a programming problem, it can be a little overwhelming thinking about where to start. Therefore, it helps to try to split the problem into as many pieces as possible. Then we can work on solving the smaller problems which will work together to solve the overarching problem. 14 | 15 | Flowcharts are a great tool for helping organize the logical flow of a program before we write the actual code. 16 | 17 | A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task. 18 | 19 | ### Symbols 20 | 21 | Flowcharts use different shapes to represent different data, processes and decisions that will make up the program. 22 | 23 | | Symbol | Name | Description | 24 | | ---------------------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | 25 | | ![Flowlines](./flowchart_images/flowArrows.jpg) | Flow Arrows | Shows the process's order of operation. A line coming from one symbol and pointing at another. | 26 | | ![Termination](./flowchart_images/circle.jpg) | Terminal | Indicates the beginning and ending of a program. They usually contain the word "Start" or "End" | 27 | | ![Process](./flowchart_images/rectangle.jpg) | Process | Represents an operation that changes data. | 28 | | ![Decision](./flowchart_images/diamond.jpg) | Decision | Shows a conditional operation that determines which one of the two paths the program will take. Commonly a yes/no question or true/false test | 29 | | ![InputOutput](./flowchart_images/parallelogram.jpg) | Input/Output | Indicates the process of entering or displaying data. | 30 | 31 | [Back to top](#top) 32 | 33 | --- 34 | 35 | ### Examples 36 | 37 | [Output a Value](flowchart_example_1.md) 38 | 39 | [Even or Odd?](flowchart_example_2.md) 40 | 41 | [Guess the Number](flowchart_example_3.md) 42 | 43 | [Square the Numbers](flowchart_example_4.md) 44 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/unit_3_review_template.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit 3 Review 3 | ''' 4 | 5 | # dictionaries are defined using curly brackets 6 | # key:value pairs are separated with commas 7 | 8 | # dict keys are usually strings 9 | # dict values can be ANY datatype, including other dicts 10 | 11 | # ---------------------------------------------------------------------------------- # 12 | 13 | # when accessing values with keys, 14 | # the keys go in SQUARE brackets 15 | 16 | # integers in square brackets generally mean lists 17 | # string in square brackets generally mean dictionaries 18 | 19 | # --------------------------------------------------------------------------------- # 20 | 21 | # cannot access a value at a non-existant key 22 | 23 | # values can be added to keys that don't yet exist 24 | 25 | # change the value at a key 26 | # the todo has been finished 27 | 28 | # ----------------------------------------------------------------------------- # 29 | '''Dictionary Methods''' 30 | 31 | # .pop(key) delete the key:value pair at the key and return the value 32 | 33 | # ----------------------------------------------------------------------------- # 34 | 35 | # alternative to the .get() method: 36 | 37 | # .get(key, default) - return the value at the key if it exists or the default if it doesn't 38 | 39 | 40 | # ------------------------------------------------------------------------- # 41 | 42 | # .update(new_dictionary) add the new_dictionary to the original 43 | # ------------------------------------- # 44 | 45 | # Display the todo item 46 | 47 | # ---------------------------------------- # 48 | # looping dictionaries 49 | # .keys(), .values(), .items() - access different parts of the a dictionary 50 | # -------------------------------------------------------------------------- # 51 | 52 | # .keys() - access a dictionary's keys 53 | 54 | # loop through keys 55 | 56 | # -------------------------------------------------------------------------- # 57 | 58 | # .values() - access a dictionary's values 59 | 60 | # ----------------------------------------------------------------------- # 61 | # loop through the key:value pairs (items) 62 | 63 | # tuple - unchangeable list, uses indices but cannot accept new values 64 | 65 | # -------------------------------------------------------- # 66 | 67 | # 'in' to check if a key is in the dictionary 68 | 69 | # -------------------------------------------------------- # 70 | 71 | # instead of multiple, individual todo item dictionaries, create a list of dictionaries instead 72 | 73 | # list of dictionaries. List is organized vertically, dictionaries organized horizontally. 74 | 75 | # list of dictionaries organized vertically 76 | 77 | # pull out a single dictionary from the list using an index 78 | 79 | # loop through the todo_list 80 | 81 | # ------------------------------------------------------------ # 82 | 83 | # nested dictionaries 84 | 85 | -------------------------------------------------------------------------------- /labs/lab1.md: -------------------------------------------------------------------------------- 1 | # Lab 1 - Troubleshooting 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | - We are going to take an existing lab and try to solve all of the mistakes by looking at the error messages. 8 | - Copy and paste the following code into your own python file 9 | - There are 5 errors total for this lab, 4 will raise errors, one will not. 10 | - Of the four errors which raise error messages, three are easy to find. However, one is not obvious as it's only triggered by a specific outcome of the game. 11 | - The error that doesn't raise an error message is also only triggered by a specific outcome of the game. 12 | - Please **leave a comment** after each error you correct 13 | 14 | ```python 15 | """ 16 | Title: Rock, Paper, Scissors 17 | Description: Let's play rock, paper scissors 18 | Author: Anthony 19 | """ 20 | import random # We need to import random before we can use it 21 | 22 | 23 | # These are the available choices, we can use this for both the user and computer 24 | choices = ["rock", "paper", "scissors"] 25 | 26 | # This is our main loop, It will continue to run our game until we break out of it 27 | while True: 28 | # Printing a welcome message everytime our game loops 29 | print("Welcome to Rock, Paper, Scissors. Type 'done' at any time to exit") 30 | 31 | # Choosing a random option from our choices for the computer 32 | computer = random.choice(choices) 33 | 34 | user = "" 35 | # Continue looping while the user has not made a valid selection 36 | while user not in choices: 37 | user = input("Choose either 'rock', 'paper', or 'scissors': ").lower() 38 | 39 | # if the user types done, we want to stop asking them 40 | if user == "done": 41 | break 42 | 43 | # if user equals done, we want to end the game 44 | if user == "done": 45 | break 46 | 47 | # if the user and computer are the same it is a tie 48 | if users == computer: 49 | print("Looks like a tie" 50 | 51 | # check all cases if user is rock 52 | elif user == "rock": 53 | 54 | # check winning case 55 | if computer == "scissors": 56 | print("You win!") 57 | 58 | # check losing case 59 | elif computer == "rock": 60 | print("Sorry, You lose.") 61 | 62 | # check all cases if user is paper 63 | elif user == "paper": 64 | 65 | # check winning case 66 | if computer == "rock" 67 | print("You win!") 68 | 69 | # check losing case 70 | elif computer == "scissors": 71 | print("Sorry, You lose.") 72 | 73 | # check all cases if user is scissors 74 | elif user == "scissors": 75 | 76 | # check winning case 77 | if computer == "paper": 78 | print("You win!") 79 | 80 | # check losing case 81 | elif computer == "rock": 82 | Print("Sorry, You lose.") 83 | 84 | ``` 85 | 86 | - Once your version is working without errors, your done! 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming 102 2 | 3 | Welcome to the five day course focused on strengthening your programming fundamentals. 4 | 5 | ## Syllabus Overview 6 | 7 | Advanced versions of labs are optional, but encouraged. Additional practice for each unit can be found in the Exercises column. 8 | 9 | | Unit | Concepts | Labs | Exercises | 10 | | ---- | -------- | -----| --------- | 11 | | [Unit 01](https://github.com/PdxCodeGuild/Programming102/blob/master/units/unit1.md) | Review 101, Troubleshooting & error messages | [Lab 01](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab1.md) | [Unit 01](practice/unit_1) | 12 | | [Unit 02](https://github.com/PdxCodeGuild/Programming102/blob/master/units/unit2.md) | REPL, Functions | [Lab 02](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab2.md) | [Unit 02](practice/unit_2)| 13 | | [Unit 03](https://github.com/PdxCodeGuild/Programming102/blob/master/units/unit3.md) | Dictionaries | [Lab 03](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab3.md) | [Unit 03](practice/unit_3)| 14 | | [Unit 04](https://github.com/PdxCodeGuild/Programming102/blob/master/units/unit4.md) | Modules | [Lab 04](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab4.md) | [Unit 04](practice/unit_4/) | 15 | | [Unit 05](https://github.com/PdxCodeGuild/Programming102/blob/master/units/unit5.md) | Final Project | [Lab 05](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab5.md) | 16 | 17 | ## Quick Links 18 | 19 | Below is a list of helpful links. 20 | | Resource | Link | Comment | 21 | | ------- |----------| -----| 22 | | Lab Submissions |[How to Submit Labs in Slack](/docs/slack.md) | For enrolled Intro students only | 23 | Terminal Cheatsheet | [Terminal Cheatsheet](/docs/terminal_cheatsheet.md) | List of terminal commands| 24 | |Vocab|[Vocab List](/docs/vocab.md/)|A collection of programming terms and their definitions| 25 | |Flowcharts|[Flowcharts](/docs/flowcharts/)|Example flowcharts with corresponding code| 26 | |Career Services|[Career Services](/docs/career_services.md/)|About Career Services at PDX Code Guild| 27 | VS Code Keyboard ShortCuts | [For Windows](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf) | 28 | VS Code Keyboard ShortCuts | [For macOS](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf) | 29 | Python Tutor | [Python Tutor](http://pythontutor.com/visualize.html#mode=edit) | Online debugging tool 30 | Stuck? | [Debugging Errors Guide](https://github.com/PdxCodeGuild/IntroToProgramming/blob/master/documentation/troubleshooting.md) | 31 | Online Code Editor | [Repl](https://repl.it) | Cloud-based editor and interpreter 32 | Compare two code snippets | [DiffChecker](https://www.diffchecker.com/) | Great tool to compare two files of code side by side| 33 | 34 |
35 | 36 | [Back to top](#top) 37 | -------------------------------------------------------------------------------- /practice/unit_3/solutions/exercise_1_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 3 Practice Solutions 2 | 3 | ## **Exercise 1 Solution** 4 | 5 | ### **1.1** 6 | 7 | ```python 8 | fruits = { 9 | 'apple': .65, 10 | 'banana': .5, 11 | 'guava': .33 12 | } 13 | 14 | # Display the price of a fruit 15 | print(f"Apples cost ${fruits['apple']} each") 16 | 17 | # Add a fruit to the dictionary, print the dictionary to verify its creation 18 | 19 | # add 'grapes 20 | fruits['grapes'] = .99 21 | print(f"Added 'grapes': {fruits}") 22 | 23 | # Remove a fruit from the dictionary, print the dictionary to verify its deletion 24 | 25 | # delete the key:value pair at 'banana' 26 | del fruits['banana'] 27 | print(f"Removed 'banana': {fruits}") 28 | ``` 29 | 30 | Output: 31 | 32 | Apples cost $0.65 each 33 | Added 'grapes': {'apple': 0.65, 'banana': 0.5, 'guava': 0.33, 'grapes': 0.99} 34 | Removed 'banana': {'apple': 0.65, 'guava': 0.33, 'grapes': 0.99} 35 | 36 | ### **1.2** 37 | 38 | ```python 39 | fruits = { 40 | 'apple': .65, 41 | 'banana': .5, 42 | 'guava': .33 43 | } 44 | 45 | # display the header label 46 | print(" Fruits ") 47 | print("----------") 48 | 49 | # loop through the keys in the fruits dictionary 50 | fruit_names = fruits.keys() 51 | for fruit_name in fruit_names: 52 | 53 | # get the price of the fruit using its name as the key 54 | price_per = fruits[fruit_name] 55 | 56 | # print the item 57 | print(f'{fruit_name}: {price_per}') 58 | ``` 59 | 60 | **Output:** 61 | 62 | Fruits 63 | ---------- 64 | apple: 0.65 65 | banana: 0.5 66 | guava: 0.33 67 | 68 | ### **1.3** 69 | 70 | **The Code:** 71 | 72 | ```python 73 | # fruits and their prices per item 74 | fruit_prices = { 75 | 'apple': .65, 76 | 'banana': .5, 77 | 'guava': .33 78 | } 79 | 80 | # fruits in the basket and their quantities 81 | shopping_basket = { 82 | 'apple': 4, 83 | 'banana': 6, 84 | 'guava': 8 85 | } 86 | 87 | # set the grand_total to zero 88 | grand_total = 0 89 | 90 | # loop through each fruit in the basket 91 | for fruit in shopping_basket: 92 | 93 | # get the quantity of the current fruit 94 | quantity = shopping_basket[fruit] 95 | 96 | # calculate the sub_total for current fruit 97 | sub_total = quantity * fruit_prices[fruit] 98 | 99 | # add the sub_total for the current 100 | # fruit to the grand total 101 | grand_total += sub_total 102 | 103 | # print the sub_total for the current fruit 104 | print(f'{quantity} {fruit.capitalize()}s: ${sub_total}') 105 | 106 | print("-------------") 107 | print(f'Grand Total: ${grand_total}') 108 | ``` 109 | 110 | **Output:** 111 | 112 | 4 Apples: $2.6 113 | 6 Bananas: $3.0 114 | 8 Guavas: $2.64 115 | ------------- 116 | Grand Total: $8.24 117 | 118 | Keep in mind that this is just one potential solution. 119 | 120 | ## [< Exercise 1](../exercise_1.md) | [Exercise 2 >](../exercise_2.md) 121 | 122 | --- 123 | 124 | ### [<< Back to Unit 3 Practice](/practice/unit_3/) 125 | -------------------------------------------------------------------------------- /practice/unit_2/solutions/exercise_2_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice Solutions 2 | 3 | ## **Exercise 2** 4 | 5 | ### **2.1 Solution** 6 | 7 | ```python 8 | # create a blank list called colors 9 | colors = [] 10 | 11 | # begin REPL 12 | while True: 13 | 14 | # prompt the user for a color 15 | color = input("Please enter a color to add it to the list or enter 'done' to exit: ") 16 | 17 | # If the user enters 'done' instead of a `color`, 18 | # display the list of colors to the user and exit the loop. 19 | if color == 'done': 20 | 21 | # display the colors using .join() to 22 | # place a comma and a space between each color 23 | print(f"The colors you entered were: {', '.join(colors)}") 24 | 25 | # end the loop 26 | break 27 | 28 | # If the color is already in the colors list, 29 | # inform the user that the color is already in the list 30 | # and repeat the loop 31 | if color in colors: 32 | 33 | # inform the user the color is in the list 34 | print(f'The color {color} is already in the list!') 35 | 36 | # go to the top of the loop 37 | continue 38 | 39 | # If the color is not already in the colors list, 40 | # add it and tell the user it was added. 41 | print(f'The color {color} was added to the list!') 42 | colors.append(color) 43 | ``` 44 | 45 | ### **2.2 Solution** 46 | 47 | ```python 48 | # Define a function get_color() 49 | # which prompts the user for a color 50 | # and then returns that color. 51 | def get_color(): 52 | ''' 53 | Prompt the user for a color. Return the color. 54 | ''' 55 | color = input("Please enter a color to add it to the list or enter 'done' to exit: ") 56 | 57 | # return the user's color to the 58 | # line on which get_color() was called 59 | return color 60 | 61 | # create a blank list called colors 62 | colors = [] 63 | 64 | # begin REPL 65 | while True: 66 | # call the get_color() to 67 | # get a color from the user 68 | color = get_color() 69 | 70 | # If the user enters 'done' instead of a `color`, 71 | # display the list of colors to the user and exit the loop. 72 | if color == 'done': 73 | 74 | # display the colors using .join() 75 | # to place a comma and a space between each color 76 | print(f"The colors you entered were: {', '.join(colors)}") 77 | 78 | # end the loop 79 | break 80 | 81 | # If the color is already in the colors list, 82 | # inform the user that the color is already in the 83 | # list and repeat the loop 84 | if color in colors: 85 | print(f'The color {color} is already in the list!') 86 | 87 | # repeat the loop 88 | continue 89 | 90 | # If the color is not already in the `colors` list, 91 | # add it and tell the user it was added. 92 | print(f'The color {color} was added to the list!') 93 | colors.append(color) 94 | ``` 95 | 96 | Keep in mind that this is just one potential solution. 97 | 98 | --- 99 | 100 | ## [< Exercise 2](../exercise_2.md) | [Exercise 3 >](../exercise_3.md) 101 | 102 | ### [<< Back to Unit 2 Practice](/practice/unit_2/) 103 | -------------------------------------------------------------------------------- /practice/unit_4/solutions/exercise_2/exercise_2_1_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 4 Practice Solutions 2 | 3 | ## **Exercise 2 Solution** 4 | 5 | ### **2.1** 6 | 7 |
8 | 9 |
10 | 11 |

12 | 13 | As shown in the flowchart, this solution will consists of a REPL loop performing a series of two actions for each character. 14 | 15 | 1. One of the characters will attack and the other's `hp` will be reduced. 16 | 2. Check if the non-attacking character's `hp` is less than or equal to zero (i.e. they've been defeated). 17 | 18 | As soon as one character is defeated, a message will print saying who won the battle and the loop will end. 19 | 20 | We'll be adding an `input()` before each character attacks to make the battle more interactive. This step isn't represented in the flowchart, but will be in the code. 21 | 22 | We'll also be adding `print()` functions periodically to provide feedback on the status of the battle to the user. 23 | 24 | ```python 25 | # ----------------------------------------------------------- # 26 | # Setup 27 | # ----------------------------------------------------------- # 28 | 29 | 30 | # define hero/villain stats 31 | hero = { 32 | "name": "Andromeda", 33 | "hp": 100, 34 | "attack": 35 35 | } 36 | 37 | villain = { 38 | "name": "Helios", 39 | "hp": 100, 40 | "attack": 33 41 | } 42 | 43 | def is_defeated(character): 44 | ''' 45 | Returns False if the character's hp is greater than zero 46 | Returns True if the character's hp is less than or equal to 47 | ''' 48 | return character['hp'] <= 0 49 | 50 | 51 | # ----------------------------------------------------------- # 52 | # Battle! 53 | # ----------------------------------------------------------- # 54 | 55 | while True: 56 | # display hp 57 | print(f"{hero['name']} has {hero['hp']} hp!") 58 | print(f"{villain['name']} has {villain['hp']} hp!") 59 | 60 | input("\nPress enter to begin the battle!") 61 | 62 | # Hero attacks 63 | print(f"\n{hero['name']} attacks!") 64 | 65 | # subtract hero's attack strength from the villain's hp 66 | villain['hp'] -= hero['attack'] 67 | 68 | # check if the villain is defeated 69 | if is_defeated(villain): 70 | print(f"{villain['name']} has been defeated! {hero['name']} is victorious!") 71 | break # end the loop 72 | 73 | # display hp 74 | print(f"{hero['name']} has {hero['hp']} hp!") 75 | print(f"{villain['name']} has {villain['hp']} hp!") 76 | 77 | input("\nPress enter to continue the battle!") 78 | 79 | # Villain attacks 80 | print(f"\n{villain['name']} attacks!") 81 | 82 | # subtract hero's attack strength from the villain's hp 83 | hero['hp'] -= villain['attack'] 84 | 85 | # check if the hero is defeated 86 | if is_defeated(hero): 87 | print(f"\n{hero['name']} has been defeated! {villain['name']} is victorious!") 88 | break # end the loop 89 | 90 | ``` 91 | 92 | 93 | Keep in mind that this is just one potential solution. 94 | 95 | ## [< Exercise 2](../exercise_2.md) | [2.2 Solution >](./exercise_2_2_solution.md) 96 | 97 | --- 98 | 99 | ### [<< Back to Unit 4 Practice](/practice/unit_4/) 100 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_3/unit_2_review_template.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 2 Review 4 | ''' 5 | 6 | import random 7 | 8 | ''' 9 | R ead 10 | E valuate 11 | P rint 12 | L oop 13 | ''' 14 | 15 | # -------------------------------------------------------------------------------- # 16 | 17 | # This REPL will only loop if the user enters exactly 'yes' 18 | 19 | # ------------------------------------------------------------------------------- # 20 | 21 | # This REPL displays different things for 'y','n' and invalid options 22 | # but will loop unless the user enters 'n' 23 | 24 | # ------------------------------------------------------------------------------ # 25 | 26 | # This REPL will ensure that the user enters a valid choice 27 | # and will output a message accordingly. 28 | 29 | 30 | # ------------------------------------------------------------------------------------- # 31 | 32 | # Functions 33 | 34 | # named code blocks that perform specific tasks 35 | # take in data, manipulate it and return the result to where the function was called 36 | # must be executed with parentheses after their name 37 | 38 | # keyword 'def' to define a function 39 | 40 | # variables in the parentheses in the function's definition are called 'parameters' 41 | # parameters are empty variables, awaiting data (can also be given default values) 42 | def multiply(): 43 | pass 44 | 45 | # define a variable using the return value from the function 46 | 47 | # define a variable using the sum of the 48 | # return values from two function calls 49 | 50 | 51 | 52 | # A function call is equal to its return value 53 | 54 | 55 | # 'arguments' must be passed to fill parameters if no default values are provided 56 | 57 | 58 | # ----------------------------------------------------------------------------------------- # 59 | 60 | def punctuate(): 61 | pass 62 | 63 | # ------------------------------------------------------------------------------------------ # 64 | 65 | # Return True if the 'number' is between 'low' and 'high'. Otherwise return False. 66 | def is_in_bounds(number, low, high): 67 | pass 68 | 69 | 70 | 71 | # display different messages if the number is in bounds or not 72 | 73 | # ------------------------------------------------------------------------------------------- # 74 | 75 | ### THIS CAN BE SKIPPED, IF NEEDED 76 | 77 | def generate_random_numbers(): 78 | pass 79 | 80 | # process all the numbers in the list and count all the numbers that are in a particular range: 81 | 82 | 83 | # ------------------------------------------------------------------- # 84 | ### THIS CAN BE SKIPPED IF NEEDED 85 | 86 | # Scope - Four 'layers' in which variables exist 87 | 88 | # built-in, global, enclosed, local 89 | 90 | # Built-in scope = all built in functions, error messages, etc 91 | 92 | 93 | # ---------------------------------------------------------------------------------- # 94 | ### THIS CAN BE SKIPPED IF NEEDED 95 | 96 | numbers = [] 97 | 98 | ''' 99 | # Don't do this 100 | def add_number_to_list(number): 101 | # Since the numbers list isn't being passed 102 | # through the parameters, it is confusing 103 | # because it's not obvious where the numbers 104 | # variable is coming from 105 | numbers.append(number) 106 | ''' 107 | 108 | ''' 109 | # Do this instead 110 | def add_number_to_list(number, numbers): 111 | # Now it is obvious where the numbers variable 112 | # is coming from. It is passed through the 113 | # parameters, manipulated and returned 114 | numbers.append(number) 115 | return numbers 116 | ''' -------------------------------------------------------------------------------- /labs/turtle.md: -------------------------------------------------------------------------------- 1 | # Lab 5: Turtle 2 | 3 | ## Explanation 4 | 5 | Turtle is a python `module` that allows us to move a virtual turtle around the screen using programming statements. This turtle has a position and a heading. Below are a list of commands, you can more in the [turtle docs](https://docs.python.org/3.6/library/turtle.html). 6 | 7 | - `forward(distance)` moves the turtle forward the given number of pixels 8 | - `left(angle)` and `right(angle)` turns the turtle left or right by the given angle (in degrees) 9 | - `color(color_name)` sets the pen's color, which can be `penup()` `penup()` `penup()` 10 | - `penup()` raises the pen, a line won't be drawn when the turtle moves, `pendown()` lowers the pen again 11 | 12 | - `setposition(x, y)` moves the turtle to the given position 13 | 14 | - `fillcolor(color_name)` sets the fill color, `begin_fill()` indicates you'd like to begin filling in whatever you draw, `end_fill()` actually fills the shape in. 15 | 16 | Use these functions to draw a stick figure with a head, body, two arms, and two legs. Once you're done, go through the examples below and create your own drawing. 17 | 18 | ## Examples 19 | 20 | ### Drawing a Square 21 | 22 | ```python 23 | from turtle import * 24 | 25 | forward(100) 26 | left(90) 27 | forward(100) 28 | left(90) 29 | forward(100) 30 | left(90) 31 | forward(100) 32 | left(90) 33 | 34 | done() 35 | 36 | ``` 37 | 38 | ### Filling in a Square 39 | 40 | ```python 41 | from turtle import * 42 | 43 | fillcolor('red') 44 | begin_fill() 45 | 46 | forward(100) 47 | left(90) 48 | forward(100) 49 | left(90) 50 | forward(100) 51 | left(90) 52 | forward(100) 53 | left(90) 54 | 55 | end_fill() 56 | 57 | done() 58 | 59 | ``` 60 | 61 | ### Drawing a Star 62 | 63 | ```python 64 | from turtle import * 65 | 66 | forward(100) 67 | right(144) 68 | forward(100) 69 | right(144) 70 | forward(100) 71 | right(144) 72 | forward(100) 73 | right(144) 74 | forward(100) 75 | 76 | done() 77 | 78 | ``` 79 | 80 | ### Drawing a Square with a Loop 81 | 82 | ```python 83 | from turtle import * 84 | 85 | i = 0 86 | while i < 4: 87 | forward(100) 88 | left(90) 89 | i = i + 1 90 | 91 | done() 92 | ``` 93 | 94 | ### Drawing a Staircase 95 | 96 | ```python 97 | from turtle import * 98 | 99 | i = 0 100 | while i < 4: 101 | forward(100) 102 | left(90) 103 | forward(100) 104 | right(90) 105 | i = i + 1 106 | done() 107 | ``` 108 | 109 | ### Filling in a Square 110 | 111 | ```python 112 | from turtle import * 113 | 114 | fillcolor('red') 115 | begin_fill() 116 | 117 | forward(100) 118 | left(90) 119 | forward(100) 120 | left(90) 121 | forward(100) 122 | left(90) 123 | forward(100) 124 | left(90) 125 | 126 | end_fill() 127 | 128 | done() 129 | 130 | ``` 131 | 132 | ### Draw an N-Sided figure 133 | 134 | ```python 135 | from turtle import * 136 | 137 | edge_length = 100 138 | n_sides = 5 139 | 140 | i = 0 141 | while i < n_sides: 142 | forward(edge_length/n_sides) 143 | right(360/n_sides) 144 | i = i + 1 145 | 146 | done() 147 | 148 | ``` 149 | 150 | ### 8-Sided Spiral 151 | 152 | ```python 153 | from turtle import * 154 | 155 | fillcolor('blue') 156 | 157 | n_sides = 8 158 | edge_length = 0 159 | 160 | i = 0 161 | begin_fill() 162 | while i < 150: 163 | forward(edge_length) 164 | right(360/n_sides) 165 | i = i + 1 166 | edge_length = edge_length + 1 167 | end_fill() 168 | done() 169 | 170 | ``` 171 | 172 | ### Expanding Star 173 | 174 | ```python 175 | from turtle import * 176 | 177 | edge_length = 0 178 | i = 0 179 | while i < 100: 180 | forward(edge_length) 181 | right(144) 182 | 183 | edge_length += 4 184 | 185 | done() 186 | ``` 187 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_5/utilities.py: -------------------------------------------------------------------------------- 1 | from string import punctuation 2 | 3 | def read_text_file(filename): 4 | '''Open a text file, read its contents and return them as a giant string''' 5 | with open('alice.txt', 'r') as text_file: 6 | # alice.txt is open ONLY in this code block 7 | 8 | # read the file's contents and save to a variable as a giant string 9 | contents = text_file.read() 10 | # text file is closed at this indentation level 11 | 12 | return contents 13 | 14 | def scrub_text(dirty_text): 15 | '''Clean text by lowercasing everything, removing new line characters and punctuation 16 | and splitting at each space into a list of words. Return the list of words.''' 17 | # lowercase everything 18 | clean_text = dirty_text.lower() 19 | 20 | # remove all newline characters 21 | clean_text = clean_text.replace('\n', ' ') 22 | 23 | # remove all punctuation 24 | # loop through each punctuation character and remove it from the text 25 | for punct in punctuation: 26 | clean_text = clean_text.replace(punct, '') 27 | 28 | # split the text at each space to form a list of words 29 | word_list = clean_text.split(' ') 30 | 31 | # return list of lowercase words with no punctuation or new lines 32 | return word_list 33 | 34 | def tally_words(word_list): 35 | '''Loop through the list of words and populate 36 | a dictionary with the words as keys and their 37 | occurances as values. Return the dictionary of counts''' 38 | # store the words and their counts in a dictionary 39 | word_counts = {} 40 | 41 | # loop through the list of words 42 | for word in word_list: 43 | 44 | # skip all blank strings 45 | if word == '': 46 | continue 47 | 48 | # if the word is not a key in the dictionary, 49 | if word not in word_counts: 50 | # add it with a value of 1 51 | word_counts[word] = 1 52 | 53 | # if the word IS ALREADY a key in the dictionary, 54 | elif word in word_counts: 55 | # add 1 to its value 56 | word_counts[word] += 1 57 | 58 | return word_counts 59 | 60 | def sort_by_value(tup): 61 | '''return the first item of the tuple for sorting''' 62 | return tup[1] 63 | 64 | def find_most_frequent(word_counts, n): 65 | '''Return a dictionary of the top n most frequently ocurring 66 | words in the word_counts dictionary.''' 67 | words = list(word_counts.items()) 68 | 69 | # sort the list of tuple items by value in descending order 70 | words.sort(key=sort_by_value, reverse=True) 71 | 72 | # empty list for top n words 73 | top_n = [] # list slicing - words[0:n] # list_name[start_index:stop_index] 74 | 75 | # loop 0 - 9 76 | for index in range(n): 77 | # add each of the top ten words to the list 78 | top_n.append(words[index]) 79 | 80 | top_n = dict(top_n) 81 | 82 | return top_n 83 | 84 | def write_text_file(filename, top_n, n): 85 | '''Write contents as a string to the filename, 86 | displaying top n words and their counts.''' 87 | # label for output 88 | output = f'Top {n} Words\n-------------\n' 89 | 90 | # number for labeling words 91 | word_num = 1 92 | 93 | # 'unpack' the word and count for each item into two variables 94 | for word, count in top_n.items(): 95 | # add the current word and its count to the output string with a new line after 96 | output += f'{word_num}. {word} - {count}\n' 97 | 98 | # increment word number 99 | word_num += 1 100 | 101 | # open new text file in WRITE mode ('w') 102 | with open(filename, 'w') as text_file: 103 | # write the output string to the text file 104 | text_file.write(output) 105 | 106 | return output 107 | -------------------------------------------------------------------------------- /practice/unit_4/solutions/exercise_2/exercise_2_2_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 4 Practice Solutions 2 | 3 | ## **Exercise 2 Solution** 4 | 5 | ### **2.2** 6 | 7 |
8 | 9 |
10 | 11 |

12 | 13 | Since the hero and the villain were both performing the same actions each round, we can reduce repetition by writing more generic logic that can apply to either character. 14 | 15 | Here we've created a function called `attack()` which is going to handle the active character's turn. We'll pass the current `attacker` and their `opponent` and the process of applying damage to the opponent will take place inside the function. 16 | 17 | We'll also use the `is_defeated()` function to return a boolean from `attack()` indicating whether or not the battle is over. 18 | 19 | ```python 20 | # ----------------------------------------------------------- # 21 | # Setup 22 | # ----------------------------------------------------------- # 23 | 24 | hero = { 25 | "name": "Andromeda", 26 | "hp": 100, 27 | "attack": 35 28 | } 29 | 30 | villain = { 31 | "name": "Helios", 32 | "hp": 100, 33 | "attack": 33 34 | } 35 | 36 | def is_defeated(character): 37 | ''' 38 | Returns False if the character's hp is greater than zero 39 | Returns True if the character's hp is less than or equal to 40 | ''' 41 | return character['hp'] <= 0 42 | 43 | 44 | def attack(active, opponent): 45 | ''' 46 | Apply battle damage to the opponent using the active characters's attack stat 47 | If the opponent is defeated, return True, signifying the battle is over 48 | Otherwise return False, signifying the battle will continue for another round 49 | ''' 50 | print(f"{active['name']} has {active['hp']} hp!") 51 | print(f"{opponent['name']} has {opponent['hp']} hp!") 52 | 53 | input("\nPress enter to battle!") 54 | 55 | # active character attacks 56 | print(f"\n{active['name']} attacks!") 57 | 58 | # subtract active character's attack strength from the opponents's hp 59 | opponent['hp'] -= active['attack'] 60 | 61 | # return True if the opponent is defeated, otherwise False 62 | return is_defeated(opponent) 63 | 64 | # ----------------------------------------------------------- # 65 | # Battle! 66 | # ----------------------------------------------------------- # 67 | 68 | 69 | # this will alternate between 0 and 1 to decide whose turn it is 70 | turn_counter = 0 71 | 72 | while True: 73 | 74 | # stat dictionaries stored at matching keys 75 | all_stats = { 76 | 'hero': hero, 77 | 'villain': villain 78 | } 79 | 80 | # keys for the all_stats dictionary 81 | # the turn_counter will alternate between 0 and 1 to decide whose turn it is 82 | stat_keys = list(all_stats.keys()) # ['hero', 'villain'] 83 | 84 | # get the key of the active character 85 | active_key = stat_keys[turn_counter] 86 | # get the stat dictionary of the active character 87 | active = all_stats[active_key] 88 | 89 | 90 | # get the key of the opponent 91 | # index -1 if turn_counter is 0 92 | # index 0 if the turn_counter is 1 93 | opponent_key = stat_keys[turn_counter - 1] 94 | # get the stat dictionary of the opponent 95 | opponent = all_stats[opponent_key] 96 | 97 | # execute current round of battle 98 | # receive True if opponent is defeated, otherwise False 99 | victorious = attack(active, opponent) 100 | 101 | # check the outcome of the battle. 102 | # if the opponent was defeated, end the loop 103 | if victorious: 104 | print(f"{opponent['name']} has been defeated! {active['name']} is victorious!") 105 | break # end the loop 106 | 107 | 108 | # increment the turn_counter 109 | turn_counter += 1 110 | 111 | # make sure the turn_counter will only ever be 0 or 1 using % 2; if/elif could be used instead 112 | turn_counter %= 2 113 | ``` 114 | 115 | 116 | 117 | 118 | Keep in mind that this is just one potential solution. 119 | 120 | ## [< 2.1 Solution](./exercise_2_1_solution.md)| [2.3 Solution >](./exercise_2_3_solution.md) 121 | 122 | --- 123 | 124 | ### [<< Back to Unit 4 Practice](/practice/unit_4/) 125 | -------------------------------------------------------------------------------- /resources/lessons/lesson_3: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 3 4 | ''' 5 | 6 | ''' 7 | Dictionaries ('dict') 8 | 9 | - one of the most powerful datatypes in Python 10 | - can be used to store large amounts of data and make accessing that data quick and easy 11 | - collections of key:value pairs 12 | - keys are used to access values 13 | 14 | - are defined using curly brackets {} 15 | - keys and values are separated with colons 16 | - key:value pairs are called 'items' 17 | - items are separated with commas 18 | ''' 19 | 20 | # blank dictionary 21 | blank_dictionary = {} 22 | 23 | # print(blank_dictionary, type(blank_dictionary)) # {} 24 | 25 | # ------------------------------------------------------------------------------- # 26 | 27 | # dict keys are generally strings 28 | # dict values can be ANY datatype, including other dictionaries 29 | 30 | example_dict = {'a':11, 'b': 22, 'c': 33} 31 | 32 | 33 | 34 | example_dict = { 35 | # key: value, 36 | 'a':11, 37 | 'b': 22, 38 | 'c': 33 39 | } 40 | 41 | # print(example_dict) # {'a': 11, 'b': 22, 'c': 33} 42 | # ------------------------------------------------------------------------------- # 43 | 44 | # dictionary values are retrieved by placing their keys 45 | # in SQUARE brackets after the dictionar's name 46 | 47 | # print(example_dict['a']) # 11 48 | # print(example_dict['b']) # 22 49 | # print(example_dict['c']) # 33 50 | 51 | # ------------------------------------------------------------------------------- # 52 | 53 | # dictionaries are usually used to group related data 54 | 55 | address = { 56 | 'street': '123 Faux St.', 57 | 'city': 'Portland', 58 | 'state': 'Oregon', 59 | 'zipcode': 123456 60 | } 61 | 62 | # print(address['street']) 63 | # print(f"{address['city']}, {address['state']} {address['zipcode']}") 64 | 65 | # ------------------------------------------------------------------------------- # 66 | 67 | book = { 68 | 'title': 'The Hobbit', 69 | 'author': 'JRR Tolkien', 70 | 'pages': 200 71 | } 72 | 73 | # print(f"The book {book['title']} has {book['pages']} pages and was written by {book['author']}") 74 | 75 | # ------------------------------------------------------------------------------- # 76 | 77 | # cannot retrieve values at non-existent keys 78 | # book['characters'] # KeyError: 'characters' 79 | 80 | # add a value at the key 'characters' 81 | book['characters'] = ['Bilbo', 'Gandalf', 'Smaug'] 82 | 83 | # print(book['characters']) # ['Bilbo', 'Gandalf', 'Smaug'] 84 | 85 | # add a character to the list 86 | book['characters'].append('Balin') 87 | 88 | # print(book['characters']) # ['Bilbo', 'Gandalf', 'Smaug', 'Balin'] 89 | # ------------------------------------------------------------------------------- # 90 | 91 | # change the value at a key 92 | book['pages'] = 199 93 | # print(book) 94 | # ------------------------------------------------------------------------------- # 95 | 96 | # deleting a key:value pair 97 | # keyword 'del' 98 | # del book['pages'] 99 | # print(book) 100 | # ------------------------------------------------------------------------------- # 101 | 102 | # dictionary methods 103 | 104 | # .pop(key) - remove the key:value pair at the key and return the value 105 | pages = book.pop('pages') 106 | # print(pages, book) 107 | # ------------------------------------------------------------------------------- # 108 | 109 | # .update(new_dict) - add the items from the new_dict to the original dictionary 110 | new_items = { 111 | 'pages': 200, 112 | 'isbn_number': 3456789876598765 113 | } 114 | 115 | # book.update(new_items) 116 | # print(book) 117 | 118 | # ------------------------------------------------------------------------------- # 119 | 120 | # as of Python 3.9, we can use 'merge' operator 121 | 122 | book = book | new_items 123 | 124 | # print(book) 125 | 126 | # ------------------------------------------------------------------------------- # 127 | 128 | # Fruit stand 129 | 130 | fruit_prices = { 131 | 'apple': 2.33, 132 | 'banana': 1.76, 133 | 'peaches': 2.99 134 | } 135 | 136 | while True: 137 | # ask the user which fruit they want to buy 138 | fruit_name = input('\nPlease enter the name of the fruit you want to buy or \'done\' to quit: ') 139 | 140 | # exit if 'done' 141 | if fruit_name == 'done': 142 | print('\nThanks for shopping!') 143 | break # end the loop 144 | 145 | # get the price of the user's fruit_name 146 | price_per = fruit_prices[fruit_name] 147 | 148 | # ask the use how many they want 149 | quantity = input('Enter the quantity: ') 150 | 151 | # convert the quantity to integer 152 | quantity = int(quantity) 153 | 154 | # calculate the total 155 | total = quantity * price_per 156 | 157 | print(f'{quantity} {fruit_name} @ ${price_per} each - ${round(total, 2)}') 158 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_3/unit_3_lesson.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 3 4 | ''' 5 | 6 | ''' 7 | Dictionaries ('dict') 8 | 9 | - one of the most powerful datatypes in Python 10 | - can be used to store large amounts of data and make accessing that data quick and easy 11 | - collections of key:value pairs 12 | - keys are used to access values 13 | 14 | - are defined using curly brackets {} 15 | - keys and values are separated with colons 16 | - key:value pairs are called 'items' 17 | - items are separated with commas 18 | ''' 19 | 20 | # blank dictionary 21 | blank_dictionary = {} 22 | # print(blank_dictionary, type(blank_dictionary)) # {} 23 | 24 | 25 | # ------------------------------------------------------------------------------- # 26 | 27 | # dict keys are generally strings 28 | # dict values can be ANY datatype, including other dictionaries 29 | 30 | example_dict = {'a': 11, 'b': 22, 'c': 33} 31 | 32 | example_dict = { 33 | # key: value, 34 | 'a': 11, 35 | 'b': 22, 36 | 'c': 33 37 | } 38 | 39 | # print(example_dict) # {'a': 11, 'b': 22, 'c': 33} 40 | 41 | # ------------------------------------------------------------------------------- # 42 | 43 | # dictionary values are retrieved by placing their keys 44 | # in SQUARE brackets after the dictionary's name 45 | 46 | # print(example_dict['a']) # 11 47 | # print(example_dict['b']) # 22 48 | # print(example_dict['c']) # 33 49 | 50 | # ---------------------------------------------------------------------------- # 51 | 52 | # dictionaries are usually used to group related data 53 | 54 | address = { 55 | "street": "123 Faux St.", 56 | "city": "Portland", 57 | "state": "Oregon", 58 | "zipcode": 123456 59 | } 60 | 61 | # print(address['street']) 62 | # print(f"{address['city']}, {address['state']} {address['zipcode']}") 63 | 64 | # ------------------------------------------------------------------------------------------ # 65 | 66 | book = { 67 | 'title': 'The Hobbit', 68 | 'author': 'JRR Tolkien', 69 | 'pages': 200 70 | } 71 | 72 | # print(f"The book {book['title']} has {book['pages']} pages and was written by {book['author']}") 73 | 74 | # ----------------------------------------------------------------------------------------- # 75 | 76 | # cannot retrieve values at non-existent keys 77 | # book['characters'] # KeyError: 'characters' 78 | 79 | # add a value at the key of 'characters' 80 | book['characters'] = ['Bilbo', 'Gandalf', 'Smaug'] 81 | # print(book['characters']) # ['Bilbo', 'Gandalf', 'Smaug'] 82 | 83 | # add a character to the list 84 | book['characters'].append('Balin') 85 | # print(book['characters']) # ['Bilbo', 'Gandalf', 'Smaug', 'Balin'] 86 | 87 | # ---------------------------------------------------------------------------------------- # 88 | 89 | # change the value at a key 90 | book['pages'] = 199 91 | # print(book) 92 | 93 | # ------------------------------------------------------------------------------------------ # 94 | 95 | # deleting a key:value pair 96 | # keyword 'del' 97 | # del book['pages'] 98 | # print(book) 99 | 100 | # ------------------------------------------------------------------------------------------- # 101 | 102 | # dictionary methods 103 | 104 | # .pop(key) - remove the key:value pair at the key and return the value 105 | pages = book.pop('pages') 106 | # print(pages, book) 107 | 108 | # --------------------------------------------------------------------------------------------- # 109 | 110 | # .update(new_dict) - add the items from the new_dict to the original dictionary 111 | new_items = { 112 | 'pages': 200, 113 | 'isbn_number': 3456789876598765 114 | } 115 | 116 | # book.update(new_items) 117 | # print(book) 118 | 119 | # ----------------------------------------------------------------------------------------------- # 120 | 121 | # as of Python 3.9, we can use the 'merge' operator 122 | 123 | book = book | new_items 124 | 125 | # print(book) 126 | 127 | # ------------------------------------------------------------------------------------------------ # 128 | 129 | # Fruit Stand 130 | 131 | fruit_prices = { 132 | 'apple': 2.33, 133 | 'banana': 1.76, 134 | 'peaches': 2.99 135 | } 136 | 137 | while True: 138 | # ask the user which fruit they want to buy 139 | fruit_name = input("\nPlease enter the name of the fruit you want to buy or 'done' to quit: ") 140 | 141 | # exit if 'done' 142 | if fruit_name == 'done': 143 | print("\nThanks for shopping!") 144 | break # end the loop 145 | 146 | # get the price of the user's fruit_name 147 | price_per = fruit_prices[fruit_name] 148 | 149 | # ask the use how many they want 150 | quantity = input("Enter the quantity: ") 151 | 152 | # convert the quantity to integer 153 | quantity = int(quantity) 154 | 155 | # calculate the total 156 | total = quantity * price_per 157 | 158 | print(f'{quantity} {fruit_name} @ ${price_per} each - ${round(total, 2)}') -------------------------------------------------------------------------------- /practice/unit_3/solutions/exercise_2_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 3 Practice Solutions 2 | 3 | ## **Exercise 1 Solution** 4 | 5 | ### **1.1** 6 | 7 | ```python 8 | def main(): 9 | # dictionary of tile scores 10 | scrabble = { 11 | 'BLANK': 0, 12 | 'A': 1, 13 | 'B': 3, 14 | 'C': 3, 15 | 'D': 2, 16 | 'E': 1, 17 | 'F': 4, 18 | 'G': 2, 19 | 'H': 4, 20 | 'I': 1, 21 | 'J': 8, 22 | 'K': 5, 23 | 'L': 1, 24 | 'M': 3, 25 | 'N': 1, 26 | 'O': 1, 27 | 'P': 3, 28 | 'Q': 10, 29 | 'R': 1, 30 | 'S': 1, 31 | 'T': 1, 32 | 'U': 1, 33 | 'V': 4, 34 | 'W': 4, 35 | 'X': 8, 36 | 'Y': 4, 37 | 'Z': 10, 38 | } 39 | 40 | 41 | # get the tiles from the user and uppercase them 42 | tiles = input('Please enter the letters on your tiles, separated by commas: ') 43 | 44 | # replace spaces with blank strings 45 | # convert all to uppercase 46 | tiles = tiles.replace(' ', '').upper() 47 | 48 | # split into a list at the commas 49 | tiles = tiles.split(',') 50 | 51 | # loop through the tiles and add up the point values 52 | total = 0 53 | for tile in tiles: 54 | # get the point value for the current tile 55 | point_value = scrabble[tile] 56 | # add the point value to the total 57 | total += point_value 58 | 59 | # place a comma and a space between each element in tiles and print the result 60 | result = f"With the letters {', '.join(tiles)} the maximum possible score is {total} if all the tiles are played." 61 | 62 | print(result) 63 | 64 | 65 | main() 66 | ``` 67 | 68 | Output: 69 | 70 | Please enter the letters on your tiles, separated by commas: blank,g,h,q,z,j,x 71 | 72 | With the letters BLANK, G, H, Q, Z, J, X the maximum possible score is 42 if all the tiles are played. 73 | 74 | ### **1.2** 75 | 76 | ```python 77 | def main(): 78 | # dictionary of tile scores 79 | scrabble = { 80 | 'BLANK': 0, 81 | 'A': 1, 82 | 'B': 3, 83 | 'C': 3, 84 | 'D': 2, 85 | 'E': 1, 86 | 'F': 4, 87 | 'G': 2, 88 | 'H': 4, 89 | 'I': 1, 90 | 'J': 8, 91 | 'K': 5, 92 | 'L': 1, 93 | 'M': 3, 94 | 'N': 1, 95 | 'O': 1, 96 | 'P': 3, 97 | 'Q': 10, 98 | 'R': 1, 99 | 'S': 1, 100 | 'T': 1, 101 | 'U': 1, 102 | 'V': 4, 103 | 'W': 4, 104 | 'X': 8, 105 | 'Y': 4, 106 | 'Z': 10, 107 | } 108 | 109 | tile_quantities = { 110 | 'A': 9, 111 | 'B': 2, 112 | 'C': 2, 113 | 'D': 4, 114 | 'E': 12, 115 | 'F': 2, 116 | 'G': 3, 117 | 'H': 2, 118 | 'I': 9, 119 | 'J': 1, 120 | 'K': 1, 121 | 'L': 4, 122 | 'M': 2, 123 | 'N': 6, 124 | 'O': 8, 125 | 'P': 2, 126 | 'Q': 1, 127 | 'R': 6, 128 | 'S': 4, 129 | 'T': 6, 130 | 'U': 4, 131 | 'V': 2, 132 | 'W': 2, 133 | 'X': 1, 134 | 'Y': 2, 135 | 'Z': 1, 136 | 'BLANK': 2, 137 | } 138 | 139 | # get the tiles from the user and uppercase them 140 | tiles = input( 141 | 'Please enter the letters on your tiles, separated by commas: ') 142 | 143 | # replace spaces with blank strings 144 | # convert all to uppercase 145 | tiles = tiles.replace(' ', '').upper() 146 | 147 | # split into a list at the commas 148 | tiles = tiles.split(',') 149 | 150 | # loop through the tiles and add up the point values 151 | total = 0 152 | for tile in tiles: 153 | 154 | # if the user's entry contains more of a tile than exist in Scrabble, tell the user. 155 | number_in_hand = tiles.count(tile) 156 | number_available = tile_quantities[tile] 157 | if number_in_hand > number_available: 158 | print(f'There is/are only {number_available} "{tile}" tile(s) in Scrabble. You entered {number_in_hand}.') 159 | 160 | # exit the main() function 161 | return 162 | 163 | # get the point value for the current tile 164 | point_value = scrabble[tile] 165 | # add the point value to the total 166 | total += point_value 167 | 168 | # place a comma and a space between each element in tiles and print the result 169 | result = f"With the letters {', '.join(tiles)} the maximum possible score is {total} if all the tiles are played." 170 | 171 | print(result) 172 | 173 | 174 | main() 175 | 176 | ``` 177 | 178 | **Output:** 179 | 180 | ``` 181 | Please enter the letters on your tiles, separated by commas: z,z,z,z,z,z,z 182 | 183 | There is/are only 1 "Z" tile(s) in Scrabble. You entered 7. 184 | ``` 185 | 186 | Keep in mind that this is just one potential solution. 187 | 188 | ## [< Exercise 2](../exercise_2.md)| [Exercise 3 >](../exercise_3.md) 189 | 190 | --- 191 | 192 | ### [<< Back to Unit 3 Practice](/practice/unit_3/) 193 | -------------------------------------------------------------------------------- /units/unit3.md: -------------------------------------------------------------------------------- 1 | # Unit 3 - Dictionaries 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | ### Table of Contents 8 | 9 | - [Dictionaries](#dictionaries) 10 | - [Dictionary Methods](#methods) 11 | - [Looping with Dictionaries](#loops) 12 | - [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_3/) 13 | - [Lab 3](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab3.md) 14 | 15 | --- 16 | 17 | ## Dictionaries 18 | 19 | - Dictionaries are one of the most powerful datatypes in Python. 20 | - They can be used to store large amounts of data and make working with data easy. 21 | - Dictionaries are a collection of `key: value` pairs 22 | - We can start with an empty dictionary: 23 | 24 | ```python 25 | employee_availability = {} 26 | ``` 27 | 28 | - Or we can start with some pre defined data: 29 | 30 | ```python 31 | employee_availability = { 32 | "lisa": "Mon", # string 33 | "al": ["Tues", "Wed", "Thurs"], # list 34 | "anthony": ["Mon", "Tues", "Wed", "Thurs", "Fri"] # list 35 | } 36 | ``` 37 | 38 | - The keys in our employee_availability dictionary are `lisa, al, and anthony` 39 | - The values in our employee_availability dictionary are `"Mon", ["Tues", "Wed", "Thurs"], ["Mon", "Tues", "Wed", "Thurs", "Fri"]` 40 | 41 | - To access a value in our dictionary we just need to use the key 42 | 43 | ```python 44 | schedule = employee_availability["al"] 45 | print(schedule) 46 | ``` 47 | 48 | > ["Tues", "Wed", "Thurs"] 49 | 50 | - We can change a value by also using a key: 51 | 52 | ```python 53 | employee_availability["al"] = ["Mon", "Wed", "Fri"] 54 | schedule = employee_availability["al"] 55 | print(schedule) 56 | ``` 57 | 58 | > ["Mon", "Wed", "Fri"] 59 | 60 | - To add a new value, we just need to give our dictionary a new key, then assign it a value: 61 | 62 | ```python 63 | employee_availability["bill"] = ["Mon", "Wed", "Fri"] 64 | print(employee_availability) 65 | ``` 66 | 67 | > {"lisa": "Mon", "al": ["Mon", "Wed", "Fri"], "anthony": ["Mon", "Tues", "Wed", "Thurs", "Fri"], "bill": ["Mon", "Wed", "Fri"]} 68 | 69 | - To remove a key value pair from a dictionary we use the `del` keyword 70 | 71 | ```python 72 | del employee_availability["bill"] 73 | print(employee_availability) 74 | ``` 75 | 76 | > {"lisa": "Mon", "al": ["Mon", "Wed", "Fri"], "anthony": ["Mon", "Tues", "Wed", "Thurs", "Fri"]} 77 | 78 | --- 79 | 80 | ## Dictionary Methods 81 | 82 | Methods give datatypes more functionality, and just like [string methods](https://www.w3schools.com/python/python_ref_string.asp) and [list methods](https://www.w3schools.com/python/python_ref_list.asp), we also have [dictionary methods](https://www.w3schools.com/python/python_ref_dictionary.asp). 83 | 84 | | method | description | example | 85 | | -------- | ------------------------------------------------------------------------- | -------------------------------------------- | 86 | | clear() | Removes all elements from a dictionary | dictionary_name.clear() | 87 | | copy() | Returns a copy of the dictionary | new_dictionary = dictionary_name.copy() | 88 | | get() | Returns the value of a specified key, or a default value if key not found | data = dictionary_name.get("key", False) | 89 | | items() | Returns a list containing key: value pairs | data = dictionary_name.items() | 90 | | keys() | Returns a list contianing a list of keys | keys = dictionary_name.keys() | 91 | | pop() | Removes the element with the specified key | dictionary_name.pop("key") | 92 | | update() | Updates the dictionary with the specified key: value pairs | dictionary_name.update({"key": "new value"}) | 93 | | values() | Returns a list of all the values | values = dictionary_name.values() | 94 | 95 | --- 96 | 97 | ## Looping with Dictionaries 98 | 99 | Since dictinaries can become quite large, Python allows us to loop over them. 100 | There are two was to loop over a dictionary: 101 | 102 | - The first is to loop over the keys 103 | 104 | ```python 105 | for key in employee_availability: 106 | print(key) 107 | ``` 108 | 109 | ```python 110 | > "lisa" 111 | > "al" 112 | > "anthony" 113 | ``` 114 | 115 | - The second is to loop over both the keys and values using the .items() method 116 | 117 | ```python 118 | for key, value in employee_availability.items(): 119 | print(key, value) 120 | ``` 121 | 122 | ```python 123 | > "lisa" "Mon" 124 | > "al" ["Mon", "Wed", "Fri"] 125 | > "anthony" ["Mon", "Tues", "Wed", "Thurs", "Fri"] 126 | ``` 127 | 128 | ### [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_3/) 129 | 130 | ### [Lab 3](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab3.md) 131 | 132 | [Back to top](#top) 133 | -------------------------------------------------------------------------------- /units/unit2.md: -------------------------------------------------------------------------------- 1 | # Unit 2 - Functions 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | ### Table of Contents 8 | 9 | - [REPL](#repl) 10 | - [What is a Function](#whatis) 11 | - [Defining a Function](#define) 12 | - [Passing Arguments to Functions](#arguments) 13 | - [Return](#return) 14 | - [main( )](#main) 15 | - [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_2/) 16 | - [Lab 2](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab2.md) 17 | 18 | --- 19 | 20 | ## REPL 21 | 22 | - **Read:** take user input 23 | - **Evaluate:** evaluate the input 24 | - **Print:** shows the output to user 25 | - **Loop:** repeat 26 | 27 | ```python 28 | play_again = "yes" 29 | while play_again == "yes": 30 | # Do some stuff 31 | play_again = input("Would you like to play again? ") 32 | ``` 33 | 34 | --- 35 | 36 | ## What is a function? 37 | 38 | - A function is a named block of code that runs only when called. 39 | - They are typically designed to do one specific job. 40 | - Once defined, you can call a function as many times as needed. 41 | - You can think of them as a variable, but for a whole block of code! 42 | 43 | --- 44 | 45 | ## Defining a function 46 | 47 | - Functions are defined (or created) by using the `def` keyword. 48 | 49 | ```python 50 | def my_func(): 51 | "This is where the body of the function goes" 52 | ``` 53 | 54 | - As we see above, we use the `def` keyword followed by our functions name `my_func`. 55 | - Notice how the function body is indented. Python uses indentation instead of `{ }` or `( )` like other languages. 56 | - The body is how we tell the computer what `my_func` does. 57 | - It is good practice to use docstrings to tell the user what the function does. Docstrings start and end with triple quotes. 58 | 59 | ```python 60 | def my_func(): 61 | '''This is a docstring, use this to tell other users what this function does''' 62 | 63 | print("The function body goes below the docstring") 64 | ``` 65 | 66 | - Now that we have defined a function, in order to use it we need to call that function. 67 | 68 | ```python 69 | my_func() 70 | ``` 71 | 72 | --- 73 | 74 | ## Passing Arguments to Functions 75 | 76 | - We can pass information into our function and have it do something with that data. 77 | - This requires us to change our function definition slightly. 78 | 79 | ```python 80 | def my_func(message): 81 | '''This function will print a message''' 82 | print(message) 83 | ``` 84 | 85 | - Now that we have told our function to expect some data, we just pass in the data when we call the function. 86 | 87 | ```python 88 | my_func("Hello World") 89 | ``` 90 | 91 | - The data `"Hello World"` is being passed in to our function call. 92 | - That data is then stored in the variable `message`. 93 | - If we run this function, our output would be: `Hello World`. 94 | - You can declare as many arguments in your function defintion as you want. 95 | 96 | - You can even declare default values to the variables we create. 97 | - Using defaults is a good way to avoid errors in your code. 98 | 99 | ```python 100 | def my_func(message="Hello"): 101 | '''This function will print a message''' 102 | print(message) 103 | ``` 104 | 105 | - Now we can see what the output would look like if we do not pass in any data: 106 | 107 | ```python 108 | my_func() 109 | ``` 110 | 111 | > "Hello" 112 | 113 | - And if we do pass in data: 114 | 115 | ```python 116 | my_func("Nice day today!") 117 | ``` 118 | 119 | > "Nice day today!" 120 | 121 | --- 122 | 123 | ## Return 124 | 125 | - Variables and data used inside a function are unique to that function. 126 | - If I declare a variable inside a function, it will only exist inside that function. 127 | - So how do we get the data back out? We use the `return` keyword 128 | 129 | ```python 130 | def add(num1, num2): 131 | '''This function will add two numbers together and return the result''' 132 | num = num1 + num2 133 | return num 134 | 135 | added_nums = add(3, 4) 136 | print(added_nums) 137 | ``` 138 | 139 | In this case our output would be: 140 | 141 | > 7 142 | 143 | --- 144 | 145 | ## main( ) 146 | 147 | - It is good practice to use a main function. This is where the core functionality of your code will live. 148 | - Using a main function also helps us keep code clean and helps us avoid using global variables 149 | - Using a main function is similar to using any other function 150 | - First we define the function: 151 | 152 | ```python 153 | def main(): 154 | '''This is our main function''' 155 | 156 | # All of our code goes here 157 | 158 | ``` 159 | 160 | - Then we just need to call that main function 161 | 162 | ```python 163 | main() 164 | ``` 165 | 166 | - Just keep in mind if you define other functions, you define them before your main function. 167 | 168 | --- 169 | 170 | ### [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_2) 171 | 172 | ### [Lab 2](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab2.md) 173 | 174 | [Back to top](#top) 175 | -------------------------------------------------------------------------------- /resources/countwords.txt: -------------------------------------------------------------------------------- 1 | Alice was beginning to get very tired of sitting by her sister on the 2 | bank, and of having nothing to do. Once or twice she had peeped into the 3 | book her sister was reading, but it had no pictures or conversations in 4 | it, "and what is the use of a book," thought Alice, "without pictures or 5 | conversations?" 6 | 7 | So she was considering in her own mind (as well as she could, for the 8 | day made her feel very sleepy and stupid), whether the pleasure of 9 | making a daisy-chain would be worth the trouble of getting up and 10 | picking the daisies, when suddenly a White Rabbit with pink eyes ran 11 | close by her. 12 | 13 | There was nothing so very remarkable in that, nor did Alice think it so 14 | very much out of the way to hear the Rabbit say to itself, "Oh dear! Oh 15 | dear! I shall be too late!" But when the Rabbit actually took a watch 16 | out of its waistcoat-pocket and looked at it and then hurried on, Alice 17 | started to her feet, for it flashed across her mind that she had never 18 | before seen a rabbit with either a waistcoat-pocket, or a watch to take 19 | out of it, and, burning with curiosity, she ran across the field after 20 | it and was just in time to see it pop down a large rabbit-hole, under 21 | the hedge. In another moment, down went Alice after it! 22 | 23 | The rabbit-hole went straight on like a tunnel for some way and then 24 | dipped suddenly down, so suddenly that Alice had not a moment to think 25 | about stopping herself before she found herself falling down what seemed 26 | to be a very deep well. 27 | 28 | Either the well was very deep, or she fell very slowly, for she had 29 | plenty of time, as she went down, to look about her. First, she tried to 30 | make out what she was coming to, but it was too dark to see anything; 31 | then she looked at the sides of the well and noticed that they were 32 | filled with cupboards and book-shelves; here and there she saw maps and 33 | pictures hung upon pegs. She took down a jar from one of the shelves as 34 | she passed. It was labeled "ORANGE MARMALADE," but, to her great 35 | disappointment, it was empty; she did not like to drop the jar, so 36 | managed to put it into one of the cupboards as she fell past it. 37 | 38 | Down, down, down! Would the fall never come to an end? There was nothing 39 | else to do, so Alice soon began talking to herself. "Dinah'll miss me 40 | very much to-night, I should think!" (Dinah was the cat.) "I hope 41 | they'll remember her saucer of milk at tea-time. Dinah, my dear, I wish 42 | you were down here with me!" Alice felt that she was dozing off, when 43 | suddenly, thump! thump! down she came upon a heap of sticks and dry 44 | leaves, and the fall was over. 45 | 46 | Alice was not a bit hurt, and she jumped up in a moment. She looked up, 47 | but it was all dark overhead; before her was another long passage and 48 | the White Rabbit was still in sight, hurrying down it. There was not a 49 | moment to be lost. Away went Alice like the wind and was just in time to 50 | hear it say, as it turned a corner, "Oh, my ears and whiskers, how late 51 | it's getting!" She was close behind it when she turned the corner, but 52 | the Rabbit was no longer to be seen. 53 | 54 | She found herself in a long, low hall, which was lit up by a row of 55 | lamps hanging from the roof. There were doors all 'round the hall, but 56 | they were all locked; and when Alice had been all the way down one side 57 | and up the other, trying every door, she walked sadly down the middle, 58 | wondering how she was ever to get out again. 59 | 60 | Suddenly she came upon a little table, all made of solid glass. There 61 | was nothing on it but a tiny golden key, and Alice's first idea was that 62 | this might belong to one of the doors of the hall; but, alas! either the 63 | locks were too large, or the key was too small, but, at any rate, it 64 | would not open any of them. However, on the second time 'round, she came 65 | upon a low curtain she had not noticed before, and behind it was a 66 | little door about fifteen inches high. She tried the little golden key 67 | in the lock, and to her great delight, it fitted! 68 | 69 | Alice opened the door and found that it led into a small passage, not 70 | much larger than a rat-hole; she knelt down and looked along the passage 71 | into the loveliest garden you ever saw. How she longed to get out of 72 | that dark hall and wander about among those beds of bright flowers and 73 | those cool fountains, but she could not even get her head through the 74 | doorway. "Oh," said Alice, "how I wish I could shut up like a telescope! 75 | I think I could, if I only knew how to begin." 76 | 77 | Alice went back to the table, half hoping she might find another key on 78 | it, or at any rate, a book of rules for shutting people up like 79 | telescopes. This time she found a little bottle on it ("which certainly 80 | was not here before," said Alice), and tied 'round the neck of the 81 | bottle was a paper label, with the words "DRINK ME" beautifully printed 82 | on it in large letters. 83 | 84 | "No, I'll look first," she said, "and see whether it's marked '_poison_' 85 | or not," for she had never forgotten that, if you drink from a bottle 86 | marked "poison," it is almost certain to disagree with you, sooner or 87 | later. However, this bottle was _not_ marked "poison," so Alice ventured 88 | to taste it, and, finding it very nice (it had a sort of mixed flavor of 89 | cherry-tart, custard, pineapple, roast turkey, toffy and hot buttered 90 | toast), she very soon finished it off. -------------------------------------------------------------------------------- /resources/example_lessons/unit_5/alice.txt: -------------------------------------------------------------------------------- 1 | Alice was beginning to get very tired of sitting by her sister on the 2 | bank, and of having nothing to do. Once or twice she had peeped into the 3 | book her sister was reading, but it had no pictures or conversations in 4 | it, "and what is the use of a book," thought Alice, "without pictures or 5 | conversations?" 6 | 7 | So she was considering in her own mind (as well as she could, for the 8 | day made her feel very sleepy and stupid), whether the pleasure of 9 | making a daisy-chain would be worth the trouble of getting up and 10 | picking the daisies, when suddenly a White Rabbit with pink eyes ran 11 | close by her. 12 | 13 | There was nothing so very remarkable in that, nor did Alice think it so 14 | very much out of the way to hear the Rabbit say to itself, "Oh dear! Oh 15 | dear! I shall be too late!" But when the Rabbit actually took a watch 16 | out of its waistcoat-pocket and looked at it and then hurried on, Alice 17 | started to her feet, for it flashed across her mind that she had never 18 | before seen a rabbit with either a waistcoat-pocket, or a watch to take 19 | out of it, and, burning with curiosity, she ran across the field after 20 | it and was just in time to see it pop down a large rabbit-hole, under 21 | the hedge. In another moment, down went Alice after it! 22 | 23 | The rabbit-hole went straight on like a tunnel for some way and then 24 | dipped suddenly down, so suddenly that Alice had not a moment to think 25 | about stopping herself before she found herself falling down what seemed 26 | to be a very deep well. 27 | 28 | Either the well was very deep, or she fell very slowly, for she had 29 | plenty of time, as she went down, to look about her. First, she tried to 30 | make out what she was coming to, but it was too dark to see anything; 31 | then she looked at the sides of the well and noticed that they were 32 | filled with cupboards and book-shelves; here and there she saw maps and 33 | pictures hung upon pegs. She took down a jar from one of the shelves as 34 | she passed. It was labeled "ORANGE MARMALADE," but, to her great 35 | disappointment, it was empty; she did not like to drop the jar, so 36 | managed to put it into one of the cupboards as she fell past it. 37 | 38 | Down, down, down! Would the fall never come to an end? There was nothing 39 | else to do, so Alice soon began talking to herself. "Dinah'll miss me 40 | very much to-night, I should think!" (Dinah was the cat.) "I hope 41 | they'll remember her saucer of milk at tea-time. Dinah, my dear, I wish 42 | you were down here with me!" Alice felt that she was dozing off, when 43 | suddenly, thump! thump! down she came upon a heap of sticks and dry 44 | leaves, and the fall was over. 45 | 46 | Alice was not a bit hurt, and she jumped up in a moment. She looked up, 47 | but it was all dark overhead; before her was another long passage and 48 | the White Rabbit was still in sight, hurrying down it. There was not a 49 | moment to be lost. Away went Alice like the wind and was just in time to 50 | hear it say, as it turned a corner, "Oh, my ears and whiskers, how late 51 | it's getting!" She was close behind it when she turned the corner, but 52 | the Rabbit was no longer to be seen. 53 | 54 | She found herself in a long, low hall, which was lit up by a row of 55 | lamps hanging from the roof. There were doors all 'round the hall, but 56 | they were all locked; and when Alice had been all the way down one side 57 | and up the other, trying every door, she walked sadly down the middle, 58 | wondering how she was ever to get out again. 59 | 60 | Suddenly she came upon a little table, all made of solid glass. There 61 | was nothing on it but a tiny golden key, and Alice's first idea was that 62 | this might belong to one of the doors of the hall; but, alas! either the 63 | locks were too large, or the key was too small, but, at any rate, it 64 | would not open any of them. However, on the second time 'round, she came 65 | upon a low curtain she had not noticed before, and behind it was a 66 | little door about fifteen inches high. She tried the little golden key 67 | in the lock, and to her great delight, it fitted! 68 | 69 | Alice opened the door and found that it led into a small passage, not 70 | much larger than a rat-hole; she knelt down and looked along the passage 71 | into the loveliest garden you ever saw. How she longed to get out of 72 | that dark hall and wander about among those beds of bright flowers and 73 | those cool fountains, but she could not even get her head through the 74 | doorway. "Oh," said Alice, "how I wish I could shut up like a telescope! 75 | I think I could, if I only knew how to begin." 76 | 77 | Alice went back to the table, half hoping she might find another key on 78 | it, or at any rate, a book of rules for shutting people up like 79 | telescopes. This time she found a little bottle on it ("which certainly 80 | was not here before," said Alice), and tied 'round the neck of the 81 | bottle was a paper label, with the words "DRINK ME" beautifully printed 82 | on it in large letters. 83 | 84 | "No, I'll look first," she said, "and see whether it's marked '_poison_' 85 | or not," for she had never forgotten that, if you drink from a bottle 86 | marked "poison," it is almost certain to disagree with you, sooner or 87 | later. However, this bottle was _not_ marked "poison," so Alice ventured 88 | to taste it, and, finding it very nice (it had a sort of mixed flavor of 89 | cherry-tart, custard, pineapple, roast turkey, toffy and hot buttered 90 | toast), she very soon finished it off. -------------------------------------------------------------------------------- /resources/lessons/lesson_2: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 2 4 | ''' 5 | 6 | import random 7 | 8 | ''' 9 | R ead 10 | E valuate 11 | P rint 12 | L oop 13 | ''' 14 | 15 | 16 | ''' 17 | play_again = 'yes' 18 | 19 | # this loop will only loop if the user enters exactly 'yes' 20 | while play_again == 'yes': 21 | # loop this code block 22 | 23 | print('\nWelcome to the game!') 24 | 25 | # ... 26 | # ... other code .. 27 | # ... 28 | 29 | # ask the user if they want to play again 30 | play_again = input('Do you want to play again? yes/no:') 31 | else: 32 | print('\nThanks for playing!') 33 | ''' 34 | # ------------------------------------------------------------------------------- # 35 | ''' 36 | while True: # infinite loop, requiring 'break' to end the loop 37 | # ask the user for a color and give them the option to quit 38 | color = input("\nEnter a color or 'done' to quit: ") 39 | 40 | # check if the user wants to quit 41 | if color == 'done': 42 | print('Goodbye!') 43 | break # end the loop 44 | 45 | print(f'\nThanks for entering "{color}"') 46 | ''' 47 | 48 | # ------------------------------------------------------------------------------- # 49 | 50 | # Functions! 51 | 52 | # built-in functions 53 | # print(), type(), input(), len(), str(), int(), float(), list(), bool(), range() 54 | 55 | ''' 56 | Functions 57 | 58 | - named code blocks 59 | - run only when called upon with parentheses after their name 60 | - typically designed to perform a single task 61 | - once defined, a function can be called as many times as needed with different data 62 | - receive data & return data after it's been manipulated 63 | ''' 64 | # ------------------------------------------------------------------------------- # 65 | 66 | ''' 67 | # parameters are empty variables in a function's defintion which await data from the function call 68 | def function_name(parameter_1, parameter_2, ...): 69 | # this code block will be run 70 | # when the function is 'called' 71 | 72 | # manipulate the parameters somehow 73 | 74 | # send the result back to where the function was called 75 | # with the keyword 'return' 76 | # if no return value is specified, a function will return 'None' by default 77 | return manipulated_parameters 78 | 79 | # call the function and save the return value in a variable 80 | data_returned_from_function = function_name(argument_1, argument_2, ...) 81 | ''' 82 | # ------------------------------------------------------------------------------- # 83 | 84 | # increment(number) - add one to the number and return the result 85 | 86 | def increment(number): 87 | result = number + 1 88 | return result 89 | 90 | # call the function with a value for 'number' 91 | result = increment(9) 92 | # print(result) # 10 93 | 94 | result = increment(result) 95 | # print(result) # 11 96 | 97 | 98 | # use the function in a loop 99 | 100 | x = 0 101 | 102 | while x < 10: 103 | # print(x) 104 | 105 | # use the function to increment x 106 | x = increment(x) 107 | 108 | # -------------------------------------------------------------------------------------- # 109 | 110 | # arguments MUST be passed to fill parameters (unless default values are provided) 111 | # increment() # TypeError: increment() missing 1 required positional argument: 'number' 112 | 113 | 114 | # -------------------------------------------------------------------------------------- # 115 | 116 | # add(a, b) - return the sum of two numbers, 'a' and 'b' 117 | 118 | def add(a=1, b=1): 119 | return a + b 120 | 121 | # if NO default values are provided for parameters: 122 | # add() # TypeError: add() missing 2 required positional arguments: 'a' and 'b' 123 | # add(9) # TypeError: add() missing 1 required positional argument: 'b' 124 | # print(add(9, 1)) # 10 - a=9, b=1 125 | 126 | # if default values ARE provided for parameters 127 | # print(add(10)) # 11 - (a=10, b=default) 128 | # print(add()) # 2 - (a=default, b=default) 129 | # print(add(5, 2)) # 7 - (a=5, b=2) 130 | # print(add(b=7)) # 8 - (a=default, b=7) 131 | # print(add(b=7, a=5)) # 12 (a=5, b=7) 132 | 133 | # -------------------------------------------------------------------------------------- # 134 | 135 | # 'shred' a string and return a randomized list of its characters 136 | 137 | def shred_string(string): 138 | # convert the string to a list of its characters 139 | characters = list(string) 140 | 141 | # random the list 142 | random.shuffle(characters) 143 | 144 | return characters 145 | 146 | 147 | shredded = shred_string('hello world') 148 | # print(shredded) 149 | 150 | shredded = shred_string('ABCDEFG') 151 | # print(shredded) 152 | 153 | # -------------------------------------------------------------------------------------- # 154 | 155 | # generate a list of 'k' integers between 'low' and 'high' 156 | 157 | def generate_random_numbers(k, low=0, high=100): 158 | # create a blank list to store the numbers 159 | numbers = [] 160 | 161 | # loop 'k' times 162 | for x in range(k): 163 | # generate a random number between 'low' and 'high' 164 | random_number = random.randint(low, high) 165 | 166 | # add the number to the list 167 | numbers.append(random_number) 168 | 169 | return numbers 170 | 171 | random_numbers = generate_random_numbers(10) 172 | # print(random_numbers) # [93, 62, 25, 98, 76, 75, 42, 20, 25, 37] 173 | 174 | random_numbers = generate_random_numbers(3, 10, 20) 175 | # print(random_numbers) # [13, 11, 15] 176 | 177 | random_numbers = generate_random_numbers(10000, -100, 100) 178 | # print(random_numbers) 179 | -------------------------------------------------------------------------------- /docs/vocab.md: -------------------------------------------------------------------------------- 1 | # Programming Vocab 2 | 3 | 4 | 5 | ## Argument 6 | 7 | - An object passed to a function to fill one of its parameters 8 | 9 | - When a function is called, arguments are passed to fill the functions parameters 10 | 11 | ## Class 12 | 13 | - A data structure which acts as a blueprint for creating objects. 14 | 15 | - All Python datatypes are created with classes. 16 | 17 | - When we create an object, we're creating an 'instance' of a pre-defined class which shares all the attributes of the class but can have properties unique to each instance 18 | 19 | - Classes have attributes which can be functions or variables 20 | 21 | ## Code Block 22 | 23 | - A section of code that executes together 24 | 25 | - In Python, code blocks are defined using horizontal indentation. 26 | 27 | - The first line of code in a code block determines its indentation and all subsequent lines in that block must match that indentation. 28 | 29 | ## Concatenation 30 | - Adding two strings together with a plus sign (`+`) to form a single string 31 | 32 | ## Docstring 33 | 34 | - A multi-line string at the beginning of a function's code block that provides documentation about the function, its parameters and its return value 35 | 36 | ## Function 37 | 38 | - A named code block that performs a specific task. 39 | 40 | - Functions reduce repetition in our code by allowing us to write code in a generic way and use it with multiple values. 41 | 42 | - Functions are executed with parentheses after their name. (e.g. `print()`) 43 | 44 | ## Immutable (Unchangeable) 45 | If an object is immutable, it cannot be given a new value directly. Instead, a new copy of the object will need to be created with the desired changes applied. 46 | 47 | See "Mutable" 48 | 49 | ## Index 50 | 51 | - An item's position in a sequence (list, string, etc.) 52 | 53 | - Indices are always integers and must correspond to an existing item in the sequence, otherwise an `IndexError` will be raised. 54 | ## Iteration 55 | A single pass through a loop's code block. A loop is made of one or more iterations. 56 | 57 | ## Loop 58 | 59 | - A code block that repeats until a certain condition is met. 60 | 61 | - With a `for` loop, the condition is that there are more items left in the `sequence` 62 | 63 | - With a `while` loop, we define the condition directly. 64 | 65 | ## Method 66 | 67 | - A function that only manipulates the object to which it belongs 68 | 69 | ## Module 70 | A Python file containing code that can be imported into another Python file to be used. 71 | 72 | All the code in the global scope of a module is run when that module is 73 | 74 | ## Mutable (Changeable) 75 | If an object is mutable, it has the ability to be given a new value without needing to create a new instance of the object. 76 | 77 | See "Immutable" 78 | 79 | ## Object 80 | 81 | - A collection of variables and methods that act on those variables. 82 | 83 | - A class is a blueprint for an object. Multiple objects can be created from the same class. 84 | 85 | - The variables and methods contained in an object are called its 'attributes' 86 | 87 | - An object's attributes are accessed with dot notation (e.g. `'abc'.upper()`) 88 | 89 | ## Operand 90 | 91 | - A piece of data being used to perform an operation 92 | 93 | ## Operation 94 | 95 | - Any process that manipulates data (operands) 96 | 97 | ## Operator 98 | 99 | - A symbol or word that performs an operation on one or more pieces of data (operands) 100 | 101 | ## Ordered Sequence 102 | 103 | - A sequence whose items can be retrieved using their position in the sequence 104 | 105 | - An item's position in a sequence is called its 'index'. 106 | 107 | - Lists (`list`) and Strings (`str`) are examples of ordered sequences. 108 | 109 | - Python Sets (`set`) are an example of an *un*-ordered sequence. 110 | 111 | ## Parameter 112 | An empty variable in the definition of a function which will hold the values which are to be used in the function. 113 | 114 | When a function is called, values are passed through the parentheses in the function call and those values are assigned to the parameters and then passed into the function's code block. 115 | 116 | Parameters can also be given default values that will be used if no value is passed for that parameter. 117 | 118 | ```python 119 | # 'a' and 'b' are parameters 120 | # 'b' has a default value of 1 121 | def add(a, b=1): 122 | '''return the sum of two numbers, 'a' and 'b'''' 123 | return a + b 124 | ``` 125 | 126 | 127 | ## Return Value 128 | The value that is sent back from a function to the location where the function was called. 129 | 130 | The return value takes the place of the function call as the code is evaluated. 131 | 132 | ## Scope 133 | Four levels in which variables exist in any Python file. Data in outer scopes are available to inner scopes, but data in inner scopes isn't available to outer scopes. 134 | 135 | Data can be returned from functions to make it available to outer scopes. 136 | 137 | ### Levels of scope 138 | **Built-in** - Everything included behind-the-scenes in a Python file 139 | 140 | **Global** - Everything created in the Python file 141 | 142 | **Enclosed** - Everything defined within the code block of a global function 143 | 144 | **Local** - Everything within the code block of an enclosed function 145 | 146 | ## Sequence 147 | A collection of items. Sequences can be ordered (e.g. lists and strings) or unordered (e.g. sets and dictionaries) 148 | 149 | If a sequence is ordered, its items can be retrieved using their positions in the list. 150 | 151 | ## Subscriptable 152 | The quality of being able to use an index or key to retrieve a value from an object. 153 | 154 | 155 | ## Typecasting 156 | The process of converting one type of data to another. 157 | ## Variable 158 | - A named storage space for data. 159 | 160 | - Variables can store objects of any datatype and can be used in operations involving that datatype. 161 | 162 | - Variables can be re-defined with new values at any time. 163 | 164 | 165 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /labs/lab5.md: -------------------------------------------------------------------------------- 1 | # Lab 5 - User Login 2 | 3 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 4 | 5 | Create a REPL which allows a user to 'log in'. 6 | 7 | Please complete the sections **in order**. Create a working version of 5.1 before attempting 5.2, etc. This will make your life easier. You may also want to consider creating separate `.py` files for each version, so you can refer back to previous working versions. 8 | 9 | ### **5.1** 10 | 11 | Create a dictionary called `profile` 12 | 13 | The `profile` should contain **two** **key : value** pairs with keys of `username` and `password` and values of your choosing. They will represent a `username` and `password` for a **single** user. 14 | 15 | username - gandalfTheGrey 16 | password - noneShallPass! 17 | 18 | **Do not** create your profile with the user's username as the key and their password as the value as below: 19 | 20 | 'gandalfTheGrey':'noneShallPass' 21 | 22 | Define a function called `login()` which will have three parameters for: 23 | 24 | - `username_attempt` 25 | - `password_attempt` 26 | - `profile` 27 | 28 | If the values passed to the function for `username_attempt` and `password_attempt` match the values at the keys of `username` and `password` found in the `profile`, The `login()` function will `return True`. 29 | 30 | If the credentials don't match those in the `profile`, the `login()` function will `return False` 31 | 32 | - Create variables for a `username_attempt` and `password_attempt` which will emulate a user's login attempt. 33 | 34 | - Pass the `profile` dictionary, `username_attempt` and `password_attempt` to `login()`. Use the boolean that is returned to tell the user whether or not their login attempt was successful. 35 | 36 | Output: 37 | ``` 38 | # successful login 39 | username: gandalfTheGrey 40 | password: noneShallPass! 41 | 42 | Welcome, gandalfTheGrey! 43 | 44 | # unsuccessful login 45 | username: gandalfTheGrey 46 | password: myPrecious? 47 | 48 | Error! Your username or password was incorrect! 49 | ``` 50 | ### **5.2** 51 | 52 | Create a REPL that asks the user for their `username_attempt` and `password_attempt` and attempts to log them in. 53 | 54 | If their login is **successful**, print a welcome message and end the program. 55 | 56 | If their login is **unsuccessful**, ask if they'd like to try again. 57 | 58 | ### **5.3 - Extra Challenge** 59 | 60 | Allow the user **three attempts** to login. If they exceed three attempts without a successful login, tell the user and end the program 61 | 62 | Output: 63 | 64 | username: gandalfTheGrey 65 | password: myPrecious? 66 | 67 | Error! Your username or password was incorrect! 68 | 69 | Enter 'y' to try again, 'n' to quit: y 70 | 71 | You have 2 login attempt(s) remaining... 72 | 73 | username: gandalfTheGrey 74 | password: foolOfATook! 75 | 76 | Error! Your username or password was incorrect! 77 | 78 | Enter 'y' to try again, 'n' to quit: y 79 | 80 | You have 1 login attempt(s) remaining... 81 | 82 | username: gandalfTheGrey 83 | password: bilboBaggins! 84 | 85 | Error! Your username or password was incorrect! 86 | 87 | Your login has been unsuccessful three times! Try again later. Goodbye! 88 | 89 | ### **5.4 - Extra Challenge** 90 | 91 | Add support for **multiple** users. 92 | 93 | A few things will need to change: 94 | 95 | - Instead of one `profile`, you will need a **_list_** of `profiles`. Each `profile` will be a dictionary containing **key : value** pairs with the keys of `username` and `password`. 96 | 97 | - When the user enters their username and password attempts, loop through the list of `profiles`, pass each `profile` one at time into the `login()` function along with the `username_attempt` and `password_attempt`. 98 | 99 | - If the `username_attempt` and `password_attempt` match the values at the keys of `username` and `password` current `profile`, the `login()` function will return that `True` and that user will be logged in. Otherwise, it will return `False`. 100 | 101 | ### **5.5 - Extra Challenge** 102 | 103 | - Define a function called `user_exists()` which will: 104 | 105 | - loop through each `profile` in the `profiles` list 106 | - check to see if the `username` the user entered already exists within one of the `profile` dictionaries. 107 | 108 | If a user with that `username` already exists, `return True`, otherwise `return False` 109 | 110 | - Define a function called `create_user()` which: 111 | 112 | - prompts the user for a `username` and `password`. 113 | - checks to see if the `username` already exists in the `profiles` list using the `user_exists()` function 114 | - If the `username` is unique and doesn't appear in the `profiles` list, `.append()` it to the `profiles` list. 115 | 116 | 117 | - Integrate the `create_user()` function into your REPL to allow the user to create a new username. 118 | 119 | --- 120 | 121 | Profiles list: 122 | 123 | username: gandalfTheGrey 124 | password: noneShallPass! 125 | 126 | username: bilboBaggins 127 | password: theShire123 128 | 129 | username: iAmSmeagol 130 | password: myPrecious! 131 | 132 | Output: 133 | 134 | Welcome! 135 | 136 | Please select from the following options: 137 | 138 | 1. Create user 139 | 2. Login 140 | 141 | Enter the number of your choice: 1 142 | 143 | Create User 144 | ----------- 145 | Enter your new username: gandalfTheGrey 146 | 147 | That username already exists! 148 | 149 | Enter your new username: 150 | mrSamwise 151 | 152 | Enter your password: 153 | frodoIsMyFriend 154 | 155 | Thanks for signing up, mrSamwise! 156 | 157 | Please select from the following options: 158 | 159 | 1. Create user 160 | 2. Login 161 | 162 | Enter the number of your choice: 2 163 | 164 | Login: 165 | ------ 166 | 167 | username: smaugTheDragon 168 | password: gimmeYerGold! 169 | 170 | Error! Your username or password was incorrect! 171 | 172 | Enter 'y' to try again, 'n' to quit: y 173 | 174 | You have 2 login attempt(s) remaining... 175 | 176 | username: iAmSmeagol 177 | password: myPrecious! 178 | 179 | Welcome, iAmSmeagol! 180 | 181 | --- 182 | 183 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 184 | -------------------------------------------------------------------------------- /practice/unit_4/exercise_2.md: -------------------------------------------------------------------------------- 1 | ## Unit 4 Practice 2 | 3 | ## **Exercise 2 - Hero Battle** 4 | 5 | ##
2.1
6 | --- 7 | Create two dictionaries, `hero` and `villain`. The items in each dictionary will represent each characters stats. 8 | 9 |
10 | 11 | |Stat|Datatype|Values| 12 | |-|-|-| 13 | |`name`| string| any| 14 | |`hp`| integer | 0 - 100| 15 | |`attack` | integer |1 - 10| 16 |
17 | 18 |
19 |
20 | 21 | ## `is_defeated()` 22 | The `is_defeated()` function will determine if a player's `hp` is at or below zero, meaning they're been defeated. Here's the function's definition: 23 | 24 | ```python 25 | def is_defeated(character): 26 | ''' 27 | Returns False if the character's hp is greater than zero 28 | Returns True if the character's hp is less than or equal to 29 | ''' 30 | # ... your code here ... 31 | 32 | pass # replace 'pass' with a return statement 33 | ``` 34 | 35 |
36 |
37 | 38 | 39 |
40 | 41 | Write a REPL which allows the two characters to do battle. Each character will attack during every loop. 42 | 43 | Each attack will subtract the character's `attack` strength from its opponents `hp`. Since the `attack` stat has a range from 1 - 10, **feel free to multiply it by *5* or *10* to speed up the battle.** 44 | 45 | Use the `is_defeated()` function to determine if the opponent has lost the battle, announce who won and end the loop. 46 | 47 | An `input()` function can be used to slow the battle down a bit and allow the user to decide when the next round of the battle will be executed. This way the battle will be more interactive and won't happen instantaneously. 48 | 49 |
50 | 51 | ### [Exercise 2.1 Solution](./solutions/exercise_2/exercise_2_1_solution.md) 52 | 53 |
54 |
55 | 56 | ##
2.2
57 | --- 58 | 59 | 60 | Chances are that there is a fair amount of reptition in the logic which performs each character's turn in the battle, since the same steps will need to be executed by each character during their turn. 61 | 62 | Create a function `attack()` to handle each round of the battle. 63 | 64 | ```python 65 | def attack(attacker, opponent): 66 | ''' 67 | Apply battle damage to the opponent using the attacker's attack stat 68 | If the opponent is defeated, return True, signifying the battle is over 69 | Otherwise return False, signifying the battle will continue for another round 70 | ''' 71 | # ... your code here ... 72 | 73 | return # use is_defeated() to return True/False if the battle is over 74 | ``` 75 | 76 | Subtract the value of the attacker's `attack` stat from the opponents `hp` stat. Return `True` if the opponent is defeated, otherwise return `False`. This boolean will be used to determine if the battle is over or if it will continue for another round. 77 | 78 |
79 | 80 | ### [Exercise 2.2 Solution](./solutions/exercise_2/exercise_2_2_solution.md) 81 | 82 | 83 |
84 |
85 | 86 | ##
2.3
87 | --- 88 | 89 | 90 | Add additional stats `defense` and `stance` and add allow each the characters to choose their `stance` each round. 91 | 92 |
93 | 94 | 95 | |Stat|Datatype|Values| 96 | |-|-|-| 97 | |`name`| string| any| 98 | |`hp`| integer | 0 - 100| 99 | |`attack` | integer |1 - 10| 100 | |`defense` |integer |1 - 10| 101 | |`stance`| string |`'attack'` / `'defend'`| 102 | 103 |
104 | 105 |
106 | 107 | If a character chooses to defend, they will not attack this turn. 108 | 109 | If the character's stance is set to `'defend'` when their opponent attacks, the damage they receive is reduced. If the character's stance is set to `'attack'`, no change is made to the incoming damage. 110 | 111 | Two additional functions could be added to handle these modifications: 112 | 113 |
114 | 115 | ## `set_stance()` 116 | 117 | This function will take in a character dictionary and allow them to choose whether they want to set their `stance` stat to`attack` or `defend` this round using a REPL. 118 | 119 | ```python 120 | def set_stance(character): 121 | ''' 122 | Ask the user which stance they would like to take this round. 123 | Change the value at the key of 'stance' to match the user's choice. 124 | Stance options: 'attack', 'defend' 125 | ''' 126 | 127 | # ... your code here ... 128 | 129 | # return the character dictionary with adjusted stance stat 130 | return character 131 | 132 | ``` 133 | 134 |
135 | 136 | ## `defend()` 137 | 138 | The function `defend()` will be used to adjust the incoming damage to a character when it's their opponent's turn to attack. 139 | 140 | Below are the damage reduction rates for different `'defense'` stat levels: 141 | 142 |
143 | 144 |
145 | 146 | |Defense Level|Damage Reduction| 147 | |-|-| 148 | |0 - 4|10%| 149 | |5 - 7|33%| 150 | |8 - 10|66%| 151 | 152 |
153 | 154 |
155 | 156 | ```python 157 | def defend(character, incoming_damage): 158 | ''' 159 | Calculate the amount the incoming_damage will be reduced 160 | based on the character's 'defense' stat. 161 | 162 | Return the amount the incoming_damage will be reduced 163 | in a variable called 'damage_reduction' 164 | 165 | 0 - 4 = 10%, 5 - 7 = 33%, 8 - 10 = 66% 166 | ''' 167 | 168 | # return the reduction amount, rounded to the nearest integer 169 | return round(damage_reduction) 170 | ``` 171 | 172 |
173 | 174 | ### [Exercise 2.3 Solution](./solutions/exercise_2/exercise_2_3_solution.md) 175 | 176 | 177 |
178 |
179 | 180 | --- 181 | 182 | ###
Extra Challenge
183 | 184 | Add some more fun features. Pull from your favorite games or stories and get creative! Some ideas might include: 185 | 186 | - Special, stronger attacks. These could even require a few rounds to build up power before they're able to be used. 187 | - randomized stats 188 | - randomize which character attacks first 189 | - add `'heal'` as a possible `stance` option and increase the character's `hp` that round if chosen based on a `healing` stat 190 | - have the opponent's choices be made by code, rather than user input 191 | - add a third character 192 | - More than one `villain` (list of dictionaries). The `hero` could `level_up()` with each opponent it defeats. 193 | 194 | 195 | --- 196 | 197 | ### [<< Back to Unit 4 Practice](/practice/unit_4/) 198 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_2/unit_2_lesson.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Programming 102 3 | Unit 2 4 | ''' 5 | 6 | import random 7 | 8 | ''' 9 | R ead 10 | E valuate 11 | P rint 12 | L oop 13 | ''' 14 | 15 | ### INTRODUCE THE TERMINAL AS A REPL 16 | 17 | ''' 18 | play_again = 'yes' 19 | 20 | # this loop will only loop if the user enters exactly 'yes' 21 | while play_again == 'yes': 22 | # loop this code block 23 | 24 | print('\nWelcome to the game!') 25 | 26 | # ... 27 | # ... other code ... 28 | # ... 29 | 30 | # ask the user if they want to play again 31 | play_again = input("Do you want to play again? yes/no: ") 32 | 33 | else: 34 | print("\nThanks for playing!") 35 | ''' 36 | # ------------------------------------------------------------------------------- # 37 | 38 | ''' 39 | while True: # infinite loop, requiring 'break' to end the loop 40 | # ask the user for a color and give them the option to quit 41 | color = input("\nEnter a color or 'done' to quit: ") 42 | 43 | # check if the user wants to quit 44 | if color == 'done': 45 | print('Goodbye!') 46 | break # end the loop 47 | 48 | 49 | print(f"\nThanks for entering '{color}'") 50 | 51 | ''' 52 | 53 | # ------------------------------------------------------------------------------------------ # 54 | 55 | # Functions! 56 | 57 | # built-in functions 58 | # print(), type(), input(), len(), str(), int(), float(), list(), bool(), range() 59 | 60 | ''' 61 | Functions 62 | 63 | - named code blocks 64 | - run only when called upon with parentheses after their name 65 | - typically designed to perform a single task 66 | - once defined, a function can be called as many times as needed with different data 67 | - receive data & return data after it's been manipulated 68 | ''' 69 | 70 | # ---------------------------------------------------------------------------------- # 71 | 72 | ### INTRODUCE INCREMENTALLY 73 | ### 1. KEYWORD def 74 | ### 2. function_name, PARENTHESES, AND COLON 75 | ### 3. EXPLAIN THAT THE CODE BLOCK WILL BE CALLED WHEN THE FUNCTION IS RUN 76 | ### 4. DEFINE PARAMETERS TO ALLOW DATA TO BE PASSED INTO THE FUNCTION 77 | ### 5. EXPLAIN THAT THE DATA THAT IS PASSED TO THE PARAMETERS IS MANIPULATED IN THE FUNCTION 78 | ### 6. EXPLAIN return, THE VALUE THAT'S RETURNED AS WELL AS TO WHERE IT'S RETURNED 79 | ### 7. CALL THE FUNCTION, PASS ARGUMENTS, DEFINE VARIABLE WITH RETURN VALUE 80 | 81 | ### 8. THIS FORMAT CAN BE USED TO DEFINE ALL THE OTHER FUNCTIONS TOO 82 | 83 | # keyword 'def' to define a function 84 | ''' 85 | # parameters are empty variables in a function's definition which await data from the function call 86 | def function_name(parameter_1, parameter_2, ...): 87 | # this code block will be run 88 | # when the function is 'called' 89 | 90 | # manipulate the parameters somehow 91 | 92 | # send the result back to where the function was called 93 | # with the keyword 'return' 94 | # if no return value is specified, a function will return 'None' by default 95 | return manipulate_parameters 96 | 97 | # call the function and save the return value in a variable 98 | data_returned_from_function = function_name(argument_1, argument_2, ...) 99 | # data passed to functions to fill parameters are called 'arguments' 100 | ''' 101 | # ----------------------------------------------------------------------------------- # 102 | 103 | # increment(number) - add one to the number and return the result 104 | 105 | def increment(number): 106 | result = number + 1 107 | return result 108 | 109 | # call the function with a value for 'number' 110 | result = increment(9) 111 | # print(result) 112 | 113 | result = increment(result) 114 | # print(result) 115 | 116 | # use the function in a loop 117 | x = 0 118 | 119 | while x < 10: 120 | # print(x) 121 | 122 | # use the function to increment x 123 | x = increment(x) 124 | 125 | # -------------------------------------------------------------------------------------- # 126 | 127 | # arguments MUST be passed to fill parameters (unless default values are provided) 128 | # increment() # TypeError: increment() missing 1 required positional argument: 'number' 129 | 130 | # ---------------------------------------------------------------------------------------- # 131 | 132 | # add(a, b) - return the sum of two numbers, 'a' and 'b' 133 | 134 | def add(a=1, b=1): 135 | return a + b 136 | 137 | # if NO default values are provided for parameters: 138 | # add() # TypeError: add() missing 2 required positional arguments: 'a' and 'b' 139 | # add(9) # TypeError: add() missing 1 required positional argument: 'b' 140 | # print(add(9, 1)) # 10 - a=9, b=1 141 | 142 | # if default values ARE provided for parameters 143 | # print(add(10)) # 11 - (a=10, b=default) 144 | # print(add()) # 2 - (a=default, b=default) 145 | # print(add(5, 2)) # 7 - (a=5, b=2) 146 | # print(add(b=7)) # 8 - (a=default, b=7) 147 | # print(add(b=7, a=5)) # 12 - (a=5, b=7) 148 | 149 | # ------------------------------------------------------------------------------------- # 150 | 151 | # 'shred' a string and return a randomized list of its characters 152 | 153 | def shred_string(string): 154 | # convert the string to a list of its characters 155 | characters = list(string) 156 | 157 | # randomize the list 158 | random.shuffle(characters) 159 | 160 | return characters 161 | 162 | 163 | 164 | shredded = shred_string('hello world') 165 | # print(shredded) 166 | 167 | shredded = shred_string('ABCDEFG') 168 | # print(shredded) 169 | 170 | # -------------------------------------------------------------------------------------- # 171 | 172 | # generate a list of 'k' integers between 'low' and 'high' 173 | 174 | def generate_random_numbers(k, low=0, high=100): 175 | # create a blank list to store the numbers 176 | numbers = [] 177 | 178 | # loop 'k' times 179 | for x in range(k): 180 | # generate a random number between 'low' and 'high' 181 | random_number = random.randint(low, high) 182 | 183 | # add the number to the list 184 | numbers.append(random_number) 185 | 186 | return numbers 187 | 188 | 189 | random_numbers = generate_random_numbers(10) 190 | # print(random_numbers) # [80, 94, 71, 99, 3, 48, 74, 29, 41, 12] 191 | 192 | random_numbers = generate_random_numbers(3, 10, 20) 193 | # print(random_numbers) # [15, 17, 17] 194 | 195 | random_numbers = generate_random_numbers(1000, -100, 100) 196 | # print(random_numbers) 197 | 198 | -------------------------------------------------------------------------------- /practice/unit_2/solutions/exercise_4_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 2 Practice Solutions 2 | 3 | ## **Exercise 4 - Calculator** 4 | 5 | ### **4.1** 6 | 7 | ```python 8 | def add(a, b): 9 | '''return the sum of two numbers, a and b''' 10 | return a + b 11 | 12 | def subtract(a, b): 13 | '''return the difference of two numbers, a and b''' 14 | return a - b 15 | 16 | 17 | while True: 18 | # ask the user for the operation 19 | operation = input("Enter the operation you would like to perform or 'done' to quit: ") 20 | 21 | # check if the user would like to quit 22 | if operation == 'done': 23 | print('Goodbye!') 24 | break # end the REPL 25 | 26 | # get the operands from the user 27 | operand_1 = input('Enter the first operand: ') 28 | operand_2 = input('Enter the second operand: ') 29 | 30 | # convert strings to floats 31 | operand_1 = float(operand_1) 32 | operand_2 = float(operand_2) 33 | 34 | # check the operation and call appropriate function 35 | if operation == '+': 36 | result = add(operand_1, operand_2) 37 | elif operation == '-': 38 | result = subtract(operand_1, operand_2) 39 | 40 | # display the result 41 | print(f'{operand_1} {operation} {operand_2} = {result}') 42 | ``` 43 | --- 44 | 45 | ### **2.2** 46 | 47 | ```python 48 | 49 | # add these two functions 50 | def multiply(a, b): 51 | '''return the product of two numbers, a and b''' 52 | return a * b 53 | 54 | def divide(a, b): 55 | '''return the quotient of two numbers, a and b''' 56 | return a / b 57 | 58 | # ---------------------------------------------------- # 59 | 60 | # add checks for multiplication and division 61 | if operation == '+': 62 | result = add(operand_1, operand_2) 63 | elif operation == '-': 64 | result = subtract(operand_1, operand_2) 65 | elif operation == '*': 66 | result = multiply(operand_1, operand_2) 67 | elif operation == '/': 68 | result = divide(operand_1, operand_2) 69 | 70 | ``` 71 | 72 | --- 73 | ### **2.3** 74 | ```python 75 | def add(a, b): 76 | '''return the sum of two numbers, a and b''' 77 | return a + b 78 | 79 | def subtract(a, b): 80 | '''return the difference of two numbers, a and b''' 81 | return a - b 82 | 83 | def multiply(a, b): 84 | '''return the product of two numbers, a and b''' 85 | return a * b 86 | 87 | def divide(a, b): 88 | '''return the quotient of two numbers, a and b''' 89 | return a / b 90 | 91 | # initialize the running total to None 92 | total = None 93 | 94 | while True: 95 | # ask the user for the operation 96 | operation = input("\n\nEnter the operation you would like to perform or 'done' to quit: ") 97 | 98 | # check if the user would like to quit 99 | if operation == 'done': 100 | # print final total 101 | print(f'\nYour final total was: {total}') 102 | 103 | print('\nGoodbye!') 104 | break # end the REPL 105 | 106 | # if total still contains the value None, get both operands from the user 107 | # note: this will only be True on the first loop 108 | if not total: 109 | # get the operands from the user 110 | operand_1 = input('Enter the first operand: ') 111 | operand_2 = input('Enter the second operand: ') 112 | 113 | else: 114 | # if the total is already defined, set it as the first operand and get the other operand from the user 115 | operand_1 = total 116 | operand_2 = input(f'\n{total} {operation} x:\n\nEnter x: ') 117 | 118 | # convert strings to floats 119 | operand_1 = float(operand_1) 120 | operand_2 = float(operand_2) 121 | 122 | # check the operation and call appropriate function 123 | if operation == '+': 124 | total = add(operand_1, operand_2) 125 | 126 | elif operation == '-': 127 | total = subtract(operand_1, operand_2) 128 | 129 | elif operation == '*': 130 | total = multiply(operand_1, operand_2) 131 | 132 | elif operation == '/': 133 | total = divide(operand_1, operand_2) 134 | 135 | # display the result 136 | print(f'\n{operand_1} {operation} {operand_2} = {total}') 137 | ``` 138 | 139 | --- 140 | ### **2.4** 141 | ```python 142 | def add(a, b): 143 | '''return the sum of two numbers, a and b''' 144 | return a + b 145 | 146 | def subtract(a, b): 147 | '''return the difference of two numbers, a and b''' 148 | return a - b 149 | 150 | def multiply(a, b): 151 | '''return the product of two numbers, a and b''' 152 | return a * b 153 | 154 | def divide(a, b): 155 | '''return the quotient of two numbers, a and b''' 156 | return a / b 157 | 158 | # dictionary of operators as keys and their respective functions as values 159 | operations = { 160 | '+': add, 161 | '-': subtract, 162 | '*': multiply, 163 | '/': divide 164 | } 165 | 166 | # begin running total 167 | total = None 168 | 169 | while True: 170 | # ask the user for the operation 171 | operator = input("\nEnter the operation you would like to perform or 'done' to quit: ") 172 | 173 | # check if the user would like to quit 174 | if operator == 'done': 175 | # print final total 176 | print(f'\nYour final total was: {total}') 177 | 178 | print('\nGoodbye!') 179 | break # end the REPL 180 | 181 | # if total still contains the value None 182 | # note: this will only be True on the first loop 183 | if not total: 184 | # get the operands from the user 185 | operand_1 = input('Enter the first operand: ') 186 | operand_2 = input('Enter the second operand: ') 187 | 188 | else: 189 | # if the total is already defined, set it as the first operand 190 | operand_1 = total 191 | operand_2 = input(f'\n{total} {operator} x:\n\nEnter x: ') 192 | 193 | # convert strings to floats 194 | operand_1 = float(operand_1) 195 | operand_2 = float(operand_2) 196 | 197 | # retrieve the function at the key of the chosen operator 198 | operation = operations[operator] 199 | 200 | # perform the calculation on the total 201 | total = operation(operand_1, operand_2) 202 | 203 | 204 | # display the result 205 | print(f'{operand_1} {operator} {operand_2} = {total}') 206 | ``` 207 | --- 208 | Keep in mind that this is just one potential solution. 209 | 210 | --- 211 | 212 | ## [< Exercise 3](../exercise_3.md) 213 | 214 | ### [<< Back to Unit 2 Practice](/practice/unit_2/) 215 | -------------------------------------------------------------------------------- /resources/example_lessons/unit_4/unit_3_review.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit 3 Review 3 | ''' 4 | 5 | # dictionaries are defined using curly brackets 6 | # key:value pairs are separated with commas 7 | 8 | blank_dictionary = {} 9 | 10 | todo = { 11 | # key: value, 12 | 'title': 'Go grocery shopping', 13 | 'completed': False 14 | } 15 | 16 | # dict keys are usually strings 17 | # dict values can be ANY datatype, including other dicts 18 | 19 | # ---------------------------------------------------------------------------------- # 20 | 21 | # when accessing values with keys, 22 | # the keys go in SQUARE brackets 23 | title = todo['title'] 24 | # print(title) # Go grocery shopping 25 | 26 | # integers in square brackets generally mean lists 27 | # string in square brackets generally mean dictionaries 28 | 29 | # --------------------------------------------------------------------------------- # 30 | 31 | # cannot access a value at a non-existant key 32 | # todo['id'] # KeyError: 'id' 33 | 34 | # values can be added to keys that don't yet exist 35 | todo['id'] = 1 36 | # print(todo) # 'title': 'Go grocery shopping', 'completed': False, 'id': 1} 37 | 38 | # change the value at a key 39 | # the to do has been finished 40 | todo['completed'] = True 41 | # print(todo) # {'title': 'Go grocery shopping', 'completed': True, 'id': 1} 42 | 43 | # ----------------------------------------------------------------------------- # 44 | 45 | # .pop(key) delete the key:value pair at the key and return it 46 | todo_id = todo.pop('id') 47 | # print(todo_id, todo) # 1 {'title': 'Go grocery shopping', 'completed': True} 48 | 49 | 50 | # alternative to the .get() method: 51 | key = 'title' 52 | default = f"'{key}' is not a valid key in the dictionary." 53 | 54 | # check if the key is in the dictionary before using it 55 | if key in todo.keys(): 56 | value = todo[key] 57 | 58 | else: 59 | value = default 60 | 61 | # print(value) 62 | 63 | # .get(key, default) - return the value at the key if it exists or the default if it doesn't 64 | 65 | key = 'id' 66 | default = f"'{key}' is not a valid key in the dictionary." 67 | 68 | value = todo.get(key, default) 69 | # print(value) # 'id' is not a valid key in the dictionary. 70 | 71 | # --------------------------------------------------------- # 72 | 73 | key = 'title' 74 | default = f"'{key}' is not a valid key in the dictionary." 75 | 76 | value = todo.get(key, default) 77 | # print(value) # Go grocery shopping 78 | 79 | # ------------------------------------------------------------------------- # 80 | 81 | #.update(new_dictionary) add the new_dictionary to the original 82 | 83 | todo.update({ 84 | 'id': 1, 85 | 'user': 'KG' 86 | }) 87 | # print(todo) # {'title': 'Go grocery shopping', 'completed': True, 'id': 1, 'user': 'KG'} 88 | 89 | # ------------------------------------- # 90 | 91 | # Display the todo item 92 | todo_display = f""" 93 | {todo['id']}. {todo['title']} 94 | Created by: {todo['user']} 95 | Completed: {todo['completed']}""" 96 | 97 | # print(todo_display) 98 | 99 | # ---------------------------------------- # 100 | 101 | # looping dictionaries 102 | # .keys(), .values(), .items() - access different parts of the a dictionary 103 | 104 | # print(todo.keys()) # dict_keys(['title', 'completed', 'id', 'user']) 105 | 106 | # loop through keys 107 | for key in todo.keys(): 108 | # get the value at the current key 109 | value = todo[key] 110 | # print(f"{key}: {value}") 111 | 112 | 113 | # -------------------------------------------------------------------------- # 114 | 115 | # .values() 116 | # print(todo.values()) # dict_values(['Go grocery shopping', True, 1, 'KG']) 117 | ''' 118 | for value in todo.values(): 119 | print(value) 120 | ''' 121 | 122 | # ----------------------------------------------------------------------- # 123 | # loop through the key:value pairs (items) 124 | 125 | # tuple - unchangeable list, uses indices but cannot accept new values 126 | # print(todo.items()) # dict_items([('title', 'Go grocery shopping'), ('completed', True), ('id', 1), ('user', 'KG')]) 127 | ''' 128 | for item in todo.items(): 129 | key = item[0] 130 | value = item[1] 131 | print(f"{key}: {value}") 132 | 133 | ''' 134 | # -------------------------------------------------------- # 135 | 136 | # 'in' to check if a key is in the dictionary 137 | # print('title' in todo.keys()) 138 | # print('completed' in todo) # .keys() is optional 139 | 140 | # -------------------------------------------------------- # 141 | 142 | # instead of multiple, individual todo item dictionaries, create a list of dictionaries instead 143 | todo_1 = {'title': 'Go grocery shopping', 'completed': False, 'id': 1} 144 | todo_2 = {'title': 'Water the garden', 'completed': True, 'id': 2} 145 | todo_3 = {'title': 'Master Python dictionaries', 'completed': False, 'id': 3} 146 | 147 | 148 | # list of dictionaries 149 | todo_list = [ 150 | {'title': 'Go grocery shopping', 'completed': False, 'id': 1}, 151 | {'title': 'Water the garden', 'completed': True, 'id': 2}, 152 | {'title': 'Master Python dictionaries', 'completed': False, 'id': 3} 153 | ] 154 | 155 | # list of dictionaries organized vertically 156 | todo_list = [ 157 | { 158 | 'title': 'Go grocery shopping', 159 | 'completed': False, 160 | 'id': 1 161 | }, 162 | { 163 | 'title': 'Water the garden', 164 | 'completed': True, 165 | 'id': 2 166 | }, 167 | { 168 | 'title': 'Master Python dictionaries', 169 | 'completed': False, 170 | 'id': 3 171 | } 172 | ] 173 | 174 | # pull out one dictionary at a time from the list 175 | # print(todo_list[0]) # {'title': 'Go grocery shopping', 'completed': False, 'id': 1} 176 | # print(todo_list[0]['title']) # Go grocery shopping 177 | 178 | # loop through the todo_list 179 | for todo in todo_list: 180 | # if todo['completed'] == False: 181 | if not todo['completed']: # same as line 168 182 | todo_display = f""" 183 | {todo['id']}. {todo['title']} 184 | Completed: {todo['completed']}""" 185 | 186 | # print(todo_display) 187 | 188 | # ------------------------------------------------------------ # 189 | 190 | # nested dictionaries 191 | 192 | fruit_prices = { 193 | 'apple': { 194 | 'green': 2.12, 195 | 'yellow': 3.13, 196 | 'red': { 197 | 'price': 4.14, 198 | 'inventory': 100 199 | } 200 | }, 201 | 'grape': 3.13 202 | } 203 | 204 | # print(fruit_prices['apple']) # {'green': 2.12, 'yellow': 3.13, 'red': 4.14} 205 | 206 | apple_prices = fruit_prices['apple'] 207 | # print(apple_prices['green']) # 2.12 208 | 209 | # print(fruit_prices['apple']['green']) # 2.12 210 | 211 | # print(fruit_prices['apple']['red']) # {'price': 4.14, 'inventory': 100} 212 | # print(fruit_prices['apple']['red']['price']) # 4.14 213 | -------------------------------------------------------------------------------- /practice/unit_4/solutions/exercise_2/exercise_2_3_solution.md: -------------------------------------------------------------------------------- 1 | # Unit 4 Practice Solutions 2 | 3 | ## **Exercise 2 Solution** 4 | 5 | ### **2.3** 6 | 7 |
8 | 9 |
10 | 11 |

12 | 13 | In this version, we're going to allow the active player to choose if they want to attack or defend each round. If they choose to defend, the next damage they receive will be reduced based on their `defense` stat. 14 | 15 | We'll be introducing two more functions, `set_stance()` and `defend()`. 16 | 17 | ### `set_stance()` 18 | 19 | This function will contain a REPL which will allow the user to choose which stance the active character should take this round. The function will take in the user's input, set the active character's stance stat and return the updated character dictionary. 20 | 21 | ### `defend()` 22 | 23 | This function will take in the opponent's stat dictionary and the amount of incoming damage from the active player's `attack` stat, reduce the incoming damage based on the opponent's `defense` stat and return the reduced damage amount. 24 | 25 | ```python 26 | 27 | # ----------------------------------------------------------- # 28 | # Setup 29 | # ----------------------------------------------------------- # 30 | hero = { 31 | "name": "Andromeda", 32 | "hp": 100, 33 | "attack": 7, 34 | "defense": 6, 35 | "stance": "" # 'attack' or 'defend' 36 | } 37 | 38 | villain = { 39 | "name": "Helios", 40 | "hp": 100, 41 | "attack": 5, 42 | "defense": 5, 43 | "stance": "" # 'attack' or 'defend' 44 | } 45 | 46 | 47 | def is_defeated(character): 48 | ''' 49 | Returns False if the character's hp is greater than zero 50 | Returns True if the character's hp is less than or equal to 51 | ''' 52 | return character['hp'] <= 0 53 | 54 | 55 | def set_stance(character): 56 | ''' 57 | Set the character's stance stat with user 58 | input and return the updated dictionary 59 | ''' 60 | 61 | stance_options = { 62 | '1': 'attack', 63 | '2': 'defend' 64 | } 65 | 66 | prompt = f""" 67 | {character['name']}, how would you like to proceed? 68 | 69 | 1. Attack 70 | 2. Defend 71 | 72 | Enter the number of the option 73 | > """ 74 | 75 | stance_number = input(prompt) 76 | 77 | # make sure the user entered a valid selection 78 | while stance_number not in stance_options.keys(): 79 | print('\n!***! Invalid selection !***!') 80 | stance_number = input(prompt) 81 | 82 | # Once the user has entered a valid selection, set the dictionary- 83 | character['stance'] = stance_options[stance_number] 84 | 85 | return character 86 | 87 | 88 | def defend(character, incoming_damage): 89 | ''' 90 | Calculate the amount the incoming_damage will be reduced 91 | based on the character's 'defense' stat. 92 | 93 | Return the amount the incoming_damage will be reduced 94 | in a variable called 'damage_reduction' 95 | 96 | 0 - 4 = 10%, 5 - 7 = 33%, 8 - 10 = 66% 97 | ''' 98 | defense = character['defense'] 99 | if defense < 5: 100 | damage_reduction = incoming_damage * .1 101 | elif defense < 8: 102 | damage_reduction = incoming_damage * .33 103 | else: 104 | damage_reduction = incoming_damage * .66 105 | 106 | # return the reduction amount, rounded to the nearest integer 107 | return round(damage_reduction) 108 | 109 | 110 | def attack(active, opponent): 111 | ''' 112 | Apply battle damage to the opponent using the attacker's attack stat 113 | If the opponent is defeated, return True, signifying the battle is over 114 | Otherwise return False, signifying the battle will continue for another round 115 | ''' 116 | battle_over = False 117 | 118 | print("\n" + ("-" * 50)) # print a divider 119 | 120 | # display hp 121 | print(f"\n{active['name']} has {active['hp']} hp!") 122 | print(f"{opponent['name']} has {opponent['hp']} hp!") 123 | 124 | input("\nPress enter to battle!") 125 | 126 | 127 | # active character chooses stance 128 | active = set_stance(active) 129 | 130 | print("\n" + ("-" * 50)) # print a divider 131 | 132 | if active['stance'] == 'attack': 133 | # active character attacks 134 | print(f"\n{active['name']} attacks!") 135 | 136 | # damage to be dealt to the opponent 137 | damage = active['attack'] * 5 # multiply damage to speed up the game 138 | 139 | # if the opponent chose to defend last turn 140 | if opponent['stance'] == 'defend': 141 | # calculate the damage reduction 142 | damage_reduction = defend(opponent, damage) 143 | 144 | # reduce damage 145 | damage -= damage_reduction 146 | 147 | print(f"\n{opponent['name']} defends! Damage reduced by {damage_reduction}!") 148 | 149 | # subtract attackers's attack strength from the opponents's hp 150 | opponent['hp'] -= damage 151 | 152 | print(f"{opponent['name']} takes {damage} damage!") 153 | 154 | elif active['stance'] == 'defend': 155 | print(f"\n{active['name']}, the next damage you receive will be reduced!") 156 | 157 | # return True if the opponent is defeated, otherwise False 158 | return is_defeated(opponent) 159 | 160 | 161 | 162 | 163 | # ----------------------------------------------------------- # 164 | # Battle! 165 | # ----------------------------------------------------------- # 166 | 167 | # this will alternate between 0 and 1 to decide whose turn it is 168 | turn_counter = 0 169 | 170 | while True: 171 | 172 | # stat dictionaries stored at matching keys 173 | all_stats = { 174 | 'hero': hero, 175 | 'villain': villain 176 | } 177 | 178 | # keys for the all_stats dictionary 179 | # the turn_counter will alternate between 0 and 1 to decide whose turn it is 180 | stat_keys = list(all_stats.keys()) # ['hero', 'villain'] 181 | 182 | # get the key of the active player 183 | active_key = stat_keys[turn_counter] 184 | # get the stat dictionary of the active player 185 | active = all_stats[active_key] 186 | 187 | 188 | # get the key of the current opponent 189 | # index -1 if turn_counter is 0 190 | # index 0 if the turn_counter is 1 191 | opponent_key = stat_keys[turn_counter - 1] 192 | # get the stat dictionary of the opponent 193 | opponent = all_stats[opponent_key] 194 | 195 | # execute current round of battle 196 | # receive True if opponent is defeated, otherwise False 197 | victorious = attack(active, opponent) 198 | 199 | # check the outcome of the battle. 200 | # if the opponent was defeated, end the loop 201 | if victorious: 202 | print(f"\n{opponent['name']} has been defeated! {active['name']} is victorious!") 203 | break # end the loop 204 | 205 | ``` 206 | 207 | 208 | 209 | 210 | Keep in mind that this is just one potential solution. 211 | 212 | ## [< 2.2 Solution](./exercise_2_2_solution.md) 213 | --- 214 | 215 | ### [<< Back to Unit 4 Practice](/practice/unit_4/) 216 | -------------------------------------------------------------------------------- /resources/lessons/lesson_3_review: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit 3 Review 3 | ''' 4 | 5 | # dictionaries are defined using curly brackets 6 | # key:value pairs are separated with commas 7 | 8 | blank_dictionary = {} 9 | 10 | 11 | todo = { 12 | # key:value 13 | 'title':'Go grocery shopping', 14 | 'completed': False 15 | } 16 | 17 | 18 | # dict keys are usually strings 19 | # dict values can be ANY datatype, including other dicts 20 | 21 | # ---------------------------------------------------------------------------------- # 22 | 23 | # when accessing values with keys, 24 | # the keys go in SQUARE brackets 25 | 26 | title = todo['title'] 27 | # print(title) # Go grocery shopping 28 | 29 | # integers in square brackets generally mean lists 30 | # string in square brackets generally mean dictionaries 31 | 32 | # --------------------------------------------------------------------------------- # 33 | 34 | # cannot access a value at a non-existant key 35 | 36 | # todo['id'] # KeyError: 'id' 37 | 38 | # values can be added to keys that don't yet exist 39 | 40 | todo['id'] = 1 41 | 42 | # print(todo) # {'title': 'Go grocery shopping', 'completed': False, 'id': 1} 43 | 44 | # change the value at a key 45 | # the todo has been finished 46 | 47 | todo['completed'] = True 48 | # print(todo) {'title': 'Go grocery shopping', 'completed': True, 'id': 1} 49 | 50 | # ----------------------------------------------------------------------------- # 51 | '''Dictionary Methods''' 52 | 53 | # .pop(key) delete the key:value pair at the key and return the value 54 | 55 | todo_id = todo.pop('id') 56 | # print(todo_id, todo) # 1 {'title': 'Go grocery shopping', 'completed': True} 57 | 58 | # ----------------------------------------------------------------------------- # 59 | 60 | # alternative to the .get() method: 61 | 62 | key = 'title' 63 | 64 | default = f"'{key}' is not a valid key in the dictionary." 65 | 66 | # check if the key is in the dictionary before using it 67 | 68 | if key in todo.keys(): 69 | value = todo[key] 70 | 71 | else: 72 | value = default 73 | 74 | # print(value) 75 | 76 | # .get(key, default) - return the value at the key if it exists or the default if it doesn't 77 | 78 | key = 'id' 79 | default = f"'{key} is not a valid key in the dictionary." 80 | 81 | value = todo.get(key, default) 82 | # print(value) # 'id' is not a valid key in the dictionary. 83 | 84 | # ------------------------------------------------------------------------- # 85 | 86 | # .update(new_dictionary) add the new_dictionary to the original 87 | 88 | 89 | todo.update({ 90 | 'id':1, 91 | 'user': 'JJ' 92 | }) 93 | 94 | # print(todo) {'title': 'Go grocery shopping', 'completed': True, 'id': 1, 'user': 'JJ'} 95 | # ------------------------------------- # 96 | 97 | # Display the todo item 98 | 99 | todo_display = f""" 100 | {todo['id']}. {todo['title']} 101 | Created by: {todo['user']} 102 | Completed: {todo['completed']}""" 103 | 104 | # print(todo_display) 105 | # ---------------------------------------- # 106 | # looping dictionaries 107 | # .keys(), .values(), .items() - access different parts of the a dictionary 108 | 109 | # print(todo.keys()) dict_keys(['title', 'completed', 'id', 'user']) 110 | 111 | 112 | # -------------------------------------------------------------------------- # 113 | 114 | # .keys() - access a dictionary's values 115 | 116 | # loop through keys 117 | 118 | for key in todo.keys(): 119 | # get the value at the current key 120 | value = todo[key] 121 | 122 | # print(f'{key}: {value}') 123 | 124 | # -------------------------------------------------------------------------- # 125 | 126 | # .values() - access a dictionary's values 127 | # print(todo.values()) # dict_values(['Go grocery shopping', True, 1, 'JJ']) 128 | 129 | ''' 130 | for value in todo.values(): 131 | print(value) 132 | ''' 133 | # ----------------------------------------------------------------------- # 134 | # loop through the key:value pairs (items) 135 | 136 | # tuple - unchangeable list, uses indices but cannot accept new values 137 | 138 | # print(todo.items()) # dict_items([('title', 'Go grocery shopping'), ('completed', True), ('id', 1), ('user', 'JJ')]) 139 | ''' 140 | for item in todo.items(): 141 | key = item[0] 142 | value = item[1] 143 | print(f'{key}: {value}') 144 | ''' 145 | 146 | 147 | # -------------------------------------------------------- # 148 | 149 | # 'in' to check if a key is in the dictionary 150 | 151 | # print('title' in todo.keys()) 152 | # print('completed' in todo) # .keys() is optional 153 | 154 | # -------------------------------------------------------- # 155 | 156 | # instead of multiple, individual todo item dictionaries, create a list of dictionaries instead 157 | 158 | todo_1 = {'title': 'Go grocery shopping', 'completed': False, 'id': 1} 159 | todo_2 = {'title': 'Water the garden', 'completed': True, 'id': 2} 160 | todo_3 = {'title': 'Master Python dictionaries', 'completed': False, 'id': 3} 161 | 162 | # list of dictionaries. List is organized vertically, dictionaries organized horizontally. 163 | 164 | todo_list = [ 165 | 166 | {'title': 'Go grocery shopping', 'completed': False, 'id': 1}, 167 | {'title': 'Water the garden', 'completed': True, 'id': 2}, 168 | {'title': 'Master Python dictionaries', 'completed': False, 'id': 3}, 169 | 170 | ] 171 | 172 | # list of dictionaries organized vertically 173 | todo_list = [ 174 | 175 | { 176 | 'title': 'Go grocery shopping', 177 | 'completed': False, 178 | 'id': 1 179 | }, 180 | { 181 | 'title': 'Water the garden', 182 | 'completed': True, 183 | 'id': 2 184 | }, 185 | { 186 | 'title': 'Master Python dictionaries', 187 | 'completed': False, 188 | 'id': 3 189 | } 190 | 191 | ] 192 | 193 | # pull out a single dictionary from the list using an index 194 | # print(todo_list[0]) # {'title': 'Go grocery shopping', 'completed': False, 'id': 1} 195 | 196 | # print(todo_list[0]['title']) # Go grocery shopping 197 | 198 | # loop through the todo_list 199 | 200 | for todo in todo_list: 201 | # if todo['completed'] == False 202 | if not todo['completed']: # same as line 201 203 | 204 | todo_display = f""" 205 | {todo['id']}. {todo['title']} 206 | Completed: {todo['completed']}""" 207 | 208 | # print(todo_display) 209 | 210 | 211 | # ------------------------------------------------------------ # 212 | 213 | # nested dictionaries 214 | 215 | fruit_prices = { 216 | 217 | 'apple': { 218 | 'green': 2.12, 219 | 'yellow': 3.13, 220 | 'red': { 221 | 'price': 4.14, 222 | 'inventory': 100 223 | } 224 | }, 225 | 'grape': 3.13 226 | } 227 | 228 | # print(fruit_prices['apple']) # {'green': 2.12, 'yellow': 3.13, 'red': {'price': 4.14, 'inventory': 100}} 229 | 230 | 231 | apple_prices = fruit_prices['apple'] 232 | 233 | # print(apple_prices['green']) # 2.12 234 | 235 | # print(fruit_prices['apple']['green']) # 2.12 236 | 237 | # print(fruit_prices['apple']['red']) # {'price': 4.14, 'inventory': 100} 238 | # print(fruit_prices['apple']['red']['price']) # 4.14 239 | -------------------------------------------------------------------------------- /units/unit1.md: -------------------------------------------------------------------------------- 1 | # Unit 1 - Review 2 | 3 | --- 4 | 5 | [Back to Syllabus](https://github.com/PdxCodeGuild/Programming102#top) 6 | 7 | ### Table of Contents 8 | 9 | - [Unit 1 - Review](#unit-1---review) 10 | - [Table of Contents](#table-of-contents) 11 | - [ Variables](#-variables) 12 | - [ DataTypes](#-datatypes) 13 | - [ Conditional Statements](#-conditional-statements) 14 | - [ For / While Loops](#-for--while-loops) 15 | - [while loops](#while-loops) 16 | - [for loops](#for-loops) 17 | - [ Troubleshooting](#-troubleshooting) 18 | - [ Common Error Messages](#-common-error-messages) 19 | - [Exercises](#exercises) 20 | - [Lab 1](#lab-1) 21 | 22 | --- 23 | 24 | ### Variables 25 | 26 | - Variables in python are used to reference data. They make our code more readable if used correctly. 27 | - Variables are declared when you give them a name and assign them a value `name = "Anthony"` 28 | - Keep in mind there are a few rules when choosing your variable name: 29 | - Variables names are case sensitive (name and NAME are different variables) 30 | - Must start with a letter or underscore 31 | - Can have numbers but can not start with one 32 | 33 | --- 34 | 35 | ### DataTypes 36 | 37 | | DataType | Description | Example | 38 | | -------- | ---------------------- | --------------------------------------------- | 39 | | String | Text Surrounded By "" | `string1 = "hello"` | 40 | | Integer | Whole Number | `int1 = 4` | 41 | | Float | Decimal Number | `float1 = 2.4` | 42 | | Boolean | True/False | `bool1 = True` | 43 | | List | Collection of Elements | `list1 = ["hello", "goodbye", 4, 2.4, False]` | 44 | 45 | --- 46 | 47 | ### Conditional Statements 48 | 49 | We can decide `if` we want code to run based on a true or false condtion. 50 | 51 | ```python 52 | num = 4 53 | if num > 0: 54 | print("Number is greater than zero") 55 | ``` 56 | 57 | We can also choose to run code if the previous condition was false, but the current condion is true. 58 | To do this we use `elif`: 59 | 60 | ```python 61 | num = 4 62 | if num > 0: 63 | print("Number is greater than zero") 64 | elif num == 0: 65 | print("The number is zero) 66 | ``` 67 | 68 | Finally we can use `else` to catch anything that was not caught by the previous condtions: 69 | 70 | ```python 71 | num = 4 72 | if num > 0: 73 | print("Number is greater than zero") 74 | elif num == 0: 75 | print("The number is zero") 76 | else: 77 | print("The number is less than zero") 78 | ``` 79 | 80 | --- 81 | 82 | ### For / While Loops 83 | 84 | Loops can be used to run a block of code more than once. Python has two kinds of loops, the `while` loop and the `for` loop. 85 | 86 | #### while loops 87 | 88 | `while` loops are similar to `if` statements. They run as long as the condition remains true. 89 | 90 | ```python 91 | num = 0 92 | while num < 5: 93 | print(num) 94 | num += 1 # Be sure to increment our counter, otherwise the condition would remain True forever 95 | ``` 96 | 97 | #### for loops 98 | 99 | `for` loops are slightly different. They are useful when iterating over a list: 100 | 101 | ```python 102 | colors = ["red", "blue", "green", "yello", "purple"] 103 | for color in colors: # color is a temporary variable name holding an element from colors 104 | print(color) 105 | ``` 106 | 107 | ### Troubleshooting 108 | 109 | ![troubleshooting](https://github.com/PdxCodeGuild/Programming102/blob/master/resources/troubleshooting.jpeg) 110 | 111 | ### Common Error Messages 112 | 113 | | Error | Cause | Example | 114 | | ------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- | 115 | | AttributeError | Attribute reference or assignment fails | [AttributeError](https://repl.it/@dirtTastesGood/pythonattributeerrorexample) | 116 | | ImportError | `import` statement has troubles trying to load a module | [ImportError](https://repl.it/@dirtTastesGood/pythonimporterrorexample) | 117 | | ModuleNotFoundError | `import` statement has troubles trying to load a module | [ModuleNotFoundError](https://repl.it/@dirtTastesGood/pythonmodulenotfounderrorexample) | 118 | | IndexError | sequence index is out of range | [IndexError](https://repl.it/@dirtTastesGood/pythonindexerrorexample) | 119 | | KeyError | Referenced key is not in a dictionary | [KeyError](https://repl.it/@dirtTastesGood/pythonkeyerrorexample) | 120 | | KeyboardInterrupt | Using `ctrl + c` to exit Python program | [KeyboardInterrupt](https://repl.it/@dirtTastesGood/pythonkeyboardinterruptexample) | 121 | | NameError | Variable or function name doesn't exist | [NameError](https://repl.it/@dirtTastesGood/pythonnameerrorexample) | 122 | | SyntaxError | Many causes. Incorrect Python syntax. | [SyntaxError](https://repl.it/@dirtTastesGood/pythonsyntaxerrorexample) | 123 | | IndentationError | Indendation too far left or right | [IndentationError](https://repl.it/@dirtTastesGood/pythonindentationerrorexample) | 124 | | TypeError | operation or function is applied to an object of inappropriate type. | [TypeError](https://repl.it/@dirtTastesGood/pythontypeerrorexample) | 125 | | UnboundLocalError | Variable isn't defined within the function | [UnboundLocalError](https://repl.it/@dirtTastesGood/pythonunboundlocalerrorexample) | 126 | | ValueError | an operation or function receives an argument that has the right type but an inappropriate value | [ValueError](https://repl.it/@dirtTastesGood/pythonvalueerrorexample) | 127 | | ZeroDivisionError | Dividing by zero | [ZeroDivisionError](https://repl.it/@dirtTastesGood/pythonzerodivisionerrorexample) | 128 | 129 | --- 130 | 131 | ### [Exercises](https://github.com/PdxCodeGuild/Programming102/blob/master/practice/unit_1/) 132 | 133 | ### [Lab 1](https://github.com/PdxCodeGuild/Programming102/blob/master/labs/lab1.md) 134 | 135 | [Back to top](#top) 136 | --------------------------------------------------------------------------------