├── .gitignore ├── README.md ├── lesson01 ├── hello.py └── why-learn-python.PNG ├── lesson02 └── welcome.py ├── lesson03 └── meaning.py ├── lesson04 └── data_types.py ├── lesson05 └── rps.py ├── lesson06 └── lists.py ├── lesson07 └── dictionaries.py ├── lesson08 ├── loops.py └── rps2.py ├── lesson09 └── functions.py ├── lesson10 ├── example.py ├── recursion.py └── rps3.py ├── lesson11 ├── rps4.py └── scope.py ├── lesson12 ├── closure.py └── rps5.py ├── lesson13 ├── f_strings.py └── rps6.py ├── lesson14 ├── kansas.py ├── modules.py └── rps7.py ├── lesson15 ├── hello_person.py └── rps8.py ├── lesson16 ├── arcade.py ├── guess_number.py └── rps.py ├── lesson17 └── lambda.py ├── lesson18 └── classes.py ├── lesson19 └── exceptions.py ├── lesson20 ├── bank_accounts.py └── oop_project.py ├── lesson21 ├── .gitignore ├── requirements.txt └── weather.py ├── lesson22 ├── context.txt ├── files.py ├── more_names.txt └── names.txt └── lesson23 ├── .gitignore ├── requirements.txt ├── server.py ├── static └── styles │ └── style.css ├── templates ├── city-not-found.html ├── index.html └── weather.html └── weather.py /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | __pycache__ 3 | .venv 4 | .env 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # "Python for Beginners" 2 | 3 | ### Full Course - 23 Chapters 4 | 5 | --- 6 | 7 | ### Author Links 8 | 9 | 👋 Hello, I'm Dave Gray. 10 | 11 | 👉 [My Courses](https://courses.davegray.codes/) 12 | 13 | ✅ [Check out my YouTube Channel with hundreds of tutorials](https://www.youtube.com/DaveGrayTeachesCode). 14 | 15 | 🚩 [Subscribe to my channel](https://bit.ly/3nGHmNn) 16 | 17 | ☕ [Buy Me A Coffee](https://buymeacoffee.com/DaveGray) 18 | 19 | 🚀 Follow Me: 20 | 21 | - [Twitter](https://twitter.com/yesdavidgray) 22 | - [LinkedIn](https://www.linkedin.com/in/davidagray/) 23 | - [Blog](https://yesdavidgray.com) 24 | - [Reddit](https://www.reddit.com/user/DaveOnEleven) 25 | 26 | --- 27 | 28 | ### Description 29 | 30 | 📺 [YouTube Playlist](https://bit.ly/dg-beginners-python) for this repository. 31 | 32 | 🚀 This repository shares ALL of the resources referenced during the Python for Beginners tutorial series. 33 | 34 | --- 35 | 36 | ### 🎓 Academic Honesty 37 | 38 | **DO NOT COPY FOR AN ASSIGNMENT** - Avoid plagiarism and adhere to the spirit of this [Academic Honesty Policy](https://www.freecodecamp.org/news/academic-honesty-policy/). 39 | 40 | --- 41 | 42 | ### ⚙ Free Python Tools 43 | - 🔗 [Python](https://www.python.org/) 44 | - 🔗 [Visual Studio Code (aka VS Code)](https://code.visualstudio.com/) 45 | - 🔗 [Python VS Code Extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) 46 | 47 | ### 📚 References 48 | - 🔗 [Python Official Site](https://www.python.org/) 49 | - 🔗 [Python Standard Library](https://docs.python.org/3/library/index.html) 50 | - 🔗 [Python Package Index](https://pypi.org/) 51 | - 🔗 [Python string methods](https://docs.python.org/3/library/stdtypes.html#textseq) 52 | - 🔗 [Python math module](https://docs.python.org/3/library/math.html) 53 | - 🔗 [Python random module](https://docs.python.org/3/library/random.html) 54 | - 🔗 [Python argparse module](https://docs.python.org/3/library/argparse.html) 55 | - 🔗 [Flask](https://flask.palletsprojects.com/) 56 | - 🔗 [OpenWeatherMap API](https://openweathermap.org/) 57 | 58 | --- 59 | 60 | ### 💻 Source Code 61 | 62 | - 🔗 [Chapter 1 - Introduction & Setup](https://github.com/gitdagray/python-course/tree/main/lesson01) 63 | - 🔗 [Chapter 2 - Python Basics](https://github.com/gitdagray/python-course/tree/main/lesson02) 64 | - 🔗 [Chapter 3 - Python Operators](https://github.com/gitdagray/python-course/tree/main/lesson03) 65 | - 🔗 [Chapter 4 - Basic Data Types](https://github.com/gitdagray/python-course/tree/main/lesson04) 66 | - 🔗 [Chapter 5 - User Input & Control Flow](https://github.com/gitdagray/python-course/tree/main/lesson05) 67 | - 🔗 [Chapter 6 - Lists & Tuples](https://github.com/gitdagray/python-course/tree/main/lesson06) 68 | - 🔗 [Chapter 7 - Dictionaries & Sets](https://github.com/gitdagray/python-course/tree/main/lesson07) 69 | - 🔗 [Chapter 8 - While Loops & For Loops](https://github.com/gitdagray/python-course/tree/main/lesson08) 70 | - 🔗 [Chapter 9 - Functions](https://github.com/gitdagray/python-course/tree/main/lesson09) 71 | - 🔗 [Chapter 10 - Recursion](https://github.com/gitdagray/python-course/tree/main/lesson10) 72 | - 🔗 [Chapter 11 - Scope](https://github.com/gitdagray/python-course/tree/main/lesson11) 73 | - 🔗 [Chapter 12 - Closures](https://github.com/gitdagray/python-course/tree/main/lesson12) 74 | - 🔗 [Chapter 13 - f-Strings](https://github.com/gitdagray/python-course/tree/main/lesson13) 75 | - 🔗 [Chapter 14 - Modules](https://github.com/gitdagray/python-course/tree/main/lesson14) 76 | - 🔗 [Chapter 15 - Command Line Arguments](https://github.com/gitdagray/python-course/tree/main/lesson15) 77 | - 🔗 [Chapter 16 - Student Challenge](https://github.com/gitdagray/python-course/tree/main/lesson16) 78 | - 🔗 [Chapter 17 - Lambda & Higher Order Functions](https://github.com/gitdagray/python-course/tree/main/lesson17) 79 | - 🔗 [Chapter 18 - Classes, Objects, Inheritance & Polymorphism](https://github.com/gitdagray/python-course/tree/main/lesson18) 80 | - 🔗 [Chapter 19 - Errors & Exception Handling](https://github.com/gitdagray/python-course/tree/main/lesson19) 81 | - 🔗 [Chapter 20 - OOP Practice Project](https://github.com/gitdagray/python-course/tree/main/lesson20) 82 | - 🔗 [Chapter 21 - Virtual Environments & PIP](https://github.com/gitdagray/python-course/tree/main/lesson21) 83 | - 🔗 [Chapter 22 - Working With Files](https://github.com/gitdagray/python-course/tree/main/lesson22) 84 | - 🔗 [Chapter 23 - Final Project: Python Web App with Flask](https://github.com/gitdagray/python-course/tree/main/lesson23) 85 | -------------------------------------------------------------------------------- /lesson01/hello.py: -------------------------------------------------------------------------------- 1 | greeting = 'Hello World!' 2 | print(greeting) 3 | -------------------------------------------------------------------------------- /lesson01/why-learn-python.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitdagray/python-course/509f657240e1af1ae04956e593628025cae5f957/lesson01/why-learn-python.PNG -------------------------------------------------------------------------------- /lesson02/welcome.py: -------------------------------------------------------------------------------- 1 | line01 = "********************" # header / footer 2 | line02 = "* *" # re-use 3 | line03 = "* WELCOME! *" 4 | 5 | 6 | # starts with a blank line 7 | print('') 8 | print(line01) 9 | print(line02) 10 | print(line03) 11 | print(line02) 12 | print(line01) 13 | -------------------------------------------------------------------------------- /lesson03/meaning.py: -------------------------------------------------------------------------------- 1 | meaning = 42 2 | print('') 3 | 4 | # if meaning > 10: 5 | # print('Right on!') 6 | # else: 7 | # print('Not today') 8 | 9 | # Ternary Operator 10 | print('Right on!') if meaning > 10 else print('Not today') 11 | -------------------------------------------------------------------------------- /lesson04/data_types.py: -------------------------------------------------------------------------------- 1 | import math 2 | # String data type 3 | 4 | # literal assignment 5 | 6 | first = "Dave" 7 | last = "Gray" 8 | 9 | # print(type(first)) 10 | # print(type(first) == str) 11 | # print(isinstance(first, str)) 12 | 13 | # constructor function 14 | # pizza = str("Pepperoni") 15 | # print(type(pizza)) 16 | # print(type(pizza) == str) 17 | # print(isinstance(pizza, str)) 18 | 19 | # Concatenation 20 | fullname = first + " " + last 21 | print(fullname) 22 | 23 | fullname += "!" 24 | print(fullname) 25 | 26 | # Casting a number to a string 27 | decade = str(1980) 28 | print(type(decade)) 29 | print(decade) 30 | 31 | statement = "I like rock music from the " + decade + "s." 32 | print(statement) 33 | 34 | # Multiple lines 35 | multiline = ''' 36 | Hey, how are you? 37 | 38 | I was just checking in. 39 | All good? 40 | 41 | ''' 42 | print(multiline) 43 | 44 | # Escaping special characters 45 | sentence = 'I\'m back at work!\tHey!\n\nWhere\'s this at\\located?' 46 | print(sentence) 47 | 48 | # String Methods 49 | 50 | print(first) 51 | print(first.lower()) 52 | print(first.upper()) 53 | print(first) 54 | 55 | print(multiline.title()) 56 | print(multiline.replace("good", "ok")) 57 | print(multiline) 58 | 59 | print(len(multiline)) 60 | multiline += " " 61 | multiline = " " + multiline 62 | print(len(multiline)) 63 | 64 | print(len(multiline.strip())) 65 | print(len(multiline.lstrip())) 66 | print(len(multiline.rstrip())) 67 | 68 | print("") 69 | 70 | # Build a menu 71 | title = "menu".upper() 72 | print(title.center(20, "=")) 73 | print("Coffee".ljust(16, ".") + "$1".rjust(4)) 74 | print("Muffin".ljust(16, ".") + "$2".rjust(4)) 75 | print("Cheesecake".ljust(16, ".") + "$4".rjust(4)) 76 | 77 | print("") 78 | 79 | # string index values 80 | print(first[1]) 81 | print(first[-1]) 82 | print(first[1:-1]) 83 | print(first[1:]) 84 | 85 | # Some methods return boolean data 86 | print(first.startswith("D")) 87 | print(first.endswith("Z")) 88 | 89 | 90 | # Boolean data type 91 | myvalue = True 92 | x = bool(False) 93 | print(type(x)) 94 | print(isinstance(myvalue, bool)) 95 | 96 | # Numeric data types 97 | 98 | # integer type 99 | price = 100 100 | best_price = int(80) 101 | print(type(price)) 102 | print(isinstance(best_price, int)) 103 | 104 | # float type 105 | gpa = 3.28 106 | y = float(1.14) 107 | print(type(gpa)) 108 | 109 | # complex type 110 | comp_value = 5+3j 111 | print(type(comp_value)) 112 | print(comp_value.real) 113 | print(comp_value.imag) 114 | 115 | # Built-in functions for numbers 116 | 117 | print(abs(gpa)) 118 | print(abs(gpa * -1)) 119 | 120 | print(round(gpa)) 121 | 122 | print(round(gpa, 1)) 123 | 124 | 125 | print(math.pi) 126 | print(math.sqrt(64)) 127 | print(math.ceil(gpa)) 128 | print(math.floor(gpa)) 129 | 130 | # Casting a string to a number 131 | zipcode = "10001" 132 | zip_value = int(zipcode) 133 | print(type(zip_value)) 134 | 135 | # Error if you attempt to cast incorrect data 136 | # zip_value = int("New York") 137 | -------------------------------------------------------------------------------- /lesson05/rps.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | class RPS(Enum): 7 | ROCK = 1 8 | PAPER = 2 9 | SCISSORS = 3 10 | 11 | 12 | print("") 13 | playerchoice = input( 14 | "Enter...\n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 15 | 16 | player = int(playerchoice) 17 | 18 | if player < 1 or player > 3: 19 | sys.exit("You must enter 1, 2, or 3.") 20 | 21 | computerchoice = random.choice("123") 22 | 23 | computer = int(computerchoice) 24 | 25 | print("") 26 | print("You chose " + str(RPS(player)).replace('RPS.', '') + ".") 27 | print("Python chose " + str(RPS(computer)).replace('RPS.', '') + ".") 28 | print("") 29 | 30 | if player == 1 and computer == 3: 31 | print("🎉 You win!") 32 | elif player == 2 and computer == 1: 33 | print("🎉 You win!") 34 | elif player == 3 and computer == 2: 35 | print("🎉 You win!") 36 | elif player == computer: 37 | print("😲 Tie game!") 38 | else: 39 | print("🐍 Python wins!") 40 | -------------------------------------------------------------------------------- /lesson06/lists.py: -------------------------------------------------------------------------------- 1 | users = ['Dave', 'John', 'Sara'] 2 | 3 | data = ['Dave', 42, True] 4 | 5 | emptylist = [] 6 | 7 | print("Dave" in emptylist) 8 | 9 | print(users[0]) 10 | print(users[-2]) 11 | 12 | print(users.index('Sara')) 13 | 14 | print(users[0:2]) 15 | print(users[1:]) 16 | print(users[-3:-1]) 17 | 18 | print(len(data)) 19 | 20 | users.append('Elsa') 21 | print(users) 22 | 23 | users += ['Jason'] 24 | print(users) 25 | 26 | users.extend(['Robert', 'Jimmy']) 27 | print(users) 28 | 29 | # users.extend(data) 30 | # print(users) 31 | 32 | users.insert(0, 'Bob') 33 | print(users) 34 | 35 | users[2:2] = ['Eddie', 'Alex'] 36 | print(users) 37 | 38 | users[1:3] = ['Robert', 'JPJ'] 39 | print(users) 40 | 41 | users.remove('Bob') 42 | print(users) 43 | 44 | print(users.pop()) 45 | print(users) 46 | 47 | del users[0] 48 | print(users) 49 | 50 | # del data 51 | data.clear() 52 | print(data) 53 | 54 | users[1:2] = ['dave'] 55 | users.sort() 56 | print(users) 57 | 58 | users.sort(key=str.lower) 59 | print(users) 60 | 61 | nums = [4, 42, 78, 1, 5] 62 | nums.reverse() 63 | print(nums) 64 | 65 | # nums.sort(reverse=True) 66 | # print(nums) 67 | 68 | print(sorted(nums, reverse=True)) 69 | print(nums) 70 | 71 | numscopy = nums.copy() 72 | mynums = list(nums) 73 | mycopy = nums[:] 74 | 75 | print(numscopy) 76 | print(mynums) 77 | mycopy.sort() 78 | print(mycopy) 79 | print(nums) 80 | 81 | print(type(nums)) 82 | 83 | mylist = list([1, "Neil", True]) 84 | print(mylist) 85 | 86 | # Tuples 87 | 88 | mytuple = tuple(('Dave', 42, True)) 89 | 90 | anothertuple = (1, 4, 2, 8, 2, 2) 91 | 92 | print(mytuple) 93 | print(type(mytuple)) 94 | print(type(anothertuple)) 95 | 96 | newlist = list(mytuple) 97 | newlist.append('Neil') 98 | newtuple = tuple(newlist) 99 | print(newtuple) 100 | 101 | (one, *two, hey) = anothertuple 102 | print(one) 103 | print(two) 104 | print(hey) 105 | 106 | print(anothertuple.count(2)) 107 | -------------------------------------------------------------------------------- /lesson07/dictionaries.py: -------------------------------------------------------------------------------- 1 | # Dictionaries 2 | band = { 3 | "vocals": "Plant", 4 | "guitar": "Page" 5 | } 6 | 7 | band2 = dict(vocals="Plant", guitar="Page") 8 | 9 | print(band) 10 | print(band2) 11 | print(type(band)) 12 | print(len(band)) 13 | 14 | # Access items 15 | print(band["vocals"]) 16 | print(band.get("guitar")) 17 | 18 | # list all keys 19 | print(band.keys()) 20 | 21 | # list all values 22 | print(band.values()) 23 | 24 | # list of key/value pairs as tuples 25 | print(band.items()) 26 | 27 | # verify a key exists 28 | print("guitar" in band) 29 | print("triangle" in band) 30 | 31 | # Change values 32 | band["vocals"] = "Coverdale" 33 | band.update({"bass": "JPJ"}) 34 | 35 | print(band) 36 | 37 | # Remove items 38 | print(band.pop("bass")) 39 | print(band) 40 | 41 | band["drums"] = "Bonham" 42 | print(band) 43 | 44 | print(band.popitem()) # tuple 45 | print(band) 46 | 47 | # Delete and clear 48 | 49 | band["drums"] = "Bonham" 50 | del band["drums"] 51 | print(band) 52 | 53 | band2.clear() 54 | print(band2) 55 | 56 | del band2 57 | 58 | # Copy dictionaries 59 | 60 | # band2 = band # create a reference 61 | # print("Bad copy!") 62 | # print(band2) 63 | # print(band) 64 | 65 | # band2["drums"] = "Dave" 66 | # print(band) 67 | 68 | band2 = band.copy() 69 | band2["drums"] = "Dave" 70 | print("Good copy!") 71 | print(band) 72 | print(band2) 73 | 74 | # or use the dict() constructor function 75 | band3 = dict(band) 76 | print("Good copy!") 77 | print(band3) 78 | 79 | # Nested dictionaries 80 | 81 | member1 = { 82 | "name": "Plant", 83 | "instrument": "vocals" 84 | } 85 | member2 = { 86 | "name": "Page", 87 | "instrument": "guitar" 88 | } 89 | band = { 90 | "member1": member1, 91 | "member2": member2 92 | } 93 | print(band) 94 | print(band["member1"]["name"]) 95 | 96 | # Sets 97 | 98 | nums = {1, 2, 3, 4} 99 | 100 | nums2 = set((1, 2, 3, 4)) 101 | 102 | print(nums) 103 | print(nums2) 104 | print(type(nums)) 105 | print(len(nums)) 106 | 107 | # No duplicate allowed 108 | nums = {1, 2, 2, 3} 109 | print(nums) 110 | 111 | # True is a dupe of 1, False is a dupe of zero 112 | nums = {1, True, 2, False, 3, 4, 0} 113 | print(nums) 114 | 115 | # check if a value is in a set 116 | print(2 in nums) 117 | 118 | # but you cannot refer to an element in the set with an index position or a key 119 | 120 | # Add a new element to a set 121 | nums.add(8) 122 | print(nums) 123 | 124 | # Add elements from one set to another 125 | morenums = {5, 6, 7} 126 | nums.update(morenums) 127 | print(nums) 128 | 129 | # you can use update with lists, tuples, and dictionaries, too. 130 | 131 | # Merge two sets to create a new set 132 | one = {1, 2, 3} 133 | two = {5, 6, 7} 134 | 135 | mynewset = one.union(two) 136 | print(mynewset) 137 | 138 | # Keep only the duplicates 139 | one = {1, 2, 3} 140 | two = {2, 3, 4} 141 | 142 | one.intersection_update(two) 143 | print(one) 144 | 145 | # Keep everything except the duplicates 146 | one = {1, 2, 3} 147 | two = {2, 3, 4} 148 | 149 | one.symmetric_difference_update(two) 150 | print(one) 151 | -------------------------------------------------------------------------------- /lesson08/loops.py: -------------------------------------------------------------------------------- 1 | value = 1 2 | # while value <= 10: 3 | # print(value) 4 | # if value == 5: 5 | # break 6 | # value += 1 7 | 8 | # while value <= 10: 9 | # value += 1 10 | # if value == 5: 11 | # continue 12 | # print(value) 13 | # else: 14 | # print("Value is now equal to " + str(value)) 15 | 16 | names = ["Dave", "Sara", "John"] 17 | # for x in names: 18 | # print(x) 19 | 20 | # for x in "Mississippi": 21 | # print(x) 22 | 23 | # for x in names: 24 | # if x == "Sara": 25 | # break 26 | # print(x) 27 | 28 | # for x in names: 29 | # if x == "Sara": 30 | # continue 31 | # print(x) 32 | 33 | # for x in range(4): 34 | # print(x) 35 | 36 | # for x in range(2, 4): 37 | # print(x) 38 | 39 | for x in range(5, 101, 5): 40 | print(x) 41 | else: 42 | print("Glad that\'s over!") 43 | 44 | names = ["Dave", "Sara", "John"] 45 | actions = ["codes", "eats", "sleeps"] 46 | 47 | # for name in names: 48 | # for action in actions: 49 | # print(name + " " + action + ".") 50 | 51 | for action in actions: 52 | for name in names: 53 | print(name + " " + action + ".") 54 | -------------------------------------------------------------------------------- /lesson08/rps2.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | class RPS(Enum): 7 | ROCK = 1 8 | PAPER = 2 9 | SCISSORS = 3 10 | 11 | 12 | playagain = True 13 | 14 | while playagain: 15 | 16 | playerchoice = input( 17 | "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 18 | 19 | player = int(playerchoice) 20 | 21 | if player < 1 or player > 3: 22 | sys.exit("You must enter 1, 2, or 3.") 23 | 24 | computerchoice = random.choice("123") 25 | 26 | computer = int(computerchoice) 27 | 28 | print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") 29 | print("Python chose " + str(RPS(computer)).replace('RPS.', '').title() + ".\n") 30 | 31 | if player == 1 and computer == 3: 32 | print("🎉 You win!") 33 | elif player == 2 and computer == 1: 34 | print("🎉 You win!") 35 | elif player == 3 and computer == 2: 36 | print("🎉 You win!") 37 | elif player == computer: 38 | print("😲 Tie game!") 39 | else: 40 | print("🐍 Python wins!") 41 | 42 | playagain = input("\nPlay again? \nY for Yes or \nQ to Quit \n\n") 43 | 44 | if playagain.lower() == "y": 45 | continue 46 | else: 47 | print("\n🎉🎉🎉🎉") 48 | print("Thank you for playing!\n") 49 | playagain = False 50 | 51 | sys.exit("Bye! 👋") 52 | -------------------------------------------------------------------------------- /lesson09/functions.py: -------------------------------------------------------------------------------- 1 | def hello_world(): 2 | print("Hello world!") 3 | 4 | 5 | hello_world() 6 | 7 | 8 | def sum(num1=0, num2=0): 9 | if (type(num1) is not int or type(num2) is not int): 10 | return 0 11 | return num1 + num2 12 | 13 | 14 | total = sum(7, 2) 15 | print(total) 16 | 17 | 18 | def multiple_items(*args): 19 | print(args) 20 | print(type(args)) 21 | 22 | 23 | multiple_items("Dave", "John", "Sara") 24 | 25 | 26 | def mult_named_items(**kwargs): 27 | print(kwargs) 28 | print(type(kwargs)) 29 | 30 | 31 | mult_named_items(first="Dave", last="Gray") 32 | -------------------------------------------------------------------------------- /lesson10/example.py: -------------------------------------------------------------------------------- 1 | value = "y" 2 | count = 0 3 | 4 | while value: 5 | count += 1 6 | print(count) 7 | if (count == 5): 8 | break 9 | else: 10 | value = 0 11 | continue 12 | -------------------------------------------------------------------------------- /lesson10/recursion.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def add_one(num): 4 | 5 | if (num >= 9): 6 | return num + 1 7 | 8 | total = num + 1 9 | print(total) 10 | 11 | return add_one(total) 12 | 13 | 14 | mynewtotal = add_one(0) 15 | print(mynewtotal) 16 | -------------------------------------------------------------------------------- /lesson10/rps3.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | def play_rps(): 7 | 8 | class RPS(Enum): 9 | ROCK = 1 10 | PAPER = 2 11 | SCISSORS = 3 12 | 13 | playerchoice = input( 14 | "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 15 | 16 | if playerchoice not in ["1", "2", "3"]: 17 | print("You must enter 1, 2, or 3.") 18 | return play_rps() 19 | 20 | player = int(playerchoice) 21 | 22 | computerchoice = random.choice("123") 23 | 24 | computer = int(computerchoice) 25 | 26 | print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") 27 | print("Python chose " + str(RPS(computer) 28 | ).replace('RPS.', '').title() + ".\n") 29 | 30 | if player == 1 and computer == 3: 31 | print("🎉 You win!") 32 | elif player == 2 and computer == 1: 33 | print("🎉 You win!") 34 | elif player == 3 and computer == 2: 35 | print("🎉 You win!") 36 | elif player == computer: 37 | print("😲 Tie game!") 38 | else: 39 | print("🐍 Python wins!") 40 | 41 | print("\nPlay again?") 42 | 43 | while True: 44 | playagain = input("\nY for Yes or \nQ to Quit\n") 45 | if playagain.lower() not in ["y", "q"]: 46 | continue 47 | else: 48 | break 49 | 50 | if playagain.lower() == "y": 51 | return play_rps() 52 | else: 53 | print("\n🎉🎉🎉🎉") 54 | print("Thank you for playing!\n") 55 | sys.exit("Bye! 👋") 56 | 57 | 58 | play_rps() 59 | -------------------------------------------------------------------------------- /lesson11/rps4.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | game_count = 0 6 | 7 | 8 | def play_rps(): 9 | 10 | class RPS(Enum): 11 | ROCK = 1 12 | PAPER = 2 13 | SCISSORS = 3 14 | 15 | playerchoice = input( 16 | "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 17 | 18 | if playerchoice not in ["1", "2", "3"]: 19 | print("You must enter 1, 2, or 3.") 20 | return play_rps() 21 | 22 | player = int(playerchoice) 23 | 24 | computerchoice = random.choice("123") 25 | 26 | computer = int(computerchoice) 27 | 28 | print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") 29 | print("Python chose " + str(RPS(computer) 30 | ).replace('RPS.', '').title() + ".\n") 31 | 32 | def decide_winner(player, computer): 33 | if player == 1 and computer == 3: 34 | return "🎉 You win!" 35 | elif player == 2 and computer == 1: 36 | return "🎉 You win!" 37 | elif player == 3 and computer == 2: 38 | return "🎉 You win!" 39 | elif player == computer: 40 | return "😲 Tie game!" 41 | else: 42 | return "🐍 Python wins!" 43 | 44 | game_result = decide_winner(player, computer) 45 | 46 | print(game_result) 47 | 48 | global game_count 49 | game_count += 1 50 | 51 | print("\nGame count: " + str(game_count)) 52 | 53 | print("\nPlay again?") 54 | 55 | while True: 56 | playagain = input("\nY for Yes or \nQ to Quit\n") 57 | if playagain.lower() not in ["y", "q"]: 58 | continue 59 | else: 60 | break 61 | 62 | if playagain.lower() == "y": 63 | return play_rps() 64 | else: 65 | print("\n🎉🎉🎉🎉") 66 | print("Thank you for playing!\n") 67 | sys.exit("Bye! 👋") 68 | 69 | 70 | play_rps() 71 | -------------------------------------------------------------------------------- /lesson11/scope.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | name = "Dave" 4 | count = 1 5 | 6 | 7 | def another(): 8 | color = "blue" 9 | global count 10 | count += 1 11 | print(count) 12 | 13 | def greeting(name): 14 | nonlocal color 15 | color = "red" 16 | print(color) 17 | print(name) 18 | 19 | greeting("Dave") 20 | 21 | 22 | another() 23 | -------------------------------------------------------------------------------- /lesson12/closure.py: -------------------------------------------------------------------------------- 1 | # Closure is a function having access to the scope of its parent 2 | # function after the parent function has returned. 3 | 4 | def parent_function(person, coins): 5 | # coins = 3 6 | 7 | def play_game(): 8 | nonlocal coins 9 | coins -= 1 10 | 11 | if coins > 1: 12 | print("\n" + person + " has " + str(coins) + " coins left.") 13 | elif coins == 1: 14 | print("\n" + person + " has " + str(coins) + " coin left.") 15 | else: 16 | print("\n" + person + " is out of coins.") 17 | 18 | return play_game 19 | 20 | 21 | tommy = parent_function("Tommy", 3) 22 | jenny = parent_function("Jenny", 5) 23 | 24 | tommy() 25 | tommy() 26 | 27 | jenny() 28 | 29 | tommy() 30 | -------------------------------------------------------------------------------- /lesson12/rps5.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | def rps(): 7 | game_count = 0 8 | player_wins = 0 9 | python_wins = 0 10 | 11 | def play_rps(): 12 | nonlocal player_wins 13 | nonlocal python_wins 14 | 15 | class RPS(Enum): 16 | ROCK = 1 17 | PAPER = 2 18 | SCISSORS = 3 19 | 20 | playerchoice = input( 21 | "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 22 | 23 | if playerchoice not in ["1", "2", "3"]: 24 | print("You must enter 1, 2, or 3.") 25 | return play_rps() 26 | 27 | player = int(playerchoice) 28 | 29 | computerchoice = random.choice("123") 30 | 31 | computer = int(computerchoice) 32 | 33 | print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") 34 | print("Python chose " + str(RPS(computer) 35 | ).replace('RPS.', '').title() + ".\n") 36 | 37 | def decide_winner(player, computer): 38 | nonlocal player_wins 39 | nonlocal python_wins 40 | if player == 1 and computer == 3: 41 | player_wins += 1 42 | return "🎉 You win!" 43 | elif player == 2 and computer == 1: 44 | player_wins += 1 45 | return "🎉 You win!" 46 | elif player == 3 and computer == 2: 47 | player_wins += 1 48 | return "🎉 You win!" 49 | elif player == computer: 50 | return "😲 Tie game!" 51 | else: 52 | python_wins += 1 53 | return "🐍 Python wins!" 54 | 55 | game_result = decide_winner(player, computer) 56 | 57 | print(game_result) 58 | 59 | nonlocal game_count 60 | game_count += 1 61 | 62 | print("\nGame count: " + str(game_count)) 63 | print("\nPlayer wins: " + str(player_wins)) 64 | print("\nPython wins: " + str(python_wins)) 65 | 66 | print("\nPlay again?") 67 | 68 | while True: 69 | playagain = input("\nY for Yes or \nQ to Quit\n") 70 | if playagain.lower() not in ["y", "q"]: 71 | continue 72 | else: 73 | break 74 | 75 | if playagain.lower() == "y": 76 | return play_rps() 77 | else: 78 | print("\n🎉🎉🎉🎉") 79 | print("Thank you for playing!\n") 80 | sys.exit("Bye! 👋") 81 | 82 | return play_rps 83 | 84 | 85 | play = rps() 86 | 87 | play() 88 | -------------------------------------------------------------------------------- /lesson13/f_strings.py: -------------------------------------------------------------------------------- 1 | person = "Dave" 2 | coins = 3 3 | 4 | ################# 5 | # Concatenating strings 6 | 7 | print("\n" + person + " has " + str(coins) + " coins left.") 8 | 9 | ################# 10 | # Previous %s formatting 11 | 12 | message = "\n%s has %s coins left." % (person, coins) 13 | print(message) 14 | 15 | ################# 16 | # Previous string.format() method 17 | 18 | message = "\n{} has {} coins left.".format(person, coins) 19 | print(message) 20 | 21 | message = "\n{1} has {0} coins left.".format(coins, person) 22 | print(message) 23 | 24 | message = "\n{person} has {coins} coins left.".format( 25 | coins=coins, person=person 26 | ) 27 | print(message) 28 | 29 | player = {'person': 'Dave', 'coins': 3} 30 | 31 | message = "\n{person} has {coins} coins left.".format(**player) 32 | print(message) 33 | 34 | ################## 35 | # f-Strings! This is the way. 36 | 37 | message = f"\n{person} has {coins} coins left." 38 | print(message) 39 | 40 | message = f"\n{person} has {2 * 5} coins left." 41 | print(message) 42 | 43 | message = f"\n{person.lower()} has {2 * 5} coins left." 44 | print(message) 45 | 46 | message = f"\n{player['person']} has {2 * 5} coins left." 47 | print(message) 48 | 49 | ################## 50 | # You can pass formatting options 51 | 52 | num = 10 53 | print(f"\n2.25 times {num} is {2.25 * num:.2f}\n") 54 | 55 | for num in range(1, 11): 56 | print(f"2.25 times {num} is {2.25 * num:.2f}") 57 | 58 | for num in range(1, 11): 59 | print(f"{num} divided by 4.52 is {num / 4.52:.2%}") 60 | -------------------------------------------------------------------------------- /lesson13/rps6.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | def rps(): 7 | game_count = 0 8 | player_wins = 0 9 | python_wins = 0 10 | 11 | def play_rps(): 12 | nonlocal player_wins 13 | nonlocal python_wins 14 | 15 | class RPS(Enum): 16 | ROCK = 1 17 | PAPER = 2 18 | SCISSORS = 3 19 | 20 | playerchoice = input( 21 | "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 22 | 23 | if playerchoice not in ["1", "2", "3"]: 24 | print("You must enter 1, 2, or 3.") 25 | return play_rps() 26 | 27 | player = int(playerchoice) 28 | 29 | computerchoice = random.choice("123") 30 | 31 | computer = int(computerchoice) 32 | 33 | print(f"\nYou chose {str(RPS(player)).replace('RPS.', '').title()}.") 34 | print( 35 | f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" 36 | ) 37 | 38 | def decide_winner(player, computer): 39 | nonlocal player_wins 40 | nonlocal python_wins 41 | if player == 1 and computer == 3: 42 | player_wins += 1 43 | return "🎉 You win!" 44 | elif player == 2 and computer == 1: 45 | player_wins += 1 46 | return "🎉 You win!" 47 | elif player == 3 and computer == 2: 48 | player_wins += 1 49 | return "🎉 You win!" 50 | elif player == computer: 51 | return "😲 Tie game!" 52 | else: 53 | python_wins += 1 54 | return "🐍 Python wins!" 55 | 56 | game_result = decide_winner(player, computer) 57 | 58 | print(game_result) 59 | 60 | nonlocal game_count 61 | game_count += 1 62 | 63 | print(f"\nGame count: {str(game_count)}") 64 | print(f"\nPlayer wins: {str(player_wins)}") 65 | print(f"\nPython wins: {str(python_wins)}") 66 | 67 | print("\nPlay again?") 68 | 69 | while True: 70 | playagain = input("\nY for Yes or \nQ to Quit\n") 71 | if playagain.lower() not in ["y", "q"]: 72 | continue 73 | else: 74 | break 75 | 76 | if playagain.lower() == "y": 77 | return play_rps() 78 | else: 79 | print("\n🎉🎉🎉🎉") 80 | print("Thank you for playing!\n") 81 | sys.exit("Bye! 👋") 82 | 83 | return play_rps 84 | 85 | 86 | play = rps() 87 | 88 | play() 89 | -------------------------------------------------------------------------------- /lesson14/kansas.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | capital = "Topeka" 4 | 5 | bird = "Western Meadowlark" 6 | 7 | flower = "Sunflower" 8 | 9 | song = "Home on the Range" 10 | 11 | 12 | def randomfunfact(): 13 | funfacts = [ 14 | "Kansas is considered flat, but it does have a mountain.", 15 | "Wichita is the largest city in the state, but many would guess that it is Kansas City.", 16 | "A considerable portion of Kansas City is actually in Missouri.", 17 | "Most Kansans are annoyed by Wizard of Oz references from people outside of Kansas." 18 | ] 19 | 20 | index = choice("0123") 21 | 22 | print(funfacts[int(index)]) 23 | 24 | 25 | if __name__ == "__main__": 26 | randomfunfact() 27 | -------------------------------------------------------------------------------- /lesson14/modules.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from math import pi 4 | import sys 5 | import random as rdm 6 | from enum import Enum 7 | import kansas 8 | from rps7 import rock_paper_scissors 9 | 10 | print(pi) 11 | 12 | # for item in dir(rdm): 13 | # print(item) 14 | 15 | print(kansas.capital) 16 | kansas.randomfunfact() 17 | 18 | print(__name__) 19 | print(kansas.__name__) 20 | 21 | rock_paper_scissors() 22 | -------------------------------------------------------------------------------- /lesson14/rps7.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | def rps(): 7 | game_count = 0 8 | player_wins = 0 9 | python_wins = 0 10 | 11 | def play_rps(): 12 | nonlocal player_wins 13 | nonlocal python_wins 14 | 15 | class RPS(Enum): 16 | ROCK = 1 17 | PAPER = 2 18 | SCISSORS = 3 19 | 20 | playerchoice = input( 21 | "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 22 | 23 | if playerchoice not in ["1", "2", "3"]: 24 | print("You must enter 1, 2, or 3.") 25 | return play_rps() 26 | 27 | player = int(playerchoice) 28 | 29 | computerchoice = random.choice("123") 30 | 31 | computer = int(computerchoice) 32 | 33 | print(f"\nYou chose {str(RPS(player)).replace('RPS.', '').title()}.") 34 | print( 35 | f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" 36 | ) 37 | 38 | def decide_winner(player, computer): 39 | nonlocal player_wins 40 | nonlocal python_wins 41 | if player == 1 and computer == 3: 42 | player_wins += 1 43 | return "🎉 You win!" 44 | elif player == 2 and computer == 1: 45 | player_wins += 1 46 | return "🎉 You win!" 47 | elif player == 3 and computer == 2: 48 | player_wins += 1 49 | return "🎉 You win!" 50 | elif player == computer: 51 | return "😲 Tie game!" 52 | else: 53 | python_wins += 1 54 | return "🐍 Python wins!" 55 | 56 | game_result = decide_winner(player, computer) 57 | 58 | print(game_result) 59 | 60 | nonlocal game_count 61 | game_count += 1 62 | 63 | print(f"\nGame count: {str(game_count)}") 64 | print(f"\nPlayer wins: {str(player_wins)}") 65 | print(f"\nPython wins: {str(python_wins)}") 66 | 67 | print("\nPlay again?") 68 | 69 | while True: 70 | playagain = input("\nY for Yes or \nQ to Quit\n") 71 | if playagain.lower() not in ["y", "q"]: 72 | continue 73 | else: 74 | break 75 | 76 | if playagain.lower() == "y": 77 | return play_rps() 78 | else: 79 | print("\n🎉🎉🎉🎉") 80 | print("Thank you for playing!\n") 81 | sys.exit("Bye! 👋") 82 | 83 | return play_rps 84 | 85 | 86 | rock_paper_scissors = rps() 87 | 88 | if __name__ == "__main__": 89 | rock_paper_scissors() 90 | -------------------------------------------------------------------------------- /lesson15/hello_person.py: -------------------------------------------------------------------------------- 1 | def hello(name, lang): 2 | greetings = { 3 | "English": "Hello", 4 | "Spanish": "Hola", 5 | "German": "Hallo", 6 | } 7 | msg = f"{greetings[lang]} {name}!" 8 | print(msg) 9 | 10 | 11 | if __name__ == '__main__': 12 | import argparse 13 | 14 | parser = argparse.ArgumentParser( 15 | description="Provides a personal greeting." 16 | ) 17 | 18 | parser.add_argument( 19 | "-n", "--name", metavar="name", 20 | required=True, help="The name of the person to greet." 21 | ) 22 | 23 | parser.add_argument( 24 | "-l", "--lang", metavar="language", 25 | required=True, choices=["English", "Spanish", "German"], 26 | help="The language of the greeting." 27 | ) 28 | 29 | args = parser.parse_args() 30 | 31 | hello(args.name, args.lang) 32 | -------------------------------------------------------------------------------- /lesson15/rps8.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | def rps(name='PlayerOne'): 7 | game_count = 0 8 | player_wins = 0 9 | python_wins = 0 10 | 11 | def play_rps(): 12 | nonlocal name 13 | nonlocal player_wins 14 | nonlocal python_wins 15 | 16 | class RPS(Enum): 17 | ROCK = 1 18 | PAPER = 2 19 | SCISSORS = 3 20 | 21 | playerchoice = input( 22 | f"\n{name}, please enter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 23 | 24 | if playerchoice not in ["1", "2", "3"]: 25 | print(f"{name}, please enter 1, 2, or 3.") 26 | return play_rps() 27 | 28 | player = int(playerchoice) 29 | 30 | computerchoice = random.choice("123") 31 | 32 | computer = int(computerchoice) 33 | 34 | print(f"\n{name}, you chose {str(RPS(player)).replace('RPS.', '').title()}.") 35 | print( 36 | f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" 37 | ) 38 | 39 | def decide_winner(player, computer): 40 | nonlocal name 41 | nonlocal player_wins 42 | nonlocal python_wins 43 | if player == 1 and computer == 3: 44 | player_wins += 1 45 | return f"🎉 {name}, you win!" 46 | elif player == 2 and computer == 1: 47 | player_wins += 1 48 | return f"🎉 {name}, you win!" 49 | elif player == 3 and computer == 2: 50 | player_wins += 1 51 | return f"🎉 {name}, you win!" 52 | elif player == computer: 53 | return "😲 Tie game!" 54 | else: 55 | python_wins += 1 56 | return f"🐍 Python wins!\nSorry, {name}..😢" 57 | 58 | game_result = decide_winner(player, computer) 59 | 60 | print(game_result) 61 | 62 | nonlocal game_count 63 | game_count += 1 64 | 65 | print(f"\nGame count: {game_count}") 66 | print(f"\n{name}'s wins: {player_wins}") 67 | print(f"\nPython wins: {python_wins}") 68 | 69 | print(f"\nPlay again, {name}?") 70 | 71 | while True: 72 | playagain = input("\nY for Yes or \nQ to Quit\n") 73 | if playagain.lower() not in ["y", "q"]: 74 | continue 75 | else: 76 | break 77 | 78 | if playagain.lower() == "y": 79 | return play_rps() 80 | else: 81 | print("\n🎉🎉🎉🎉") 82 | print("Thank you for playing!\n") 83 | sys.exit(f"Bye {name}! 👋") 84 | 85 | return play_rps 86 | 87 | 88 | 89 | 90 | if __name__ == "__main__": 91 | import argparse 92 | 93 | parser = argparse.ArgumentParser( 94 | description="Provides a personalized game experience." 95 | ) 96 | 97 | parser.add_argument( 98 | "-n", "--name", metavar="name", 99 | required=True, help="The name of the person playing the game." 100 | ) 101 | 102 | args = parser.parse_args() 103 | 104 | rock_paper_scissors = rps(args.name) 105 | rock_paper_scissors() 106 | -------------------------------------------------------------------------------- /lesson16/arcade.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from rps import rps 3 | from guess_number import guess_number 4 | 5 | 6 | def play_game(name='PlayerOne'): 7 | welcome_back = False 8 | 9 | while True: 10 | if welcome_back == True: 11 | print(f"\n{name}, welcome back to the Arcade menu.") 12 | 13 | playerchoice = input( 14 | "\nPlease choose a game:\n1 = Rock Paper Scissors\n2 = Guess My Number\n\nOr press \"x\" to exit the Arcade\n\n" 15 | ) 16 | 17 | if playerchoice not in ["1", "2", "x"]: 18 | print(f"\n{name}, please enter 1, 2, or x.") 19 | return play_game(name) 20 | 21 | welcome_back = True 22 | 23 | if playerchoice == "1": 24 | rock_paper_scissors = rps(name) 25 | rock_paper_scissors() 26 | elif playerchoice == "2": 27 | guess_my_number = guess_number(name) 28 | guess_my_number() 29 | else: 30 | print("\nSee you next time!\n") 31 | sys.exit(f"Bye {name}! 👋") 32 | 33 | 34 | if __name__ == "__main__": 35 | import argparse 36 | 37 | parser = argparse.ArgumentParser( 38 | description="Provides a personalized game experience." 39 | ) 40 | 41 | parser.add_argument( 42 | '-n', '--name', metavar='name', 43 | required=True, help='The name of the person playing the game.' 44 | ) 45 | 46 | args = parser.parse_args() 47 | 48 | print(f"\n{args.name}, welcome to the Arcade! 🤖") 49 | 50 | play_game(args.name) 51 | -------------------------------------------------------------------------------- /lesson16/guess_number.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | 4 | 5 | def guess_number(name='PlayerOne'): 6 | game_count = 0 7 | player_wins = 0 8 | 9 | def play_guess_number(): 10 | nonlocal name 11 | nonlocal player_wins 12 | 13 | playerchoice = input( 14 | f"\n{name}, guess which number I'm thinking of... 1, 2, or 3.\n\n") 15 | 16 | if playerchoice not in ["1", "2", "3"]: 17 | print(f"{name}, please enter 1, 2, or 3.") 18 | return play_guess_number() 19 | 20 | computerchoice = random.choice("123") 21 | 22 | print(f"\n{name}, you chose {playerchoice}.") 23 | print( 24 | f"I was thinking about the number {computerchoice}.\n" 25 | ) 26 | 27 | player = int(playerchoice) 28 | 29 | computer = int(computerchoice) 30 | 31 | def decide_winner(player, computer): 32 | nonlocal name 33 | nonlocal player_wins 34 | 35 | if player == computer: 36 | player_wins += 1 37 | return f"🎉 {name}, you win!" 38 | else: 39 | return f"Sorry, {name}. Better luck next time. 😢" 40 | 41 | game_result = decide_winner(player, computer) 42 | 43 | print(game_result) 44 | 45 | nonlocal game_count 46 | game_count += 1 47 | 48 | print(f"\nGame count: {game_count}") 49 | print(f"\n{name}'s wins: {player_wins}") 50 | print(f"\nYour winning percentage: {player_wins/game_count:.2%}") 51 | 52 | print(f"\nPlay again, {name}?") 53 | 54 | while True: 55 | playagain = input("\nY for Yes or \nQ to Quit\n") 56 | if playagain.lower() not in ["y", "q"]: 57 | continue 58 | else: 59 | break 60 | 61 | if playagain.lower() == "y": 62 | return play_guess_number() 63 | else: 64 | print("\n🎉🎉🎉🎉") 65 | print("Thank you for playing!\n") 66 | if __name__ == "__main__": 67 | sys.exit(f"Bye {name}! 👋") 68 | else: 69 | return 70 | 71 | return play_guess_number 72 | 73 | 74 | if __name__ == "__main__": 75 | import argparse 76 | 77 | parser = argparse.ArgumentParser( 78 | description="Provides a personalized game experience." 79 | ) 80 | 81 | parser.add_argument( 82 | '-n', '--name', metavar='name', 83 | required=True, help='The name of the person playing the game.' 84 | ) 85 | 86 | args = parser.parse_args() 87 | 88 | guess_my_number = guess_number(args.name) 89 | guess_my_number() 90 | -------------------------------------------------------------------------------- /lesson16/rps.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | from enum import Enum 4 | 5 | 6 | def rps(name='PlayerOne'): 7 | game_count = 0 8 | player_wins = 0 9 | python_wins = 0 10 | 11 | def play_rps(): 12 | nonlocal name 13 | nonlocal player_wins 14 | nonlocal python_wins 15 | 16 | class RPS(Enum): 17 | ROCK = 1 18 | PAPER = 2 19 | SCISSORS = 3 20 | 21 | playerchoice = input( 22 | f"\n{name}, please enter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") 23 | 24 | if playerchoice not in ["1", "2", "3"]: 25 | print(f"{name}, please enter 1, 2, or 3.") 26 | return play_rps() 27 | 28 | player = int(playerchoice) 29 | 30 | computerchoice = random.choice("123") 31 | 32 | computer = int(computerchoice) 33 | 34 | print(f"\n{name}, you chose {str(RPS(player)).replace('RPS.', '').title()}.") 35 | print( 36 | f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" 37 | ) 38 | 39 | def decide_winner(player, computer): 40 | nonlocal name 41 | nonlocal player_wins 42 | nonlocal python_wins 43 | if player == 1 and computer == 3: 44 | player_wins += 1 45 | return f"🎉 {name}, you win!" 46 | elif player == 2 and computer == 1: 47 | player_wins += 1 48 | return f"🎉 {name}, you win!" 49 | elif player == 3 and computer == 2: 50 | player_wins += 1 51 | return f"🎉 {name}, you win!" 52 | elif player == computer: 53 | return "😲 Tie game!" 54 | else: 55 | python_wins += 1 56 | return f"🐍 Python wins!\nSorry, {name}.. 😢" 57 | 58 | game_result = decide_winner(player, computer) 59 | 60 | print(game_result) 61 | 62 | nonlocal game_count 63 | game_count += 1 64 | 65 | print(f"\nGame count: {game_count}") 66 | print(f"\nPython wins: {python_wins}") 67 | print(f"\n{name}'s wins: {player_wins}") 68 | 69 | print(f"\nPlay again, {name}?") 70 | 71 | while True: 72 | playagain = input("\nY for Yes or \nQ to Quit\n") 73 | if playagain.lower() not in ["y", "q"]: 74 | continue 75 | else: 76 | break 77 | 78 | if playagain.lower() == "y": 79 | return play_rps() 80 | else: 81 | print("\n🎉🎉🎉🎉") 82 | print("Thank you for playing!\n") 83 | if __name__ == "__main__": 84 | sys.exit(f"Bye {name}! 👋") 85 | else: 86 | return 87 | 88 | return play_rps 89 | 90 | 91 | if __name__ == "__main__": 92 | import argparse 93 | 94 | parser = argparse.ArgumentParser( 95 | description="Provides a personalized game experience." 96 | ) 97 | 98 | parser.add_argument( 99 | '-n', '--name', metavar='name', 100 | required=True, help='The name of the person playing the game.' 101 | ) 102 | 103 | args = parser.parse_args() 104 | 105 | rock_paper_scissors = rps(args.name) 106 | rock_paper_scissors() 107 | 108 | -------------------------------------------------------------------------------- /lesson17/lambda.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | def squared(num): return num * num 3 | # lambda num : num * num 4 | 5 | 6 | print(squared(2)) 7 | 8 | 9 | def add_two(num): return num + 2 10 | # lambda num : num + 2 11 | 12 | 13 | print(add_two(12)) 14 | 15 | 16 | def sum_total(a, b): return a + b 17 | # lambda a, b : a + b 18 | 19 | 20 | print(sum_total(10, 8)) 21 | 22 | ####################### 23 | 24 | 25 | def funcBuilder(x): 26 | return lambda num: num + x 27 | 28 | 29 | add_ten = funcBuilder(10) 30 | add_twenty = funcBuilder(20) 31 | 32 | print(add_ten(7)) 33 | print(add_twenty(7)) 34 | 35 | ######################## 36 | 37 | 38 | numbers = [3, 7, 12, 18, 20, 21] 39 | 40 | squared_nums = map(lambda num: num * num, numbers) 41 | 42 | print(list(squared_nums)) 43 | 44 | ############################### 45 | 46 | odd_nums = filter(lambda num: num % 2 != 0, numbers) 47 | 48 | print(list(odd_nums)) 49 | 50 | ############################# 51 | 52 | 53 | numbers = [1, 2, 3, 4, 5, 1] 54 | 55 | total = reduce(lambda acc, curr: acc + curr, numbers, 10) 56 | 57 | print(total) 58 | 59 | print(sum(numbers, 10)) 60 | 61 | 62 | names = ['Dave Gray', 'Sara Ito', 'John Jacob Jingleheimerschmidt'] 63 | 64 | char_count = reduce(lambda acc, curr: acc + len(curr), names, 0) 65 | 66 | print(char_count) 67 | -------------------------------------------------------------------------------- /lesson18/classes.py: -------------------------------------------------------------------------------- 1 | class Vehicle: 2 | def __init__(self, make, model): 3 | self.make = make 4 | self.model = model 5 | 6 | def moves(self): 7 | print('Moves along..') 8 | 9 | def get_make_model(self): 10 | print(f"I'm a {self.make} {self.model}.") 11 | 12 | 13 | my_car = Vehicle('Tesla', 'Model 3') 14 | 15 | # print(my_car.make) 16 | # print(my_car.model) 17 | my_car.get_make_model() 18 | my_car.moves() 19 | 20 | your_car = Vehicle('Cadillac', 'Escalade') 21 | your_car.get_make_model() 22 | your_car.moves() 23 | 24 | 25 | class Airplane(Vehicle): 26 | def __init__(self, make, model, faa_id): 27 | super().__init__(make, model) 28 | self.faa_id = faa_id 29 | 30 | def moves(self): 31 | print('Flies along..') 32 | 33 | 34 | class Truck(Vehicle): 35 | def moves(self): 36 | print('Rumbles along..') 37 | 38 | 39 | class GolfCart(Vehicle): 40 | pass 41 | 42 | 43 | cessna = Airplane('Cessna', 'Skyhawk', 'N-12345') 44 | mack = Truck('Mack', 'Pinnacle') 45 | golfwagon = GolfCart('Yamaha', 'GC100') 46 | 47 | cessna.get_make_model() 48 | cessna.moves() 49 | mack.get_make_model() 50 | mack.moves() 51 | golfwagon.get_make_model() 52 | golfwagon.moves() 53 | 54 | print('\n\n') 55 | 56 | for v in (my_car, your_car, cessna, mack, golfwagon): 57 | v.get_make_model() 58 | v.moves() 59 | -------------------------------------------------------------------------------- /lesson19/exceptions.py: -------------------------------------------------------------------------------- 1 | class JustNotCoolError(Exception): 2 | pass 3 | 4 | 5 | x = 2 6 | try: 7 | raise JustNotCoolError("This just isn't cool, man.") 8 | # raise Exception("I'm a custom exception!") 9 | # print(x / 0) 10 | # if not type(x) is str: 11 | # raise TypeError("Only strings are allowed.") 12 | except NameError: 13 | print('NameError means something is probably undefined.') 14 | except ZeroDivisionError: 15 | print('Please do not divide by zero.') 16 | except Exception as error: 17 | print(error) 18 | else: 19 | print('No errors!') 20 | finally: 21 | print("I'm going to print with or without an error.") 22 | -------------------------------------------------------------------------------- /lesson20/bank_accounts.py: -------------------------------------------------------------------------------- 1 | class BalanceException(Exception): 2 | pass 3 | 4 | 5 | class BankAccount: 6 | def __init__(self, initial_amount, acct_name): 7 | self.balance = initial_amount 8 | self.name = acct_name 9 | print( 10 | f"\nAccount '{self.name}' created.\nBalance = ${self.balance:.2f}") 11 | 12 | def get_balance(self): 13 | print(f"\nAccount '{self.name}' balance = ${self.balance:.2f}") 14 | 15 | def deposit(self, amount): 16 | self.balance = self.balance + amount 17 | print("\nDeposit complete.") 18 | self.get_balance() 19 | 20 | def viable_transaction(self, amount): 21 | if self.balance >= amount: 22 | return 23 | else: 24 | raise BalanceException( 25 | f"\nSorry, account '{self.name}' only has a balance of ${self.balance:.2f}" 26 | ) 27 | 28 | def withdraw(self, amount): 29 | try: 30 | self.viable_transaction(amount) 31 | self.balance = self.balance - amount 32 | print("\nWithdraw complete.") 33 | self.get_balance() 34 | except BalanceException as error: 35 | print(f'\nWithdraw interrupted: {error}') 36 | 37 | def transfer(self, amount, account): 38 | try: 39 | print('\n**********\n\nBeginning Transfer.. 🚀') 40 | self.viable_transaction(amount) 41 | self.withdraw(amount) 42 | account.deposit(amount) 43 | print('\nTransfer complete! ✅\n\n**********') 44 | except BalanceException as error: 45 | print(f'\nTransfer interrupted. ❌ {error}') 46 | 47 | class InterestRewardsAcct(BankAccount): 48 | def deposit(self, amount): 49 | self.balance = self.balance + (amount * 1.05) 50 | print("\nDeposit complete.") 51 | self.get_balance() 52 | 53 | class SavingsAcct(InterestRewardsAcct): 54 | def __init__(self, initial_amount, acct_name): 55 | super().__init__(initial_amount, acct_name) 56 | self.fee = 5 57 | 58 | def withdraw(self, amount): 59 | try: 60 | self.viable_transaction(amount + self.fee) 61 | self.balance = self.balance - (amount + self.fee) 62 | print("\nWithdraw completed.") 63 | self.get_balance() 64 | except BalanceException as error: 65 | print(f'\nWithdraw interrupted: {error}') 66 | -------------------------------------------------------------------------------- /lesson20/oop_project.py: -------------------------------------------------------------------------------- 1 | from bank_accounts import * 2 | 3 | Dave = BankAccount(1000, "Dave") 4 | Sara = BankAccount(2000, "Sara") 5 | 6 | Dave.get_balance() 7 | Sara.get_balance() 8 | 9 | Sara.deposit(500) 10 | 11 | Dave.withdraw(10000) 12 | Dave.withdraw(10) 13 | 14 | Dave.transfer(10000, Sara) 15 | Dave.transfer(100, Sara) 16 | 17 | Jim = InterestRewardsAcct(1000, "Jim") 18 | 19 | Jim.get_balance() 20 | 21 | Jim.deposit(100) 22 | 23 | Jim.transfer(100, Dave) 24 | 25 | Blaze = SavingsAcct(1000, "Blaze") 26 | 27 | Blaze.get_balance() 28 | 29 | Blaze.deposit(100) 30 | 31 | Blaze.transfer(10000, Sara) 32 | Blaze.transfer(1000, Sara) 33 | -------------------------------------------------------------------------------- /lesson21/.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | .env 3 | -------------------------------------------------------------------------------- /lesson21/requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2023.5.7 2 | charset-normalizer==3.1.0 3 | idna==3.4 4 | python-dotenv==1.0.0 5 | requests==2.31.0 6 | urllib3==2.0.3 7 | -------------------------------------------------------------------------------- /lesson21/weather.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from dotenv import load_dotenv 3 | import os 4 | from pprint import pprint 5 | 6 | load_dotenv() 7 | 8 | 9 | def get_current_weather(): 10 | print('\n*** Get Current Weather Conditions ***\n') 11 | 12 | city = input("\nPlease enter a city name:\n") 13 | 14 | request_url = f'https://api.openweathermap.org/data/2.5/weather?appid={os.getenv("API_KEY")}&q={city}&units=imperial' 15 | 16 | # print(request_url) 17 | 18 | weather_data = requests.get(request_url).json() 19 | 20 | # pprint(weather_data) 21 | 22 | print(f'\nCurrent weather for {weather_data["name"]}:') 23 | print(f'\nThe temp is {weather_data["main"]["temp"]:.1f}°') 24 | print( 25 | f'\n{weather_data["weather"][0]["description"].capitalize()} and feels like {weather_data["main"]["feels_like"]:.1f}°\n') 26 | 27 | 28 | if __name__ == "__main__": 29 | get_current_weather() 30 | -------------------------------------------------------------------------------- /lesson22/context.txt: -------------------------------------------------------------------------------- 1 | Dave 2 | Jane 3 | Eddie 4 | Jimmie 5 | -------------------------------------------------------------------------------- /lesson22/files.py: -------------------------------------------------------------------------------- 1 | import os 2 | # r = Read 3 | # a = Append 4 | # w = Write 5 | # x = Create 6 | 7 | # Read - error if it doesn't exist 8 | 9 | f = open("names.txt") 10 | # print(f.read()) 11 | # print(f.read(4)) 12 | 13 | # print(f.readline()) 14 | # print(f.readline()) 15 | 16 | for line in f: 17 | print(line) 18 | 19 | f.close() 20 | 21 | try: 22 | f = open("names.txt") 23 | print(f.read()) 24 | except: 25 | print("The file you want to read doesn't exist") 26 | finally: 27 | f.close() 28 | 29 | # Append - creates the file if it doesn't exist 30 | f = open("names.txt", "a") 31 | f.write("Neil\n") 32 | f.close() 33 | 34 | f = open("names.txt") 35 | print(f.read()) 36 | f.close() 37 | 38 | # Write (overwrite) 39 | f = open("context.txt", "w") 40 | f.write("I deleted all of the context") 41 | f.close() 42 | 43 | f = open("context.txt") 44 | print(f.read()) 45 | f.close() 46 | 47 | # Two ways to create a new file 48 | 49 | # Opens a file for writing, creates the file if it does not exist 50 | f = open("name_list.txt", "w") 51 | f.close() 52 | 53 | # Creates the specified file, but returns an error if the file exists 54 | if not os.path.exists("dave.txt"): 55 | f = open("dave.txt", "x") 56 | f.close() 57 | 58 | # Delete a file 59 | 60 | # avoid an error if it doesn't exist 61 | if os.path.exists("dave.txt"): 62 | os.remove("dave.txt") 63 | else: 64 | print("The file you wish to delete does not exist") 65 | 66 | 67 | # with has built-in implicit exception handling 68 | # close() will be automatically called 69 | with open("more_names.txt") as f: 70 | content = f.read() 71 | 72 | with open("names.txt", "w") as f: 73 | f.write(content) 74 | -------------------------------------------------------------------------------- /lesson22/more_names.txt: -------------------------------------------------------------------------------- 1 | Dave 2 | Jane 3 | Eddie 4 | Jimmie 5 | -------------------------------------------------------------------------------- /lesson22/names.txt: -------------------------------------------------------------------------------- 1 | Dave 2 | Jane 3 | Eddie 4 | Jimmie 5 | -------------------------------------------------------------------------------- /lesson23/.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | .env 3 | __pycache__ 4 | -------------------------------------------------------------------------------- /lesson23/requirements.txt: -------------------------------------------------------------------------------- 1 | blinker==1.6.2 2 | certifi==2023.5.7 3 | charset-normalizer==3.2.0 4 | click==8.1.5 5 | colorama==0.4.6 6 | Flask==2.3.2 7 | idna==3.4 8 | itsdangerous==2.1.2 9 | Jinja2==3.1.2 10 | MarkupSafe==2.1.3 11 | python-dotenv==1.0.0 12 | requests==2.31.0 13 | urllib3==2.0.3 14 | waitress==2.1.2 15 | Werkzeug==2.3.6 16 | -------------------------------------------------------------------------------- /lesson23/server.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | from weather import get_current_weather 3 | from waitress import serve 4 | 5 | app = Flask(__name__) 6 | 7 | 8 | @app.route('/') 9 | @app.route('/index') 10 | def index(): 11 | return render_template('index.html') 12 | 13 | 14 | @app.route('/weather') 15 | def get_weather(): 16 | city = request.args.get('city') 17 | 18 | # Check for empty strings or string with only spaces 19 | if not bool(city.strip()): 20 | # You could render "City Not Found" instead like we do below 21 | city = "Kansas City" 22 | 23 | weather_data = get_current_weather(city) 24 | 25 | # City is not found by API 26 | if not weather_data['cod'] == 200: 27 | return render_template('city-not-found.html') 28 | 29 | return render_template( 30 | "weather.html", 31 | title=weather_data["name"], 32 | status=weather_data["weather"][0]["description"].capitalize(), 33 | temp=f"{weather_data['main']['temp']:.1f}", 34 | feels_like=f"{weather_data['main']['feels_like']:.1f}" 35 | ) 36 | 37 | 38 | if __name__ == "__main__": 39 | serve(app, host="0.0.0.0", port=8000) 40 | -------------------------------------------------------------------------------- /lesson23/static/styles/style.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | box-sizing: border-box; 5 | } 6 | 7 | body { 8 | padding: 2rem; 9 | background-color: #333; 10 | color: whitesmoke; 11 | min-height: 100vh; 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | gap: 2rem; 16 | font-size: 2rem; 17 | } 18 | 19 | input, button { 20 | font-size: 2rem; 21 | padding: 1rem; 22 | border-radius: 10px; 23 | } -------------------------------------------------------------------------------- /lesson23/templates/city-not-found.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | 6 | 7 |{{ status }} and {{ temp }} °
14 |Feels like {{ feels_like }} °
15 | 16 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /lesson23/weather.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | from pprint import pprint 3 | import requests 4 | import os 5 | 6 | load_dotenv() 7 | 8 | 9 | def get_current_weather(city="Kansas City"): 10 | 11 | request_url = f'http://api.openweathermap.org/data/2.5/weather?appid={os.getenv("API_KEY")}&q={city}&units=imperial' 12 | 13 | weather_data = requests.get(request_url).json() 14 | 15 | return weather_data 16 | 17 | 18 | if __name__ == "__main__": 19 | print('\n*** Get Current Weather Conditions ***\n') 20 | 21 | city = input("\nPlease enter a city name: ") 22 | 23 | # Check for empty strings or string with only spaces 24 | # This step is not required here 25 | # if not bool(city.strip()): 26 | # city = "Kansas City" 27 | 28 | weather_data = get_current_weather(city) 29 | 30 | print("\n") 31 | pprint(weather_data) 32 | --------------------------------------------------------------------------------