diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b431de6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.vscode +__pycache__ +.venv +.env diff --git a/README.md b/README.md index cfc92d6..9edfc90 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # "Python for Beginners" -### Full Course - ?? Chapters +### Full Course - 23 Chapters --- @@ -27,7 +27,7 @@ ### Description -šŗ [YouTube Playlist](https://www.youtube.com/playlist?list=PL0Zuz27SZ-6MQri81d012LwP5jvFZ_scc) for this repository. +šŗ [YouTube Playlist](https://bit.ly/dg-beginners-python) for this repository. š This repository shares ALL of the resources referenced during the Python for Beginners tutorial series. @@ -46,9 +46,14 @@ ### š References - š [Python Official Site](https://www.python.org/) -- š [Python String Methods](https://docs.python.org/3/library/stdtypes.html#textseq) -- š [Python Math Module](https://docs.python.org/3/library/math.html?highlight=math#module-math) -- š [Python Random Module](https://docs.python.org/3/library/random.html?highlight=random%20module#module-random) +- š [Python Standard Library](https://docs.python.org/3/library/index.html) +- š [Python Package Index](https://pypi.org/) +- š [Python string methods](https://docs.python.org/3/library/stdtypes.html#textseq) +- š [Python math module](https://docs.python.org/3/library/math.html) +- š [Python random module](https://docs.python.org/3/library/random.html) +- š [Python argparse module](https://docs.python.org/3/library/argparse.html) +- š [Flask](https://flask.palletsprojects.com/) +- š [OpenWeatherMap API](https://openweathermap.org/) --- @@ -63,3 +68,17 @@ - š [Chapter 7 - Dictionaries & Sets](https://github.com/gitdagray/python-course/tree/main/lesson07) - š [Chapter 8 - While Loops & For Loops](https://github.com/gitdagray/python-course/tree/main/lesson08) - š [Chapter 9 - Functions](https://github.com/gitdagray/python-course/tree/main/lesson09) +- š [Chapter 10 - Recursion](https://github.com/gitdagray/python-course/tree/main/lesson10) +- š [Chapter 11 - Scope](https://github.com/gitdagray/python-course/tree/main/lesson11) +- š [Chapter 12 - Closures](https://github.com/gitdagray/python-course/tree/main/lesson12) +- š [Chapter 13 - f-Strings](https://github.com/gitdagray/python-course/tree/main/lesson13) +- š [Chapter 14 - Modules](https://github.com/gitdagray/python-course/tree/main/lesson14) +- š [Chapter 15 - Command Line Arguments](https://github.com/gitdagray/python-course/tree/main/lesson15) +- š [Chapter 16 - Student Challenge](https://github.com/gitdagray/python-course/tree/main/lesson16) +- š [Chapter 17 - Lambda & Higher Order Functions](https://github.com/gitdagray/python-course/tree/main/lesson17) +- š [Chapter 18 - Classes, Objects, Inheritance & Polymorphism](https://github.com/gitdagray/python-course/tree/main/lesson18) +- š [Chapter 19 - Errors & Exception Handling](https://github.com/gitdagray/python-course/tree/main/lesson19) +- š [Chapter 20 - OOP Practice Project](https://github.com/gitdagray/python-course/tree/main/lesson20) +- š [Chapter 21 - Virtual Environments & PIP](https://github.com/gitdagray/python-course/tree/main/lesson21) +- š [Chapter 22 - Working With Files](https://github.com/gitdagray/python-course/tree/main/lesson22) +- š [Chapter 23 - Final Project: Python Web App with Flask](https://github.com/gitdagray/python-course/tree/main/lesson23) diff --git a/lesson10/example.py b/lesson10/example.py new file mode 100644 index 0000000..d9c8713 --- /dev/null +++ b/lesson10/example.py @@ -0,0 +1,11 @@ +value = "y" +count = 0 + +while value: + count += 1 + print(count) + if (count == 5): + break + else: + value = 0 + continue diff --git a/lesson10/recursion.py b/lesson10/recursion.py new file mode 100644 index 0000000..246b35c --- /dev/null +++ b/lesson10/recursion.py @@ -0,0 +1,15 @@ + + +def add_one(num): + + if (num >= 9): + return num + 1 + + total = num + 1 + print(total) + + return add_one(total) + + +mynewtotal = add_one(0) +print(mynewtotal) diff --git a/lesson10/rps3.py b/lesson10/rps3.py new file mode 100644 index 0000000..4568608 --- /dev/null +++ b/lesson10/rps3.py @@ -0,0 +1,58 @@ +import sys +import random +from enum import Enum + + +def play_rps(): + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print("You must enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") + print("Python chose " + str(RPS(computer) + ).replace('RPS.', '').title() + ".\n") + + if player == 1 and computer == 3: + print("š You win!") + elif player == 2 and computer == 1: + print("š You win!") + elif player == 3 and computer == 2: + print("š You win!") + elif player == computer: + print("š² Tie game!") + else: + print("š Python wins!") + + print("\nPlay again?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + sys.exit("Bye! š") + + +play_rps() diff --git a/lesson11/rps4.py b/lesson11/rps4.py new file mode 100644 index 0000000..31ce417 --- /dev/null +++ b/lesson11/rps4.py @@ -0,0 +1,70 @@ +import sys +import random +from enum import Enum + +game_count = 0 + + +def play_rps(): + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print("You must enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") + print("Python chose " + str(RPS(computer) + ).replace('RPS.', '').title() + ".\n") + + def decide_winner(player, computer): + if player == 1 and computer == 3: + return "š You win!" + elif player == 2 and computer == 1: + return "š You win!" + elif player == 3 and computer == 2: + return "š You win!" + elif player == computer: + return "š² Tie game!" + else: + return "š Python wins!" + + game_result = decide_winner(player, computer) + + print(game_result) + + global game_count + game_count += 1 + + print("\nGame count: " + str(game_count)) + + print("\nPlay again?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + sys.exit("Bye! š") + + +play_rps() diff --git a/lesson11/scope.py b/lesson11/scope.py new file mode 100644 index 0000000..d320d0d --- /dev/null +++ b/lesson11/scope.py @@ -0,0 +1,22 @@ + + +name = "Dave" +count = 1 + + +def another(): + color = "blue" + global count + count += 1 + print(count) + + def greeting(name): + nonlocal color + color = "red" + print(color) + print(name) + + greeting("Dave") + + +another() diff --git a/lesson12/closure.py b/lesson12/closure.py new file mode 100644 index 0000000..817f7ca --- /dev/null +++ b/lesson12/closure.py @@ -0,0 +1,29 @@ +# Closure is a function having access to the scope of its parent +# function after the parent function has returned. + +def parent_function(person, coins): + # coins = 3 + + def play_game(): + nonlocal coins + coins -= 1 + + if coins > 1: + print("\n" + person + " has " + str(coins) + " coins left.") + elif coins == 1: + print("\n" + person + " has " + str(coins) + " coin left.") + else: + print("\n" + person + " is out of coins.") + + return play_game + + +tommy = parent_function("Tommy", 3) +jenny = parent_function("Jenny", 5) + +tommy() +tommy() + +jenny() + +tommy() diff --git a/lesson12/rps5.py b/lesson12/rps5.py new file mode 100644 index 0000000..494676f --- /dev/null +++ b/lesson12/rps5.py @@ -0,0 +1,87 @@ +import sys +import random +from enum import Enum + + +def rps(): + game_count = 0 + player_wins = 0 + python_wins = 0 + + def play_rps(): + nonlocal player_wins + nonlocal python_wins + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print("You must enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".") + print("Python chose " + str(RPS(computer) + ).replace('RPS.', '').title() + ".\n") + + def decide_winner(player, computer): + nonlocal player_wins + nonlocal python_wins + if player == 1 and computer == 3: + player_wins += 1 + return "š You win!" + elif player == 2 and computer == 1: + player_wins += 1 + return "š You win!" + elif player == 3 and computer == 2: + player_wins += 1 + return "š You win!" + elif player == computer: + return "š² Tie game!" + else: + python_wins += 1 + return "š Python wins!" + + game_result = decide_winner(player, computer) + + print(game_result) + + nonlocal game_count + game_count += 1 + + print("\nGame count: " + str(game_count)) + print("\nPlayer wins: " + str(player_wins)) + print("\nPython wins: " + str(python_wins)) + + print("\nPlay again?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + sys.exit("Bye! š") + + return play_rps + + +play = rps() + +play() diff --git a/lesson13/f_strings.py b/lesson13/f_strings.py new file mode 100644 index 0000000..06e80fd --- /dev/null +++ b/lesson13/f_strings.py @@ -0,0 +1,59 @@ +person = "Dave" +coins = 3 + +################# +# Concatenating strings + +print("\n" + person + " has " + str(coins) + " coins left.") + +################# +# Previous %s formatting + +message = "\n%s has %s coins left." % (person, coins) +print(message) + +################# +# Previous string.format() method + +message = "\n{} has {} coins left.".format(person, coins) +print(message) + +message = "\n{1} has {0} coins left.".format(coins, person) +print(message) + +message = "\n{person} has {coins} coins left.".format( + coins=coins, person=person +) +print(message) + +player = {'person': 'Dave', 'coins': 3} + +message = "\n{person} has {coins} coins left.".format(**player) +print(message) + +################## +# f-Strings! This is the way. + +message = f"\n{person} has {coins} coins left." +print(message) + +message = f"\n{person} has {2 * 5} coins left." +print(message) + +message = f"\n{person.lower()} has {2 * 5} coins left." +print(message) + +message = f"\n{player['person']} has {2 * 5} coins left." +print(message) + +################## +# You can pass formatting options + +num = 10 +print(f"\n2.25 times {num} is {2.25 * num:.2f}\n") + +for num in range(1, 11): + print(f"2.25 times {num} is {2.25 * num:.2f}") + +for num in range(1, 11): + print(f"{num} divided by 4.52 is {num / 4.52:.2%}") diff --git a/lesson13/rps6.py b/lesson13/rps6.py new file mode 100644 index 0000000..cd12f28 --- /dev/null +++ b/lesson13/rps6.py @@ -0,0 +1,88 @@ +import sys +import random +from enum import Enum + + +def rps(): + game_count = 0 + player_wins = 0 + python_wins = 0 + + def play_rps(): + nonlocal player_wins + nonlocal python_wins + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print("You must enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print(f"\nYou chose {str(RPS(player)).replace('RPS.', '').title()}.") + print( + f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" + ) + + def decide_winner(player, computer): + nonlocal player_wins + nonlocal python_wins + if player == 1 and computer == 3: + player_wins += 1 + return "š You win!" + elif player == 2 and computer == 1: + player_wins += 1 + return "š You win!" + elif player == 3 and computer == 2: + player_wins += 1 + return "š You win!" + elif player == computer: + return "š² Tie game!" + else: + python_wins += 1 + return "š Python wins!" + + game_result = decide_winner(player, computer) + + print(game_result) + + nonlocal game_count + game_count += 1 + + print(f"\nGame count: {str(game_count)}") + print(f"\nPlayer wins: {str(player_wins)}") + print(f"\nPython wins: {str(python_wins)}") + + print("\nPlay again?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + sys.exit("Bye! š") + + return play_rps + + +play = rps() + +play() diff --git a/lesson14/kansas.py b/lesson14/kansas.py new file mode 100644 index 0000000..7829fe0 --- /dev/null +++ b/lesson14/kansas.py @@ -0,0 +1,26 @@ +from random import choice + +capital = "Topeka" + +bird = "Western Meadowlark" + +flower = "Sunflower" + +song = "Home on the Range" + + +def randomfunfact(): + funfacts = [ + "Kansas is considered flat, but it does have a mountain.", + "Wichita is the largest city in the state, but many would guess that it is Kansas City.", + "A considerable portion of Kansas City is actually in Missouri.", + "Most Kansans are annoyed by Wizard of Oz references from people outside of Kansas." + ] + + index = choice("0123") + + print(funfacts[int(index)]) + + +if __name__ == "__main__": + randomfunfact() diff --git a/lesson14/modules.py b/lesson14/modules.py new file mode 100644 index 0000000..1af30da --- /dev/null +++ b/lesson14/modules.py @@ -0,0 +1,21 @@ + + +from math import pi +import sys +import random as rdm +from enum import Enum +import kansas +from rps7 import rock_paper_scissors + +print(pi) + +# for item in dir(rdm): +# print(item) + +print(kansas.capital) +kansas.randomfunfact() + +print(__name__) +print(kansas.__name__) + +rock_paper_scissors() diff --git a/lesson14/rps7.py b/lesson14/rps7.py new file mode 100644 index 0000000..dea1216 --- /dev/null +++ b/lesson14/rps7.py @@ -0,0 +1,89 @@ +import sys +import random +from enum import Enum + + +def rps(): + game_count = 0 + player_wins = 0 + python_wins = 0 + + def play_rps(): + nonlocal player_wins + nonlocal python_wins + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print("You must enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print(f"\nYou chose {str(RPS(player)).replace('RPS.', '').title()}.") + print( + f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" + ) + + def decide_winner(player, computer): + nonlocal player_wins + nonlocal python_wins + if player == 1 and computer == 3: + player_wins += 1 + return "š You win!" + elif player == 2 and computer == 1: + player_wins += 1 + return "š You win!" + elif player == 3 and computer == 2: + player_wins += 1 + return "š You win!" + elif player == computer: + return "š² Tie game!" + else: + python_wins += 1 + return "š Python wins!" + + game_result = decide_winner(player, computer) + + print(game_result) + + nonlocal game_count + game_count += 1 + + print(f"\nGame count: {str(game_count)}") + print(f"\nPlayer wins: {str(player_wins)}") + print(f"\nPython wins: {str(python_wins)}") + + print("\nPlay again?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + sys.exit("Bye! š") + + return play_rps + + +rock_paper_scissors = rps() + +if __name__ == "__main__": + rock_paper_scissors() diff --git a/lesson15/hello_person.py b/lesson15/hello_person.py new file mode 100644 index 0000000..dc6fa2c --- /dev/null +++ b/lesson15/hello_person.py @@ -0,0 +1,31 @@ +def hello(name, lang): + greetings = { + "English": "Hello", + "Spanish": "Hola", + "German": "Hallo", + } + msg = f"{greetings[lang]} {name}!" + print(msg) + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser( + description="Provides a personal greeting." + ) + + parser.add_argument( + "-n", "--name", metavar="name", + required=True, help="The name of the person to greet." + ) + + parser.add_argument( + "-l", "--lang", metavar="language", + required=True, choices=["English", "Spanish", "German"], + help="The language of the greeting." + ) + + args = parser.parse_args() + + hello(args.name, args.lang) diff --git a/lesson15/rps8.py b/lesson15/rps8.py new file mode 100644 index 0000000..aaf1d73 --- /dev/null +++ b/lesson15/rps8.py @@ -0,0 +1,105 @@ +import sys +import random +from enum import Enum + + +def rps(name='PlayerOne'): + game_count = 0 + player_wins = 0 + python_wins = 0 + + def play_rps(): + nonlocal name + nonlocal player_wins + nonlocal python_wins + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + f"\n{name}, please enter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print(f"{name}, please enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print(f"\n{name}, you chose {str(RPS(player)).replace('RPS.', '').title()}.") + print( + f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" + ) + + def decide_winner(player, computer): + nonlocal name + nonlocal player_wins + nonlocal python_wins + if player == 1 and computer == 3: + player_wins += 1 + return f"š {name}, you win!" + elif player == 2 and computer == 1: + player_wins += 1 + return f"š {name}, you win!" + elif player == 3 and computer == 2: + player_wins += 1 + return f"š {name}, you win!" + elif player == computer: + return "š² Tie game!" + else: + python_wins += 1 + return f"š Python wins!\nSorry, {name}..š¢" + + game_result = decide_winner(player, computer) + + print(game_result) + + nonlocal game_count + game_count += 1 + + print(f"\nGame count: {game_count}") + print(f"\n{name}'s wins: {player_wins}") + print(f"\nPython wins: {python_wins}") + + print(f"\nPlay again, {name}?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + sys.exit(f"Bye {name}! š") + + return play_rps + + + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Provides a personalized game experience." + ) + + parser.add_argument( + "-n", "--name", metavar="name", + required=True, help="The name of the person playing the game." + ) + + args = parser.parse_args() + + rock_paper_scissors = rps(args.name) + rock_paper_scissors() diff --git a/lesson16/arcade.py b/lesson16/arcade.py new file mode 100644 index 0000000..c4f35f6 --- /dev/null +++ b/lesson16/arcade.py @@ -0,0 +1,50 @@ +import sys +from rps import rps +from guess_number import guess_number + + +def play_game(name='PlayerOne'): + welcome_back = False + + while True: + if welcome_back == True: + print(f"\n{name}, welcome back to the Arcade menu.") + + playerchoice = input( + "\nPlease choose a game:\n1 = Rock Paper Scissors\n2 = Guess My Number\n\nOr press \"x\" to exit the Arcade\n\n" + ) + + if playerchoice not in ["1", "2", "x"]: + print(f"\n{name}, please enter 1, 2, or x.") + return play_game(name) + + welcome_back = True + + if playerchoice == "1": + rock_paper_scissors = rps(name) + rock_paper_scissors() + elif playerchoice == "2": + guess_my_number = guess_number(name) + guess_my_number() + else: + print("\nSee you next time!\n") + sys.exit(f"Bye {name}! š") + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Provides a personalized game experience." + ) + + parser.add_argument( + '-n', '--name', metavar='name', + required=True, help='The name of the person playing the game.' + ) + + args = parser.parse_args() + + print(f"\n{args.name}, welcome to the Arcade! š¤") + + play_game(args.name) diff --git a/lesson16/guess_number.py b/lesson16/guess_number.py new file mode 100644 index 0000000..68e5ed1 --- /dev/null +++ b/lesson16/guess_number.py @@ -0,0 +1,89 @@ +import sys +import random + + +def guess_number(name='PlayerOne'): + game_count = 0 + player_wins = 0 + + def play_guess_number(): + nonlocal name + nonlocal player_wins + + playerchoice = input( + f"\n{name}, guess which number I'm thinking of... 1, 2, or 3.\n\n") + + if playerchoice not in ["1", "2", "3"]: + print(f"{name}, please enter 1, 2, or 3.") + return play_guess_number() + + computerchoice = random.choice("123") + + print(f"\n{name}, you chose {playerchoice}.") + print( + f"I was thinking about the number {computerchoice}.\n" + ) + + player = int(playerchoice) + + computer = int(computerchoice) + + def decide_winner(player, computer): + nonlocal name + nonlocal player_wins + + if player == computer: + player_wins += 1 + return f"š {name}, you win!" + else: + return f"Sorry, {name}. Better luck next time. š¢" + + game_result = decide_winner(player, computer) + + print(game_result) + + nonlocal game_count + game_count += 1 + + print(f"\nGame count: {game_count}") + print(f"\n{name}'s wins: {player_wins}") + print(f"\nYour winning percentage: {player_wins/game_count:.2%}") + + print(f"\nPlay again, {name}?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_guess_number() + else: + print("\nšššš") + print("Thank you for playing!\n") + if __name__ == "__main__": + sys.exit(f"Bye {name}! š") + else: + return + + return play_guess_number + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Provides a personalized game experience." + ) + + parser.add_argument( + '-n', '--name', metavar='name', + required=True, help='The name of the person playing the game.' + ) + + args = parser.parse_args() + + guess_my_number = guess_number(args.name) + guess_my_number() diff --git a/lesson16/rps.py b/lesson16/rps.py new file mode 100644 index 0000000..289d5d7 --- /dev/null +++ b/lesson16/rps.py @@ -0,0 +1,107 @@ +import sys +import random +from enum import Enum + + +def rps(name='PlayerOne'): + game_count = 0 + player_wins = 0 + python_wins = 0 + + def play_rps(): + nonlocal name + nonlocal player_wins + nonlocal python_wins + + class RPS(Enum): + ROCK = 1 + PAPER = 2 + SCISSORS = 3 + + playerchoice = input( + f"\n{name}, please enter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + + if playerchoice not in ["1", "2", "3"]: + print(f"{name}, please enter 1, 2, or 3.") + return play_rps() + + player = int(playerchoice) + + computerchoice = random.choice("123") + + computer = int(computerchoice) + + print(f"\n{name}, you chose {str(RPS(player)).replace('RPS.', '').title()}.") + print( + f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n" + ) + + def decide_winner(player, computer): + nonlocal name + nonlocal player_wins + nonlocal python_wins + if player == 1 and computer == 3: + player_wins += 1 + return f"š {name}, you win!" + elif player == 2 and computer == 1: + player_wins += 1 + return f"š {name}, you win!" + elif player == 3 and computer == 2: + player_wins += 1 + return f"š {name}, you win!" + elif player == computer: + return "š² Tie game!" + else: + python_wins += 1 + return f"š Python wins!\nSorry, {name}.. š¢" + + game_result = decide_winner(player, computer) + + print(game_result) + + nonlocal game_count + game_count += 1 + + print(f"\nGame count: {game_count}") + print(f"\nPython wins: {python_wins}") + print(f"\n{name}'s wins: {player_wins}") + + print(f"\nPlay again, {name}?") + + while True: + playagain = input("\nY for Yes or \nQ to Quit\n") + if playagain.lower() not in ["y", "q"]: + continue + else: + break + + if playagain.lower() == "y": + return play_rps() + else: + print("\nšššš") + print("Thank you for playing!\n") + if __name__ == "__main__": + sys.exit(f"Bye {name}! š") + else: + return + + return play_rps + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Provides a personalized game experience." + ) + + parser.add_argument( + '-n', '--name', metavar='name', + required=True, help='The name of the person playing the game.' + ) + + args = parser.parse_args() + + rock_paper_scissors = rps(args.name) + rock_paper_scissors() + diff --git a/lesson17/lambda.py b/lesson17/lambda.py new file mode 100644 index 0000000..b205ca8 --- /dev/null +++ b/lesson17/lambda.py @@ -0,0 +1,66 @@ +from functools import reduce +def squared(num): return num * num +# lambda num : num * num + + +print(squared(2)) + + +def add_two(num): return num + 2 +# lambda num : num + 2 + + +print(add_two(12)) + + +def sum_total(a, b): return a + b +# lambda a, b : a + b + + +print(sum_total(10, 8)) + +####################### + + +def funcBuilder(x): + return lambda num: num + x + + +add_ten = funcBuilder(10) +add_twenty = funcBuilder(20) + +print(add_ten(7)) +print(add_twenty(7)) + +######################## + + +numbers = [3, 7, 12, 18, 20, 21] + +squared_nums = map(lambda num: num * num, numbers) + +print(list(squared_nums)) + +############################### + +odd_nums = filter(lambda num: num % 2 != 0, numbers) + +print(list(odd_nums)) + +############################# + + +numbers = [1, 2, 3, 4, 5, 1] + +total = reduce(lambda acc, curr: acc + curr, numbers, 10) + +print(total) + +print(sum(numbers, 10)) + + +names = ['Dave Gray', 'Sara Ito', 'John Jacob Jingleheimerschmidt'] + +char_count = reduce(lambda acc, curr: acc + len(curr), names, 0) + +print(char_count) diff --git a/lesson18/classes.py b/lesson18/classes.py new file mode 100644 index 0000000..ef563aa --- /dev/null +++ b/lesson18/classes.py @@ -0,0 +1,58 @@ +class Vehicle: + def __init__(self, make, model): + self.make = make + self.model = model + + def moves(self): + print('Moves along..') + + def get_make_model(self): + print(f"I'm a {self.make} {self.model}.") + + +my_car = Vehicle('Tesla', 'Model 3') + +# print(my_car.make) +# print(my_car.model) +my_car.get_make_model() +my_car.moves() + +your_car = Vehicle('Cadillac', 'Escalade') +your_car.get_make_model() +your_car.moves() + + +class Airplane(Vehicle): + def __init__(self, make, model, faa_id): + super().__init__(make, model) + self.faa_id = faa_id + + def moves(self): + print('Flies along..') + + +class Truck(Vehicle): + def moves(self): + print('Rumbles along..') + + +class GolfCart(Vehicle): + pass + + +cessna = Airplane('Cessna', 'Skyhawk', 'N-12345') +mack = Truck('Mack', 'Pinnacle') +golfwagon = GolfCart('Yamaha', 'GC100') + +cessna.get_make_model() +cessna.moves() +mack.get_make_model() +mack.moves() +golfwagon.get_make_model() +golfwagon.moves() + +print('\n\n') + +for v in (my_car, your_car, cessna, mack, golfwagon): + v.get_make_model() + v.moves() diff --git a/lesson19/exceptions.py b/lesson19/exceptions.py new file mode 100644 index 0000000..f29334b --- /dev/null +++ b/lesson19/exceptions.py @@ -0,0 +1,21 @@ +class JustNotCoolError(Exception): + pass + + +x = 2 +try: + raise JustNotCoolError("This just isn't cool, man.") + # raise Exception("I'm a custom exception!") + # print(x / 0) + # if not type(x) is str: + # raise TypeError("Only strings are allowed.") +except NameError: + print('NameError means something is probably undefined.') +except ZeroDivisionError: + print('Please do not divide by zero.') +except Exception as error: + print(error) +else: + print('No errors!') +finally: + print("I'm going to print with or without an error.") diff --git a/lesson20/bank_accounts.py b/lesson20/bank_accounts.py new file mode 100644 index 0000000..e96035e --- /dev/null +++ b/lesson20/bank_accounts.py @@ -0,0 +1,65 @@ +class BalanceException(Exception): + pass + + +class BankAccount: + def __init__(self, initial_amount, acct_name): + self.balance = initial_amount + self.name = acct_name + print( + f"\nAccount '{self.name}' created.\nBalance = ${self.balance:.2f}") + + def get_balance(self): + print(f"\nAccount '{self.name}' balance = ${self.balance:.2f}") + + def deposit(self, amount): + self.balance = self.balance + amount + print("\nDeposit complete.") + self.get_balance() + + def viable_transaction(self, amount): + if self.balance >= amount: + return + else: + raise BalanceException( + f"\nSorry, account '{self.name}' only has a balance of ${self.balance:.2f}" + ) + + def withdraw(self, amount): + try: + self.viable_transaction(amount) + self.balance = self.balance - amount + print("\nWithdraw complete.") + self.get_balance() + except BalanceException as error: + print(f'\nWithdraw interrupted: {error}') + + def transfer(self, amount, account): + try: + print('\n**********\n\nBeginning Transfer.. š') + self.viable_transaction(amount) + self.withdraw(amount) + account.deposit(amount) + print('\nTransfer complete! ā \n\n**********') + except BalanceException as error: + print(f'\nTransfer interrupted. ā {error}') + +class InterestRewardsAcct(BankAccount): + def deposit(self, amount): + self.balance = self.balance + (amount * 1.05) + print("\nDeposit complete.") + self.get_balance() + +class SavingsAcct(InterestRewardsAcct): + def __init__(self, initial_amount, acct_name): + super().__init__(initial_amount, acct_name) + self.fee = 5 + + def withdraw(self, amount): + try: + self.viable_transaction(amount + self.fee) + self.balance = self.balance - (amount + self.fee) + print("\nWithdraw completed.") + self.get_balance() + except BalanceException as error: + print(f'\nWithdraw interrupted: {error}') diff --git a/lesson20/oop_project.py b/lesson20/oop_project.py new file mode 100644 index 0000000..1dc589f --- /dev/null +++ b/lesson20/oop_project.py @@ -0,0 +1,32 @@ +from bank_accounts import * + +Dave = BankAccount(1000, "Dave") +Sara = BankAccount(2000, "Sara") + +Dave.get_balance() +Sara.get_balance() + +Sara.deposit(500) + +Dave.withdraw(10000) +Dave.withdraw(10) + +Dave.transfer(10000, Sara) +Dave.transfer(100, Sara) + +Jim = InterestRewardsAcct(1000, "Jim") + +Jim.get_balance() + +Jim.deposit(100) + +Jim.transfer(100, Dave) + +Blaze = SavingsAcct(1000, "Blaze") + +Blaze.get_balance() + +Blaze.deposit(100) + +Blaze.transfer(10000, Sara) +Blaze.transfer(1000, Sara) diff --git a/lesson21/.gitignore b/lesson21/.gitignore new file mode 100644 index 0000000..8d19362 --- /dev/null +++ b/lesson21/.gitignore @@ -0,0 +1,2 @@ +.venv +.env diff --git a/lesson21/requirements.txt b/lesson21/requirements.txt new file mode 100644 index 0000000..e07fa87 --- /dev/null +++ b/lesson21/requirements.txt @@ -0,0 +1,6 @@ +certifi==2023.5.7 +charset-normalizer==3.1.0 +idna==3.4 +python-dotenv==1.0.0 +requests==2.31.0 +urllib3==2.0.3 diff --git a/lesson21/weather.py b/lesson21/weather.py new file mode 100644 index 0000000..b5966f8 --- /dev/null +++ b/lesson21/weather.py @@ -0,0 +1,29 @@ +import requests +from dotenv import load_dotenv +import os +from pprint import pprint + +load_dotenv() + + +def get_current_weather(): + print('\n*** Get Current Weather Conditions ***\n') + + city = input("\nPlease enter a city name:\n") + + request_url = f'https://api.openweathermap.org/data/2.5/weather?appid={os.getenv("API_KEY")}&q={city}&units=imperial' + + # print(request_url) + + weather_data = requests.get(request_url).json() + + # pprint(weather_data) + + print(f'\nCurrent weather for {weather_data["name"]}:') + print(f'\nThe temp is {weather_data["main"]["temp"]:.1f}°') + print( + f'\n{weather_data["weather"][0]["description"].capitalize()} and feels like {weather_data["main"]["feels_like"]:.1f}°\n') + + +if __name__ == "__main__": + get_current_weather() diff --git a/lesson22/context.txt b/lesson22/context.txt new file mode 100644 index 0000000..cc7ab2b --- /dev/null +++ b/lesson22/context.txt @@ -0,0 +1,4 @@ +Dave +Jane +Eddie +Jimmie diff --git a/lesson22/files.py b/lesson22/files.py new file mode 100644 index 0000000..e428a2f --- /dev/null +++ b/lesson22/files.py @@ -0,0 +1,73 @@ +import os +# r = Read +# a = Append +# w = Write +# x = Create + +# Read - error if it doesn't exist + +f = open("names.txt") +# print(f.read()) +# print(f.read(4)) + +# print(f.readline()) +# print(f.readline()) + +for line in f: + print(line) + +f.close() + +try: + f = open("names.txt") + print(f.read()) +except: + print("The file you want to read doesn't exist") +finally: + f.close() + +# Append - creates the file if it doesn't exist +f = open("names.txt", "a") +f.write("Neil\n") +f.close() + +f = open("names.txt") +print(f.read()) +f.close() + +# Write (overwrite) +f = open("context.txt", "w") +f.write("I deleted all of the context") +f.close() + +f = open("context.txt") +print(f.read()) +f.close() + +# Two ways to create a new file + +# Opens a file for writing, creates the file if it does not exist +f = open("name_list.txt", "w") +f.close() + +# Creates the specified file, but returns an error if the file exists +if not os.path.exists("dave.txt"): + f = open("dave.txt", "x") + f.close() + +# Delete a file + +# avoid an error if it doesn't exist +if os.path.exists("dave.txt"): + os.remove("dave.txt") +else: + print("The file you wish to delete does not exist") + + +# with has built-in implicit exception handling +# close() will be automatically called +with open("more_names.txt") as f: + content = f.read() + +with open("names.txt", "w") as f: + f.write(content) diff --git a/lesson22/more_names.txt b/lesson22/more_names.txt new file mode 100644 index 0000000..cc7ab2b --- /dev/null +++ b/lesson22/more_names.txt @@ -0,0 +1,4 @@ +Dave +Jane +Eddie +Jimmie diff --git a/lesson22/names.txt b/lesson22/names.txt new file mode 100644 index 0000000..cc7ab2b --- /dev/null +++ b/lesson22/names.txt @@ -0,0 +1,4 @@ +Dave +Jane +Eddie +Jimmie diff --git a/lesson23/.gitignore b/lesson23/.gitignore new file mode 100644 index 0000000..32ac21b --- /dev/null +++ b/lesson23/.gitignore @@ -0,0 +1,3 @@ +.venv +.env +__pycache__ diff --git a/lesson23/requirements.txt b/lesson23/requirements.txt new file mode 100644 index 0000000..6dee033 --- /dev/null +++ b/lesson23/requirements.txt @@ -0,0 +1,15 @@ +blinker==1.6.2 +certifi==2023.5.7 +charset-normalizer==3.2.0 +click==8.1.5 +colorama==0.4.6 +Flask==2.3.2 +idna==3.4 +itsdangerous==2.1.2 +Jinja2==3.1.2 +MarkupSafe==2.1.3 +python-dotenv==1.0.0 +requests==2.31.0 +urllib3==2.0.3 +waitress==2.1.2 +Werkzeug==2.3.6 diff --git a/lesson23/server.py b/lesson23/server.py new file mode 100644 index 0000000..87894af --- /dev/null +++ b/lesson23/server.py @@ -0,0 +1,39 @@ +from flask import Flask, render_template, request +from weather import get_current_weather +from waitress import serve + +app = Flask(__name__) + + +@app.route('/') +@app.route('/index') +def index(): + return render_template('index.html') + + +@app.route('/weather') +def get_weather(): + city = request.args.get('city') + + # Check for empty strings or string with only spaces + if not bool(city.strip()): + # You could render "City Not Found" instead like we do below + city = "Kansas City" + + weather_data = get_current_weather(city) + + # City is not found by API + if not weather_data['cod'] == 200: + return render_template('city-not-found.html') + + return render_template( + "weather.html", + title=weather_data["name"], + status=weather_data["weather"][0]["description"].capitalize(), + temp=f"{weather_data['main']['temp']:.1f}", + feels_like=f"{weather_data['main']['feels_like']:.1f}" + ) + + +if __name__ == "__main__": + serve(app, host="0.0.0.0", port=8000) diff --git a/lesson23/static/styles/style.css b/lesson23/static/styles/style.css new file mode 100644 index 0000000..5a11238 --- /dev/null +++ b/lesson23/static/styles/style.css @@ -0,0 +1,23 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + padding: 2rem; + background-color: #333; + color: whitesmoke; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + font-size: 2rem; +} + +input, button { + font-size: 2rem; + padding: 1rem; + border-radius: 10px; +} \ No newline at end of file diff --git a/lesson23/templates/city-not-found.html b/lesson23/templates/city-not-found.html new file mode 100644 index 0000000..ba5cc62 --- /dev/null +++ b/lesson23/templates/city-not-found.html @@ -0,0 +1,20 @@ + + + +
+ + +{{ status }} and {{ temp }} °
+Feels like {{ feels_like }} °
+ + + + + \ No newline at end of file diff --git a/lesson23/weather.py b/lesson23/weather.py new file mode 100644 index 0000000..655ff04 --- /dev/null +++ b/lesson23/weather.py @@ -0,0 +1,31 @@ +from dotenv import load_dotenv +from pprint import pprint +import requests +import os + +load_dotenv() + + +def get_current_weather(city="Kansas City"): + + request_url = f'http://api.openweathermap.org/data/2.5/weather?appid={os.getenv("API_KEY")}&q={city}&units=imperial' + + weather_data = requests.get(request_url).json() + + return weather_data + + +if __name__ == "__main__": + print('\n*** Get Current Weather Conditions ***\n') + + city = input("\nPlease enter a city name: ") + + # Check for empty strings or string with only spaces + # This step is not required here + # if not bool(city.strip()): + # city = "Kansas City" + + weather_data = get_current_weather(city) + + print("\n") + pprint(weather_data)