From 155a1a5626ede8c272531008698ea3410e495108 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 17 Apr 2023 15:20:10 -0500 Subject: [PATCH 01/18] Added lesson 10 --- README.md | 1 + lesson10/example.py | 11 ++++++++ lesson10/recursion.py | 15 +++++++++++ lesson10/rps3.py | 58 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 lesson10/example.py create mode 100644 lesson10/recursion.py create mode 100644 lesson10/rps3.py diff --git a/README.md b/README.md index cfc92d6..52c514c 100644 --- a/README.md +++ b/README.md @@ -63,3 +63,4 @@ - šŸ”— [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) 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() From 81e941715094603b62394d664da04a6d6138bd82 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 25 Apr 2023 14:38:05 -0500 Subject: [PATCH 02/18] Added lesson 11 --- lesson11/rps4.py | 70 +++++++++++++++++++++++++++++++++++++++++++++++ lesson11/scope.py | 22 +++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 lesson11/rps4.py create mode 100644 lesson11/scope.py 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() From a57bcc9180bde554c73e06414d4bd2c8bc4c85c1 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 25 Apr 2023 14:38:39 -0500 Subject: [PATCH 03/18] Updated README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 52c514c..6b6e3ce 100644 --- a/README.md +++ b/README.md @@ -64,3 +64,4 @@ - šŸ”— [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) From 4f139c6ba157e877797a2c7be761ecfc7e506ef8 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 1 May 2023 15:26:10 -0500 Subject: [PATCH 04/18] Added lesson 12 --- README.md | 1 + lesson12/closure.py | 29 +++++++++++++++ lesson12/rps5.py | 87 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 lesson12/closure.py create mode 100644 lesson12/rps5.py diff --git a/README.md b/README.md index 6b6e3ce..0feffc7 100644 --- a/README.md +++ b/README.md @@ -65,3 +65,4 @@ - šŸ”— [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) 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() From 007ea906b65b1ec4342f27885511ed568aa95b03 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Thu, 11 May 2023 16:13:06 -0500 Subject: [PATCH 05/18] Added lesson 13 --- README.md | 1 + lesson13/f_strings.py | 59 +++++++++++++++++++++++++++++ lesson13/rps6.py | 88 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 148 insertions(+) create mode 100644 lesson13/f_strings.py create mode 100644 lesson13/rps6.py diff --git a/README.md b/README.md index 0feffc7..a6becdb 100644 --- a/README.md +++ b/README.md @@ -66,3 +66,4 @@ - šŸ”— [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) 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() From 3efd214ec4e659973b2962fd3f71e6bc73d648cf Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 16 May 2023 07:34:49 -0500 Subject: [PATCH 06/18] Added lesson 14 --- README.md | 1 + lesson14/kansas.py | 26 +++++++++++++ lesson14/modules.py | 21 +++++++++++ lesson14/rps7.py | 89 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 137 insertions(+) create mode 100644 lesson14/kansas.py create mode 100644 lesson14/modules.py create mode 100644 lesson14/rps7.py diff --git a/README.md b/README.md index a6becdb..f794f92 100644 --- a/README.md +++ b/README.md @@ -67,3 +67,4 @@ - šŸ”— [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) 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() From a8fa067a50530b86d5b2519184c01e361cf3d49e Mon Sep 17 00:00:00 2001 From: gitdagray Date: Sun, 21 May 2023 23:16:22 -0500 Subject: [PATCH 07/18] Added lesson 15 --- .gitignore | 1 + README.md | 10 ++-- lesson15/hello_person.py | 31 ++++++++++++ lesson15/rps8.py | 105 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 144 insertions(+), 3 deletions(-) create mode 100644 .gitignore create mode 100644 lesson15/hello_person.py create mode 100644 lesson15/rps8.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..722d5e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vscode diff --git a/README.md b/README.md index f794f92..958dfe8 100644 --- a/README.md +++ b/README.md @@ -46,9 +46,12 @@ ### šŸ“š 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) --- @@ -68,3 +71,4 @@ - šŸ”— [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) 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() From 6a426794708c20bddae59916e4509b70ef834267 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 29 May 2023 22:36:28 -0500 Subject: [PATCH 08/18] Added lesson 16 --- .gitignore | 1 + README.md | 1 + lesson16/arcade.py | 50 ++++++++++++++++++ lesson16/guess_number.py | 89 ++++++++++++++++++++++++++++++++ lesson16/rps.py | 107 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 248 insertions(+) create mode 100644 lesson16/arcade.py create mode 100644 lesson16/guess_number.py create mode 100644 lesson16/rps.py diff --git a/.gitignore b/.gitignore index 722d5e7..4edd750 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ .vscode +__pycache__ \ No newline at end of file diff --git a/README.md b/README.md index 958dfe8..3c893cf 100644 --- a/README.md +++ b/README.md @@ -72,3 +72,4 @@ - šŸ”— [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) 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() + From 6506adc738d62c124398777f735c3db4901d016d Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 5 Jun 2023 16:56:10 -0500 Subject: [PATCH 09/18] Added lesson 17 --- README.md | 1 + lesson17/lambda.py | 66 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 lesson17/lambda.py diff --git a/README.md b/README.md index 3c893cf..4a56a43 100644 --- a/README.md +++ b/README.md @@ -73,3 +73,4 @@ - šŸ”— [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) 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) From a90f743d11a638fa71297f0f9488e6da4b76ad77 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 12 Jun 2023 21:54:53 -0500 Subject: [PATCH 10/18] lesson 18 added --- README.md | 1 + lesson18/classes.py | 58 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 lesson18/classes.py diff --git a/README.md b/README.md index 4a56a43..4e4994a 100644 --- a/README.md +++ b/README.md @@ -74,3 +74,4 @@ - šŸ”— [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) 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() From 58b47ed14e4b5279d7a8e57eef97bea8735dc1a9 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 19 Jun 2023 18:03:08 -0500 Subject: [PATCH 11/18] Added lesson 19 --- README.md | 1 + lesson19/exceptions.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 lesson19/exceptions.py diff --git a/README.md b/README.md index 4e4994a..54d5396 100644 --- a/README.md +++ b/README.md @@ -75,3 +75,4 @@ - šŸ”— [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) 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.") From 3b540d293c735420e9acb00fa5face7a57547163 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 27 Jun 2023 07:21:53 -0500 Subject: [PATCH 12/18] Added lesson 20 --- README.md | 1 + lesson20/bank_accounts.py | 65 +++++++++++++++++++++++++++++++++++++++ lesson20/oop_project.py | 32 +++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 lesson20/bank_accounts.py create mode 100644 lesson20/oop_project.py diff --git a/README.md b/README.md index 54d5396..f5edb23 100644 --- a/README.md +++ b/README.md @@ -76,3 +76,4 @@ - šŸ”— [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) 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) From 2dd9f6a47cd04acb999e4b004a03eec38d1e2312 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 3 Jul 2023 17:17:39 -0500 Subject: [PATCH 13/18] Added lesson 21 --- .gitignore | 4 +++- README.md | 1 + lesson21/.gitignore | 2 ++ lesson21/requirements.txt | 6 ++++++ lesson21/weather.py | 29 +++++++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 lesson21/.gitignore create mode 100644 lesson21/requirements.txt create mode 100644 lesson21/weather.py diff --git a/.gitignore b/.gitignore index 4edd750..b431de6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .vscode -__pycache__ \ No newline at end of file +__pycache__ +.venv +.env diff --git a/README.md b/README.md index f5edb23..3e839ec 100644 --- a/README.md +++ b/README.md @@ -77,3 +77,4 @@ - šŸ”— [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) 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() From a724cf1a244dc90c96020d9164c5e30ec2b93b84 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Mon, 10 Jul 2023 20:07:50 -0500 Subject: [PATCH 14/18] Added lesson 22 --- README.md | 1 + lesson22/context.txt | 4 +++ lesson22/files.py | 73 +++++++++++++++++++++++++++++++++++++++++ lesson22/more_names.txt | 4 +++ lesson22/names.txt | 4 +++ 5 files changed, 86 insertions(+) create mode 100644 lesson22/context.txt create mode 100644 lesson22/files.py create mode 100644 lesson22/more_names.txt create mode 100644 lesson22/names.txt diff --git a/README.md b/README.md index 3e839ec..199f9d5 100644 --- a/README.md +++ b/README.md @@ -78,3 +78,4 @@ - šŸ”— [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) 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 From 607109da630a894019626fb80289f13b6dc438d5 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 18 Jul 2023 07:48:27 -0500 Subject: [PATCH 15/18] Added lesson 23 --- README.md | 5 ++++- lesson23 | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) create mode 160000 lesson23 diff --git a/README.md b/README.md index 199f9d5..d807edd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # "Python for Beginners" -### Full Course - ?? Chapters +### Full Course - 23 Chapters --- @@ -52,6 +52,8 @@ - šŸ”— [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/) --- @@ -79,3 +81,4 @@ - šŸ”— [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/lesson23 b/lesson23 new file mode 160000 index 0000000..2f93c5c --- /dev/null +++ b/lesson23 @@ -0,0 +1 @@ +Subproject commit 2f93c5cdda8324b4ceaee88f755924cbeb5c852e From 07dab2d957bfce7ea12c346e51c135ae1fa2bbfc Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 18 Jul 2023 07:50:45 -0500 Subject: [PATCH 16/18] Added lesson 23 --- lesson23 | 1 - lesson23/.gitignore | 3 ++ lesson23/requirements.txt | 15 ++++++++++ lesson23/server.py | 38 ++++++++++++++++++++++++++ lesson23/static/styles/style.css | 23 ++++++++++++++++ lesson23/templates/city-not-found.html | 20 ++++++++++++++ lesson23/templates/index.html | 19 +++++++++++++ lesson23/templates/weather.html | 22 +++++++++++++++ lesson23/weather.py | 30 ++++++++++++++++++++ 9 files changed, 170 insertions(+), 1 deletion(-) delete mode 160000 lesson23 create mode 100644 lesson23/.gitignore create mode 100644 lesson23/requirements.txt create mode 100644 lesson23/server.py create mode 100644 lesson23/static/styles/style.css create mode 100644 lesson23/templates/city-not-found.html create mode 100644 lesson23/templates/index.html create mode 100644 lesson23/templates/weather.html create mode 100644 lesson23/weather.py diff --git a/lesson23 b/lesson23 deleted file mode 160000 index 2f93c5c..0000000 --- a/lesson23 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2f93c5cdda8324b4ceaee88f755924cbeb5c852e 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..815aa78 --- /dev/null +++ b/lesson23/server.py @@ -0,0 +1,38 @@ +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()): + 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 @@ + + + + + + + City Not Found + + + + +

