From 33ea81cdcf1b7524ef2ce9e439757f07d5ed8a7d Mon Sep 17 00:00:00 2001 From: Dmitriy Malayev Date: Sat, 31 Aug 2024 16:51:59 -0400 Subject: [PATCH 1/3] updated --- .DS_Store | Bin 0 -> 10244 bytes lesson04/data_types.py | 176 +++++++++++++++++++-------------------- lesson05/rps.py | 7 +- lesson06/lists.py | 93 ++++++++++++--------- lesson07/dictionaries.py | 10 ++- lesson08/loops.py | 12 +-- lesson08/rps2.py | 2 +- lesson09/functions.py | 4 +- lesson10/recursion.py | 2 +- lesson11/scope.py | 5 +- lesson14/kansas.py | 4 +- lesson14/modules.py | 6 +- lesson16/arcade.py | 17 ++-- lesson16/guess_number.py | 16 ++-- lesson16/rps.py | 17 ++-- lesson17/lambda.py | 35 +++++--- lesson18/classes.py | 42 ++++++---- 17 files changed, 250 insertions(+), 198 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..3b1cfda1abde8571b8086c197fed945c040290aa GIT binary patch literal 10244 zcmeI1J!lj`6vyA*oqFa2Lpr+!8zE7$o9`x`;RFjsLO=^aLUIx%xm-d_XK^3|RIpAX z1i{WgiWD|NY%Kh!Q)**lt-Wt%mh8OQH_rt@B+Q20x7q#A&2Rtg{%>av0HWEgRss+M zKpj_A2l{ZsEb6>k3ri(CvVb+h_OQB~%rAA?>jh;v5F7{&1P6ix!GYkw|Kb3CXRD>& zYiigA2Z95^fnx_$KE$}H+Q@3xR2?0-(L(^NH9V{r+#gUoSmUfVvf4Ej&)^c7rdUnW zC>vr#ra2yuGhHLAT~keSh_b;)l=U2CBa}$@j-MZEIYbRp!!|e&94I=lfQM>u8J6K8 zJR;-w>e`-tuH9)i7gsxrc&xrz*=~Kk^5H5y-xANSKd|NoYTvLaKJlw?A2#u?18Xn> z3F*JG^PSV!9K#o0EoB^q&uVva9!W>ID*GH)O1J=iFkGq4wK41ELS4=!=?IqzMfVy< z9j*h0Yt-f%y6)vdUCt%xN^p%)uAWhbYs}_)f5Xd#x|~bWmEanuT-B7}8n?MV&3U;{ zmvc$F5?m9Mt3JqZP1sy}x4m4b%ef?739d=Xb+*lLP1;;DcfDMw%ef?739c#1Ri9zF zrfjayEiV`9axO_nxnk_HkYCf3D>~#fHrJCCFW0oqCFv-ae*2+0k-!M$I{mu9g&Lb{ zc+113b-7=Xj&hA)myTbFllO3Dh11wvE04WgiS3u9qg*k^<>YzS+i{!neqg?F$<>Y<;F2hCgeq-0m zMe<(KQLY%fEZp}_-k-n8Y3%!c@Qs&?3LGk#%?H;>9mvoe? zfn65-a`OJ%E~l~my7SA+Me<(KQLZj_8I}|3K-FAVtmgl(`G5aEp;sR+D>x7wP!2@3 z=6rKj?Rfl9bL}y%3%II9>AI%sCb-el@mTeAJpQAm<1gZ>wE9ao+izsGYpQOJ8r>Z0 zKl(8spK~PdgJJw{=69uWy*= 9): + print(num) return num + 1 total = num + 1 diff --git a/lesson11/scope.py b/lesson11/scope.py index d320d0d..c82501c 100644 --- a/lesson11/scope.py +++ b/lesson11/scope.py @@ -12,11 +12,12 @@ def another(): def greeting(name): nonlocal color + print(color) color = "red" print(color) - print(name) + print(name) #local priority - greeting("Dave") + greeting("Davee") another() diff --git a/lesson14/kansas.py b/lesson14/kansas.py index 7829fe0..7568410 100644 --- a/lesson14/kansas.py +++ b/lesson14/kansas.py @@ -22,5 +22,5 @@ def randomfunfact(): print(funfacts[int(index)]) -if __name__ == "__main__": - randomfunfact() + +randomfunfact() \ No newline at end of file diff --git a/lesson14/modules.py b/lesson14/modules.py index 1af30da..5c84c86 100644 --- a/lesson14/modules.py +++ b/lesson14/modules.py @@ -15,7 +15,7 @@ print(kansas.capital) kansas.randomfunfact() -print(__name__) -print(kansas.__name__) +print(__name__) #__main__ because it's the module we're running +print(kansas.__name__) #kansas (t1he imported module ) -rock_paper_scissors() +rock_paper_scissors() \ No newline at end of file diff --git a/lesson16/arcade.py b/lesson16/arcade.py index c4f35f6..1ae1652 100644 --- a/lesson16/arcade.py +++ b/lesson16/arcade.py @@ -3,22 +3,22 @@ from guess_number import guess_number -def play_game(name='PlayerOne'): +def play_game(name="PlayerOne"): welcome_back = False while True: - if welcome_back == True: + if welcome_back == True: #Initially False 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" + '\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 + welcome_back = True #set to True only after entering a valid choice if playerchoice == "1": rock_paper_scissors = rps(name) @@ -39,12 +39,15 @@ def play_game(name='PlayerOne'): ) parser.add_argument( - '-n', '--name', metavar='name', - required=True, help='The name of the person playing the game.' + "-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) + play_game(args.name) diff --git a/lesson16/guess_number.py b/lesson16/guess_number.py index 68e5ed1..9af767c 100644 --- a/lesson16/guess_number.py +++ b/lesson16/guess_number.py @@ -2,7 +2,7 @@ import random -def guess_number(name='PlayerOne'): +def guess_number(name="PlayerOne"): game_count = 0 player_wins = 0 @@ -11,7 +11,8 @@ def play_guess_number(): nonlocal player_wins playerchoice = input( - f"\n{name}, guess which number I'm thinking of... 1, 2, or 3.\n\n") + 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.") @@ -20,9 +21,7 @@ def play_guess_number(): computerchoice = random.choice("123") print(f"\n{name}, you chose {playerchoice}.") - print( - f"I was thinking about the number {computerchoice}.\n" - ) + print(f"I was thinking about the number {computerchoice}.\n") player = int(playerchoice) @@ -79,8 +78,11 @@ def decide_winner(player, computer): ) parser.add_argument( - '-n', '--name', metavar='name', - required=True, help='The name of the person playing the game.' + "-n", + "--name", + metavar="name", + required=True, + help="The name of the person playing the game.", ) args = parser.parse_args() diff --git a/lesson16/rps.py b/lesson16/rps.py index 289d5d7..711456f 100644 --- a/lesson16/rps.py +++ b/lesson16/rps.py @@ -3,7 +3,7 @@ from enum import Enum -def rps(name='PlayerOne'): +def rps(name="PlayerOne"): game_count = 0 player_wins = 0 python_wins = 0 @@ -19,7 +19,8 @@ class RPS(Enum): SCISSORS = 3 playerchoice = input( - f"\n{name}, please enter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n") + 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.") @@ -32,9 +33,7 @@ class RPS(Enum): 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" - ) + print(f"Python chose {str(RPS(computer)).replace('RPS.', '').title()}.\n") def decide_winner(player, computer): nonlocal name @@ -96,12 +95,14 @@ def decide_winner(player, computer): ) parser.add_argument( - '-n', '--name', metavar='name', - required=True, help='The name of the person playing the game.' + "-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 index b205ca8..e70dd02 100644 --- a/lesson17/lambda.py +++ b/lesson17/lambda.py @@ -1,22 +1,33 @@ from functools import reduce -def squared(num): return num * num -# lambda num : num * num + +# lamba function is a single expression that returns a value + +squared_lambda = ( + lambda num: num * num +) # equivalent to def squared_lambda(num): return num * num +print(squared_lambda(2)) + + +def squared(num): + return num * num # lambda num : num * num print(squared(2)) -def add_two(num): return num + 2 -# lambda num : num + 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 +def sum_total(a, b): + return a + b +# lambda a, b : a + b + print(sum_total(10, 8)) ####################### @@ -29,14 +40,18 @@ def funcBuilder(x): add_ten = funcBuilder(10) add_twenty = funcBuilder(20) -print(add_ten(7)) -print(add_twenty(7)) +print(add_ten(7)) # 17 +print(add_twenty(7)) # 27 ######################## +# Higher order function - function that takes another function as an argument or returns a function. This allows for more flexible and reusable code. + numbers = [3, 7, 12, 18, 20, 21] +# map is a function built into Python and it receives a function as it's first argument and applies it to each item in the iterable. The second argument is an iterable. + squared_nums = map(lambda num: num * num, numbers) print(list(squared_nums)) @@ -44,7 +59,7 @@ def funcBuilder(x): ############################### odd_nums = filter(lambda num: num % 2 != 0, numbers) - +print(tuple(odd_nums)) print(list(odd_nums)) ############################# @@ -59,7 +74,7 @@ def funcBuilder(x): print(sum(numbers, 10)) -names = ['Dave Gray', 'Sara Ito', 'John Jacob Jingleheimerschmidt'] +names = ["Dave Gray", "Sara Ito", "John Jacob Jingleheimerschmidt"] char_count = reduce(lambda acc, curr: acc + len(curr), names, 0) diff --git a/lesson18/classes.py b/lesson18/classes.py index ef563aa..01448f6 100644 --- a/lesson18/classes.py +++ b/lesson18/classes.py @@ -1,48 +1,54 @@ -class Vehicle: - def __init__(self, make, model): +class Vehicle: # blueprint for Objects representing vehicles + def __init__( + self, make, model + ): # initialized function used to set properties of the class self.make = make self.model = model def moves(self): - print('Moves along..') + print("Moves along..") def get_make_model(self): print(f"I'm a {self.make} {self.model}.") -my_car = Vehicle('Tesla', 'Model 3') +my_car = Vehicle("Tesla", "Model 3") -# print(my_car.make) -# print(my_car.model) -my_car.get_make_model() +print(my_car.make) # accessing property of the my_car instance +print(my_car.model) +my_car.get_make_model() # method that is a function which is associated with the object. my_car.moves() -your_car = Vehicle('Cadillac', 'Escalade') +your_car = Vehicle("Cadillac", "Escalade") your_car.get_make_model() your_car.moves() +# Inheritance example class Airplane(Vehicle): def __init__(self, make, model, faa_id): - super().__init__(make, model) + super().__init__(make, model) # inherit from parent class self.faa_id = faa_id def moves(self): - print('Flies along..') + print("Flies along..") class Truck(Vehicle): def moves(self): - print('Rumbles along..') + print("Rumbles along..") class GolfCart(Vehicle): - pass + pass # inherit everything as is -cessna = Airplane('Cessna', 'Skyhawk', 'N-12345') -mack = Truck('Mack', 'Pinnacle') -golfwagon = GolfCart('Yamaha', 'GC100') +print("") +print("") + +cessna = Airplane("Cessna", "Skyhawk", "N-12345") +mack = Truck("Mack", "Pinnacle") +golfwagon = GolfCart("Yamaha", "GC100") cessna.get_make_model() cessna.moves() @@ -51,8 +57,12 @@ class GolfCart(Vehicle): golfwagon.get_make_model() golfwagon.moves() -print('\n\n') +print("\n\n") + +# Polymorphism example using a list of objects +# The ability to behave differently in response to different input messages +# They all have a 'get_make_model' and a'moves' method but they have different responses to these methods for v in (my_car, your_car, cessna, mack, golfwagon): v.get_make_model() v.moves() From 33d10813cb61e6bccfdd1a3147c87fc17b1e9c3a Mon Sep 17 00:00:00 2001 From: Dmitriy Malayev Date: Sat, 31 Aug 2024 17:28:36 -0400 Subject: [PATCH 2/3] update --- lesson09/functions.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lesson09/functions.py b/lesson09/functions.py index fc2fd9e..05702dd 100644 --- a/lesson09/functions.py +++ b/lesson09/functions.py @@ -6,7 +6,7 @@ def hello_world(): def sum(num1=0, num2=0): - if (type(num1) is not int or type(num2) is not int): + if type(num1) is not int or type(num2) is not int: return 0 return num1 + num2 @@ -23,9 +23,9 @@ def multiple_items(*args): multiple_items("Dave", "John", "Sara") -def mult_named_items(**kwargs): #keyword arguments +def mult_named_items(**kwargs): print(kwargs) print(type(kwargs)) -multiple_items(first="Dave", last="Gray") +mult_named_items(first="Dave", last="Gray") From 334914c8368923f12e85460b4461d5f0e6db375e Mon Sep 17 00:00:00 2001 From: Dmitriy Malayev Date: Sun, 1 Sep 2024 01:34:21 -0400 Subject: [PATCH 3/3] update --- lesson19/exceptions.py | 10 +++++++--- lesson20/bank_accounts.py | 41 +++++++++++++++++++++------------------ lesson20/oop_project.py | 22 +++++++++++---------- 3 files changed, 41 insertions(+), 32 deletions(-) diff --git a/lesson19/exceptions.py b/lesson19/exceptions.py index f29334b..30778ce 100644 --- a/lesson19/exceptions.py +++ b/lesson19/exceptions.py @@ -10,12 +10,16 @@ class JustNotCoolError(Exception): # if not type(x) is str: # raise TypeError("Only strings are allowed.") except NameError: - print('NameError means something is probably undefined.') + print("NameError means something is probably undefined.") except ZeroDivisionError: - print('Please do not divide by zero.') + print("Please do not divide by zero.") except Exception as error: print(error) else: - print('No errors!') + print("No errors!") finally: print("I'm going to print with or without an error.") + + +# raise in Python is the same as throw in JS +# except are used for general error handling diff --git a/lesson20/bank_accounts.py b/lesson20/bank_accounts.py index e96035e..89cee5c 100644 --- a/lesson20/bank_accounts.py +++ b/lesson20/bank_accounts.py @@ -6,14 +6,15 @@ 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}") + 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 + if amount <= 0: + print("\nInvalid deposit amount.") + return print("\nDeposit complete.") self.get_balance() @@ -32,34 +33,36 @@ def withdraw(self, amount): print("\nWithdraw complete.") self.get_balance() except BalanceException as error: - print(f'\nWithdraw interrupted: {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}') + 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): +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): + def __init__(self, initial_amount, acct_name): super().__init__(initial_amount, acct_name) self.fee = 5 - def withdraw(self, amount): - try: + def withdraw(self, amount): + try: self.viable_transaction(amount + self.fee) - self.balance = self.balance - (amount + self.fee) + self.balance = self.balance - (amount + self.fee) print("\nWithdraw completed.") - self.get_balance() + self.get_balance() except BalanceException as error: - print(f'\nWithdraw interrupted: {error}') + print(f"\nWithdraw interrupted: {error}") diff --git a/lesson20/oop_project.py b/lesson20/oop_project.py index 1dc589f..7a105d7 100644 --- a/lesson20/oop_project.py +++ b/lesson20/oop_project.py @@ -8,25 +8,27 @@ Sara.deposit(500) -Dave.withdraw(10000) Dave.withdraw(10) +Dave.withdraw(10000) Dave.transfer(10000, Sara) Dave.transfer(100, Sara) -Jim = InterestRewardsAcct(1000, "Jim") +Jim = InterestRewardsAcct(100, "Jim") + +# Jim.get_balance() -Jim.get_balance() +# Jim.deposit(100) -Jim.deposit(100) +# Jim.transfer(100, Dave) -Jim.transfer(100, Dave) +# Blaze = SavingsAcct(1000, "Blaze") -Blaze = SavingsAcct(1000, "Blaze") +# Blaze.get_balance() -Blaze.get_balance() +# Blaze.deposit(100) -Blaze.deposit(100) +# Blaze.transfer(10000, Sara) +# Blaze.transfer(1000, Sara) -Blaze.transfer(10000, Sara) -Blaze.transfer(1000, Sara) +print("\n\n**********")