City Not Found

+

Try Again?

+
+ + +
+ + + \ No newline at end of file diff --git a/lesson23/templates/index.html b/lesson23/templates/index.html new file mode 100644 index 0000000..cdb9244 --- /dev/null +++ b/lesson23/templates/index.html @@ -0,0 +1,19 @@ + + + + + + + Get Weather Conditions + + + + +

Get Weather Conditions

+
+ + +
+ + + \ No newline at end of file diff --git a/lesson23/templates/weather.html b/lesson23/templates/weather.html new file mode 100644 index 0000000..76a4355 --- /dev/null +++ b/lesson23/templates/weather.html @@ -0,0 +1,22 @@ + + + + + + + {{ title }} Weather + + + + +

{{ title }} Weather

+

{{ 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..0387d69 --- /dev/null +++ b/lesson23/weather.py @@ -0,0 +1,30 @@ +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 + if not bool(city.strip()): + city = "Kansas City" + + weather_data = get_current_weather(city) + + print("\n") + pprint(weather_data) From 4a605684840d30dd2a2287a45f5860295733b799 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 18 Jul 2023 07:58:40 -0500 Subject: [PATCH 17/18] added comments --- lesson23/server.py | 1 + lesson23/weather.py | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lesson23/server.py b/lesson23/server.py index 815aa78..87894af 100644 --- a/lesson23/server.py +++ b/lesson23/server.py @@ -17,6 +17,7 @@ def get_weather(): # 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) diff --git a/lesson23/weather.py b/lesson23/weather.py index 0387d69..655ff04 100644 --- a/lesson23/weather.py +++ b/lesson23/weather.py @@ -21,8 +21,9 @@ def get_current_weather(city="Kansas City"): city = input("\nPlease enter a city name: ") # Check for empty strings or string with only spaces - if not bool(city.strip()): - city = "Kansas City" + # This step is not required here + # if not bool(city.strip()): + # city = "Kansas City" weather_data = get_current_weather(city) From 509f657240e1af1ae04956e593628025cae5f957 Mon Sep 17 00:00:00 2001 From: gitdagray Date: Tue, 18 Jul 2023 13:12:10 -0500 Subject: [PATCH 18/18] Update link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d807edd..9edfc90 100644 --- a/README.md +++ b/README.md @@ -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.