├── Day001-Band_name_Generator.py
├── Day002-Tip_CalculatorInRM.py
├── Day003-Treasure_Island_Adventure.py
├── Day004-Rock_Paper_Scissors_Game.py
├── Day005-Random_Password_Generator.py
├── Day006-Hurdle1-4 & Maze_for_Reeborg'sWorld
├── Day007-Hangman_Game.py
├── Day008-Caeser_Cipher_encryption_decryption.py
├── Day009-Silent_Auction.py
├── Day010-Basic-Calculator.py
├── Day011-Blackjack.py
├── Day012-Number Guessing Game.py
├── Day013- Debugging
├── Day014-Higher-lower-game
├── Day015-Coffee_Machine.py
├── Day016-OOP-Coffee_Machine.py
└── README.md
/Day001-Band_name_Generator.py:
--------------------------------------------------------------------------------
1 | #1. Create a greeting for your program.
2 | print("Hello there! Welcome to the band name generator!")
3 | #2. Ask the user for the city that they grew up in.
4 | city = (input("First off, what city are you from?\n"))
5 | #3. Ask the user for the name of a pet.
6 | pet_name = (input("Alright! Now enter a name of a pet!\n"))
7 | #4. Combine the name of their city and pet and show them their band name.
8 | print("Your band name is " + city + " " + pet_name )
9 | #5. Make sure the input cursor shows on a new line, see the example at:
10 | # https://band-name-generator-end.appbrewery.repl.run/
11 |
--------------------------------------------------------------------------------
/Day002-Tip_CalculatorInRM.py:
--------------------------------------------------------------------------------
1 | print("Welcome to the tip calculator!")
2 | bill = float(input("What was the total bill?\nRM"))
3 | tip = int(input("What percentage of tip would you like to give?\n"))
4 | ppl = int(input("How many people to split the bill?\n"))
5 |
6 | totalbill = bill * (1+tip/100)
7 | final= round(totalbill/ppl,2)
8 |
9 | print(f"Each person should pay: RM{final}")
10 |
--------------------------------------------------------------------------------
/Day003-Treasure_Island_Adventure.py:
--------------------------------------------------------------------------------
1 | print('''
2 | *******************************************************************************
3 | | | | |
4 | _________|________________.=""_;=.______________|_____________________|_______
5 | | | ,-"_,="" `"=.| |
6 | |___________________|__"=._o`"-._ `"=.______________|___________________
7 | | `"=._o`"=._ _`"=._ |
8 | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______
9 | | | __.--" , ; `"=._o." ,-"""-._ ". |
10 | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________
11 | | |o`"=._` , "` `; .". , "-._"-._; ; |
12 | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
13 | | | |o; `"-.o`"=._`` '` " ,__.--o; |
14 | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________
15 | ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____
16 | /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_
17 | ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____
18 | /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
19 | ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
20 | /______/______/______/______/______/______/______/______/______/______/_____ /
21 | *******************************************************************************
22 | ''')
23 |
24 | print("Welcome to Treasure Island!⛱")
25 | print("Your mission is to find the treasure.💰")
26 | first = input("You have come acrossed a crossroad, would you like to turn Left or Right?\nLeft/Right\n").lower()
27 | if first == "left":
28 | second=input("You have reached an icy river. Would you rather swim across or wait for a sail that you can see coming in your way?\nSwim/Wait\n").lower()
29 | if second == "wait":
30 | print('''
31 |
32 | .
33 | .'| .8
34 | . | .8:
35 | . | .8;: .8
36 | . | .8;;: | .8;
37 | . n .8;;;: | .8;;;
38 | . M.8;;;;;: |,8;;;;;
39 | . .,"n8;;;;;;: |8;;;;;;
40 | . .', n;;;;;;;: M;;;;;;;;
41 | . ,' , n;;;;;;;;: n;;;;;;;;;
42 | . ,' , N;;;;;;;;: n;;;;;;;;;
43 | . ' , N;;;;;;;;;: N;;;;;;;;;;
44 | .,' . N;;;;;;;;;: N;;;;;;;;;;
45 | .. , N6666666666 N6666666666
46 | I , M M
47 | ---nnnnn_______M___________M______mmnnn
48 | "-. /
49 | __________"-_______________________/_______
50 | ~ ~~~~~ ~~~~~~ ~~~~~~~~~ ~~~~~~~~~~~~~~ ~~~~~~~ ~
51 | ~~ ~~~~~~ ~~~~~~~~~ ~~~~~ ~~~~~~~~ ~~~~~~~~~~~~ ~~~~ ~~~~
52 | ''')
53 | third = input("You safely crossed the icy river!brrr...\nYou walked and reached a house with three doors! Red, Yellow and Blue!Now choose wisely..\nRed/Yellow/Blue\n").lower()
54 | if third == "red":
55 | print('''
56 | /^\ /^\
57 | | \ / |
58 | ||\ \../ /||
59 | )' `(
60 | ,;`w, ,w';,
61 | ;, ) __ ( ,;
62 | ; \(\/)/ ;;
63 | ;| |vwwv| ``-...
64 | ; `lwwl' ; ```''-.
65 | ;| ; `""' ; ; `.
66 | ; , , , |
67 | ' ; ; l . | |
68 | ; , , |,-,._| \;
69 | ; ; `' ; ' \ `\ \;
70 | | | | | | | |;
71 | | ; ; | \ \ (;
72 | | | | l | | \ |
73 | | | | | | | ) |
74 | | | | ; | | | |
75 | ; , : , ,_.' | |
76 | :__' | | ,_.'
77 | `--'
78 | ''')
79 | print("You should have understood that red means danger...\nYou entered the room with a wolf behind it...awooo..")
80 | elif third == "yellow":
81 | print("You have chosen the right door! You have found the treasure and is heading back home to enjoy the rest of your life!💰")
82 | elif third == "blue":
83 | print('''
84 |
85 | |.
86 | ::.
87 | :::
88 | ___ |::
89 | `-._''--.._ |::
90 | `-._ `-._ .|::
91 | `-._ `-::::
92 | `. |:::.
93 | ) |::`:"-._
94 | <' _.7 ::::::`-,.._
95 | `-.: `` '::::::".
96 | .:' . . `::::\
97 | .:' . .:::}
98 | _.:' __ . :::/
99 | ,-.___,,..--'' --.""`` ``"".-- --,.._____.-.
100 | (( ___ """ -- ... .... __ ______ (D
101 | "-'` ```''-. __,,.......,,__ ::. `-"
102 | `<-....,,,,....-< .:::'
103 | "._ ___,,._:::(
104 | ::--='' `\:::.
105 | / :::' `\::.
106 | / ::' `\::
107 | / :' `\:
108 | ( / `"
109 | "
110 | ''')
111 | print("You opened the door and got dragged into the sea by a hammerhead shark..you are hammered..")
112 | else:
113 | print("You have chose a wrong colour, start again!")
114 | elif second == "swim":
115 | print('''
116 | _____ _____
117 | ,888888b. ,888888b.
118 | .d888888888b .d888888888b
119 | _..-'.`*'_,88888b _..-'.`*'_,88888b
120 | ,'..-..`"ad88888888b. ,'..-..`"ad88888888b.
121 | ``-. `*Y888888b. ``-. `*Y888888b.
122 | \ `Y888888b. \ `Y888888b.
123 | : Y8888888b. : Y8888888b.
124 | : Y88888888b. : Y88888888b.
125 | | _,8ad88888888. | _,8ad88888888.
126 | : .d88888888888888b. : .d88888888888888b.
127 | \d888888888888888888 \d888888888888888888
128 | 8888;''"`88888888888 8888;ss'`88888888888
129 | 888' Y8888888888 888'N""N Y8888888888
130 | `Y8 :8888888888 `Y8 N " :8888888888
131 | |` '8888888888 |` N '8888888888
132 | | 8888888888 | N 8888888888
133 | | 8888888888 | N 8888888888
134 | | 8888888888 | N 8888888888
135 | | ,888888888P | N ,888888888P
136 | : ;888888888' : N ;888888888'
137 | \ d88888888' : N ;888888888'
138 | _.>, 888888P' \ N d88888888'
139 | <,--''`.._>8888( _.>N 888888P'
140 | `>__...--' `''` SSt <,--'N`.._>8888(
141 | `>__N..--' `''` SSt
142 | N
143 | ''')
144 | print("You froze to death in the river while the last thing you hear is penguins chuckling at you🤣")
145 | else:
146 | print("Wrong instruction! Start Again!")
147 | elif first == "right":
148 | print('''
149 | .<==+.
150 | \\
151 | __ /*-----._//
152 | >_)='-[[[[---'
153 | ''')
154 | print("You turned right and fell into a hole full of scorpions...Yikes!")
155 | else:
156 | print("Wrong direction! Start again!")
157 |
--------------------------------------------------------------------------------
/Day004-Rock_Paper_Scissors_Game.py:
--------------------------------------------------------------------------------
1 | rock = '''
2 | _______
3 | ---' ____)
4 | (_____)
5 | (_____)
6 | (____)
7 | ---.__(___)
8 | '''
9 |
10 | paper = '''
11 | _______
12 | ---' ____)____
13 | ______)
14 | _______)
15 | _______)
16 | ---.__________)
17 | '''
18 |
19 | scissors = '''
20 | _______
21 | ---' ____)____
22 | ______)
23 | __________)
24 | (____)
25 | ---.__(___)
26 | '''
27 |
28 | moves= [rock,paper,scissors]
29 | userMove = input("What do you choose?\n0 for Rock, 1 for Paper & 2 for Scissors.\n")
30 | import random
31 | compMove = random.choice(moves)
32 |
33 | if userMove == "0":
34 | print(f"{rock}\nComputer chose:")
35 | if compMove == rock:
36 | print(f"{rock}\nTied!")
37 | elif compMove == paper:
38 | print(f"{paper}\nYou Lost!")
39 | else:
40 | print(f"{scissors}\nYou Won!")
41 | elif userMove == "1":
42 | print(f"{paper}\nComputer chose:")
43 | if compMove == rock:
44 | print(f"{rock}\nYou Won!")
45 | elif compMove == paper:
46 | print(f"{paper}\nTied!")
47 | else:
48 | print(f"{scissors}\nYou Lost!")
49 | elif userMove == "2":
50 | print(f"{scissors}\nComputer chose:")
51 | if compMove == rock:
52 | print(f"{rock}\nYou Lost!")
53 | elif compMove == paper:
54 | print(f"{paper}\nYou Won!")
55 | else:
56 | print(f"{scissors}\nTied!")
57 | else:
58 | print("Your move isn't available. Please choose between 0 to 2 inclusive")
59 |
60 | #or
61 |
62 | # game_images = [rock, paper, scissors]
63 |
64 | # user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
65 | # print(game_images[user_choice])
66 |
67 | # computer_choice = random.randint(0, 2)
68 | # print("Computer chose:")
69 | # print(game_images[computer_choice])
70 |
71 | # if user_choice >= 3 or user_choice < 0:
72 | # print("You typed an invalid number, you lose!")
73 | # elif user_choice == 0 and computer_choice == 2:
74 | # print("You win!")
75 | # elif computer_choice == 0 and user_choice == 2:
76 | # print("You lose")
77 | # elif computer_choice > user_choice:
78 | # print("You lose")
79 | # elif user_choice > computer_choice:
80 | # print("You win!")
81 | # elif computer_choice == user_choice:
82 | # print("It's a draw")
83 |
--------------------------------------------------------------------------------
/Day005-Random_Password_Generator.py:
--------------------------------------------------------------------------------
1 | #Password Generator Project
2 | import random
3 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
4 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
5 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
6 |
7 | print("Welcome to the PyPassword Generator!")
8 | nr_letters= int(input("How many letters would you like in your password?\n"))
9 | nr_symbols = int(input(f"How many symbols would you like?\n"))
10 | nr_numbers = int(input(f"How many numbers would you like?\n"))
11 |
12 | #Eazy Level - Order not randomised:
13 | #e.g. 4 letter, 2 symbol, 2 number = JduE&!91
14 | password = ("")
15 |
16 | for char in range(1,nr_letters + 1):
17 | password += random.choice(letters)
18 |
19 | for char in range(1, nr_symbols + 1):
20 | password += random.choice(symbols)
21 |
22 | for char in range(1, nr_numbers + 1):
23 | password += random.choice(numbers)
24 |
25 | print(f"\nEasy password: {password}")
26 |
27 | #Hard Level - Order of characters randomised:
28 | #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P
29 | password_list = []
30 |
31 | #adding random letters based on input number into the empty list
32 | #Use append/ += is the same(look below for letters vs symbols)
33 | for char in range(1, nr_letters + 1):
34 | password_list.append(random.choice(letters))
35 |
36 | #add symbols and numbers behind the list that has letters
37 | for char in range(1, nr_symbols + 1):
38 | password_list += random.choice(symbols)
39 |
40 | for char in range(1, nr_numbers + 1):
41 | password_list += random.choice(numbers)
42 |
43 | #After the list with random letters+symbols+numbers are created, the list is shuffled so that it does not follow the sequence of letters > symbols > numbers
44 | random.shuffle(password_list)
45 |
46 | #Converting into a string.
47 | password = ""
48 | for char in password_list:
49 | password += char
50 |
51 | print(f"\nHard password: {password}")
52 |
53 |
--------------------------------------------------------------------------------
/Day006-Hurdle1-4 & Maze_for_Reeborg'sWorld:
--------------------------------------------------------------------------------
1 | #https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%204&url=worlds%2Ftutorial_en%2Fhurdle4.json
2 | #Hurdle 1-4
3 | def turn_right():
4 | turn_left()
5 | turn_left()
6 | turn_left()
7 |
8 | def jump():
9 | turn_left()
10 | while wall_on_right():
11 | move()
12 |
13 | turn_right()
14 | move()
15 | turn_right()
16 |
17 | while front_is_clear():
18 | move()
19 | turn_left()
20 |
21 |
22 | while not at_goal():
23 | if wall_in_front():
24 | jump()
25 | else:
26 | move()
27 |
28 | #CODE FOR MAZE(POTD)
29 | def turn_right():
30 | turn_left()
31 | turn_left()
32 | turn_left()
33 |
34 |
35 | while not at_goal():
36 | if wall_on_right():
37 | if front_is_clear():
38 | move()
39 | elif wall_in_front():
40 | turn_left()
41 | elif right_is_clear:
42 | turn_right()
43 | move()
44 |
--------------------------------------------------------------------------------
/Day007-Hangman_Game.py:
--------------------------------------------------------------------------------
1 | import random
2 | from hangman_art import stages, logo
3 | from hangman_words import word_list
4 | from replit import clear
5 |
6 | print(logo)
7 | game_is_finished = False
8 | lives = len(stages) - 1
9 |
10 | chosen_word = random.choice(word_list)
11 | word_length = len(chosen_word)
12 |
13 | display = []
14 | for _ in range(word_length):
15 | display += "_"
16 |
17 | while not game_is_finished:
18 | guess = input("Guess a letter: ").lower()
19 |
20 | #Use the clear() function imported from replit to clear the output between guesses.
21 | clear()
22 |
23 | if guess in display:
24 | print(f"You've already guessed {guess}")
25 |
26 | for position in range(word_length):
27 | letter = chosen_word[position]
28 | if letter == guess:
29 | display[position] = letter
30 | print(f"{' '.join(display)}")
31 |
32 | if guess not in chosen_word:
33 | lives -= 1
34 | print(f"You guessed {guess}\nThat's not in the word.\nYou lose a life. {lives} lifes left")
35 | if lives == 0:
36 | game_is_finished = True
37 | print(f"You lose.\nThe word was {chosen_word}")
38 |
39 | if not "_" in display:
40 | game_is_finished = True
41 | print("You win.")
42 |
43 | print(stages[lives])
44 |
--------------------------------------------------------------------------------
/Day008-Caeser_Cipher_encryption_decryption.py:
--------------------------------------------------------------------------------
1 | alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
2 |
3 | def caesar(start_text, shift_amount, cipher_direction):
4 | end_text = ""
5 | if cipher_direction == "decode":
6 | shift_amount *= -1
7 | for char in start_text:
8 | if char in alphabet:
9 | position = alphabet.index(char)
10 | new_position = position + shift_amount
11 | end_text += alphabet[new_position]
12 | else:
13 | end_text += char
14 |
15 | print(f"Here's the {cipher_direction}d result: {end_text}")
16 |
17 | from art import logo
18 | print(logo)
19 |
20 | should_continue = True
21 | while should_continue:
22 | direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
23 | text = input("Type your message:\n").lower()
24 | shift = int(input("Type the shift number:\n"))
25 |
26 | shift = shift % 25
27 | caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
28 |
29 | result = input('Would you like to repeat the program again? "Yes" or "No"\n').lower()
30 | if result=="no":
31 | should_continue=False
32 | print("Program ended...")
33 |
--------------------------------------------------------------------------------
/Day009-Silent_Auction.py:
--------------------------------------------------------------------------------
1 | from replit import clear
2 | from art import logo
3 | print(logo)
4 |
5 | def find_highest_bidder(bidding_record):
6 | highest_bid = 0
7 | winner = ""
8 |
9 | for bidder in bidding_record:
10 | bid_amount = bidding_record[bidder]
11 |
12 | if bid_amount > highest_bid:
13 | highest_bid = bid_amount
14 | winner = bidder
15 |
16 | print(f"The winner is {bidder} with a bid of ${highest_bid}")
17 |
18 | bids = {}
19 | bidding_finish = False
20 |
21 | while not bidding_finish:
22 | name = input("What is your name?\n")
23 | price = int(input("How much would you like to bid?\n$"))
24 |
25 | bids[name] = price
26 |
27 | should_continue = input('Are there any other bidders? type "Yes" or "No"\n').lower()
28 |
29 | if should_continue == "no":
30 | bidding_finish = True
31 | find_highest_bidder(bids)
32 | elif should_continue == "yes":
33 | clear()
34 |
--------------------------------------------------------------------------------
/Day010-Basic-Calculator.py:
--------------------------------------------------------------------------------
1 | from art import logo
2 |
3 | from replit import clear
4 |
5 | #Calculator
6 | #Add
7 | def add(n1,n2):
8 | return n1 + n2
9 |
10 | #Subtract
11 | def subtract(n1,n2):
12 | return n1 - n2
13 |
14 | #Multiply
15 | def multiply(n1,n2):
16 | return n1 * n2
17 | 3
18 |
19 | #Divide
20 | def divide(n1,n2):
21 | return n1 / n2
22 |
23 | #Dictionary
24 | operations = {
25 | "+" : add,
26 | "-" : subtract,
27 | "*" : multiply,
28 | "/" : divide,
29 | }
30 |
31 | def calculator():
32 | print(logo)
33 |
34 | num1 = float(input("What is the first number?\n"))
35 | for symbol in operations:
36 | print(symbol)
37 |
38 | repeat = True
39 |
40 | while repeat:
41 | operation_symbol = (input("Pick an operation:\n"))
42 |
43 | num2 = float(input("What is the next number?\n"))
44 |
45 | calc_function = operations[operation_symbol]
46 |
47 | answer = calc_function(num1,num2)
48 |
49 | print(f"{num1} {operation_symbol} {num2} = {answer}")
50 |
51 | if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to exit.\n").lower() == "y":
52 | num1 = answer
53 | else:
54 | repeat = False
55 | clear()
56 | calculator()
57 |
58 | calculator()
59 |
--------------------------------------------------------------------------------
/Day011-Blackjack.py:
--------------------------------------------------------------------------------
1 | ############### Blackjack Project #####################
2 |
3 | #Difficulty Normal 😎: Use all Hints below to complete the project.
4 | #Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.
5 | #Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project.
6 | #Difficulty Expert 🤯: Only use Hint 1 to complete the project.
7 |
8 | ############### Our Blackjack House Rules #####################
9 |
10 | ## The deck is unlimited in size.
11 | ## There are no jokers.
12 | ## The Jack/Queen/King all count as 10.
13 | ## The the Ace can count as 11 or 1.
14 | ## Use the following list as the deck of cards:
15 | ## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
16 | ## The cards in the list have equal probability of being drawn.
17 | ## Cards are not removed from the deck as they are drawn.
18 |
19 | ##################### Hints #####################
20 |
21 | #Hint 1: Go to this website and try out the Blackjack game:
22 | # https://games.washingtonpost.com/games/blackjack/
23 | #Then try out the completed Blackjack project here:
24 | # http://blackjack-final.appbrewery.repl.run
25 |
26 | #Hint 2: Read this breakdown of program requirements:
27 | # http://listmoz.com/view/6h34DJpvJBFVRlZfJvxF
28 | #Then try to create your own flowchart for the program.
29 |
30 | #Hint 3: Download and read this flow chart I've created:
31 | # https://drive.google.com/uc?export=download&id=1rDkiHCrhaf9eX7u7yjM1qwSuyEk-rPnt
32 |
33 | #Hint 4: Create a deal_card() function that uses the List below to *return* a random card.
34 | #11 is the Ace.
35 | import random
36 | from replit import clear
37 | from art import logo
38 |
39 | def deal_card():
40 | """Returns a random card from the deck."""
41 | cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
42 | card = random.choice(cards)
43 | return card
44 |
45 | #Hint 6: Create a function called calculate_score() that takes a List of cards as input
46 | #and returns the score.
47 | #Look up the sum() function to help you do this.
48 | def calculate_score(cards):
49 | """Take a list of cards and return the score calculated from the cards"""
50 |
51 | #Hint 7: Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
52 | if sum(cards) == 21 and len(cards) == 2:
53 | return 0
54 | #Hint 8: Inside calculate_score() check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1. You might need to look up append() and remove().
55 | if 11 in cards and sum(cards) > 21:
56 | cards.remove(11)
57 | cards.append(1)
58 | return sum(cards)
59 |
60 | #Hint 13: Create a function called compare() and pass in the user_score and computer_score. If the computer and user both have the same score, then it's a draw. If the computer has a blackjack (0), then the user loses. If the user has a blackjack (0), then the user wins. If the user_score is over 21, then the user loses. If the computer_score is over 21, then the computer loses. If none of the above, then the player with the highest score wins.
61 | def compare(user_score, computer_score):
62 | #Bug fix. If you and the computer are both over, you lose.
63 | if user_score > 21 and computer_score > 21:
64 | return "You went over. You lose 😤"
65 |
66 |
67 | if user_score == computer_score:
68 | return "Draw 🙃"
69 | elif computer_score == 0:
70 | return "Lose, opponent has Blackjack 😱"
71 | elif user_score == 0:
72 | return "Win with a Blackjack 😎"
73 | elif user_score > 21:
74 | return "You went over. You lose 😭"
75 | elif computer_score > 21:
76 | return "Opponent went over. You win 😁"
77 | elif user_score > computer_score:
78 | return "You win 😃"
79 | else:
80 | return "You lose 😤"
81 |
82 | def play_game():
83 |
84 | print(logo)
85 |
86 | #Hint 5: Deal the user and computer 2 cards each using deal_card()
87 | user_cards = []
88 | computer_cards = []
89 | is_game_over = False
90 |
91 | for _ in range(2):
92 | user_cards.append(deal_card())
93 | computer_cards.append(deal_card())
94 |
95 | #Hint 11: The score will need to be rechecked with every new card drawn and the checks in Hint 9 need to be repeated until the game ends.
96 |
97 | while not is_game_over:
98 | #Hint 9: Call calculate_score(). If the computer or the user has a blackjack (0) or if the user's score is over 21, then the game ends.
99 | user_score = calculate_score(user_cards)
100 | computer_score = calculate_score(computer_cards)
101 | print(f" Your cards: {user_cards}, current score: {user_score}")
102 | print(f" Computer's first card: {computer_cards[0]}")
103 |
104 | if user_score == 0 or computer_score == 0 or user_score > 21:
105 | is_game_over = True
106 | else:
107 | #Hint 10: If the game has not ended, ask the user if they want to draw another card. If yes, then use the deal_card() function to add another card to the user_cards List. If no, then the game has ended.
108 | user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
109 | if user_should_deal == "y":
110 | user_cards.append(deal_card())
111 | elif user_score < 17:
112 | print("Your cards are less than 17. You would have to draw a card")
113 | user_cards.append(deal_card())
114 | else:
115 | is_game_over = True
116 |
117 | #Hint 12: Once the user is done, it's time to let the computer play. The computer should keep drawing cards as long as it has a score less than 17.
118 | while computer_score != 0 and computer_score < 17:
119 | computer_cards.append(deal_card())
120 | computer_score = calculate_score(computer_cards)
121 |
122 | print(f" Your final hand: {user_cards}, final score: {user_score}")
123 | print(f" Computer's final hand: {computer_cards}, final score: {computer_score}")
124 | print(compare(user_score, computer_score))
125 |
126 | #Hint 14: Ask the user if they want to restart the game. If they answer yes, clear the console and start a new game of blackjack and show the logo from art.py.
127 | while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
128 | clear()
129 | play_game()
130 |
--------------------------------------------------------------------------------
/Day012-Number Guessing Game.py:
--------------------------------------------------------------------------------
1 | from art import logo
2 | from random import randint
3 |
4 | EASY_LEVEL_TURNS = 10
5 | HARD_LEVEL_TURNS = 5
6 |
7 | #Function to check user's guess against actual answer.
8 | def check_answer(guess, answer, turns):
9 | """checks answer against guess. Returns the number of turns remaining."""
10 | if guess > answer:
11 | print("Too high.")
12 | return turns - 1
13 | elif guess < answer:
14 | print("Too low.")
15 | return turns - 1
16 | else:
17 | print(f"You got it! The answer was {answer}.")
18 |
19 | #Make function to set difficulty.
20 | def set_difficulty():
21 | level = input("Choose a difficulty. Type 'easy' or 'hard': ")
22 | if level == "easy":
23 | return EASY_LEVEL_TURNS
24 | else:
25 | return HARD_LEVEL_TURNS
26 |
27 | def game():
28 | print(logo)
29 | #Choosing a random number between 1 and 100.
30 | print("Welcome to the Number Guessing Game!")
31 | print("I'm thinking of a number between 1 and 100.")
32 | answer = randint(1, 100)
33 | # print(f"Pssst, the correct answer is {answer}")
34 |
35 | turns = set_difficulty()
36 | #Repeat the guessing functionality if they get it wrong.
37 | guess = 0
38 | while guess != answer:
39 | print(f"You have {turns} attempts remaining to guess the number.")
40 |
41 | #Let the user guess a number.
42 | guess = int(input("Make a guess: "))
43 |
44 | #Track the number of turns and reduce by 1 if they get it wrong.
45 | turns = check_answer(guess, answer, turns)
46 | if turns == 0:
47 | print("You've run out of guesses, you lose.")
48 | return
49 | elif guess != answer:
50 | print("Guess again.")
51 |
52 |
53 | game()
54 |
55 |
56 | #/////////////////////MY SOLUTION//////////////////////////
57 | # random_number = randint(1,100)
58 |
59 | # game_over = False
60 | # while not game_over:
61 | # print(logo)
62 | # print("Welcome to the number guessing game!")
63 | # print("I'm thinking of a number between 1 and 100. Can you guess?")
64 | # # print(f"psst the correct answer is {random_number}")
65 |
66 | # if (input('Choose a difficuly! Type "Easy" or "Hard".\n').lower()) == "easy":
67 | # life = 10
68 | # else:
69 | # life = 5
70 |
71 | # while life > 0 and game_over == False:
72 | # print(f"You have {life} attempts to remaining to guess the number.")
73 | # guess = int(input("Your guess: "))
74 |
75 | # if guess > random_number:
76 | # if life == 1:
77 | # print("Too high!\nYou've run out of guesses, you lose..")
78 | # else:
79 | # print("Too high!\nGuess Again!")
80 | # life -= 1
81 | # elif guess < random_number:
82 | # if life == 1:
83 | # print("Too low!\nYou've run out of guesses, you lose..")
84 | # else:
85 | # print("Too low!\nGuess Again!")
86 | # life -= 1
87 | # else:
88 | # print(f'You got it! The number is {random_number}')
89 | # game_over = True
90 |
91 | # game_over = True
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/Day013- Debugging:
--------------------------------------------------------------------------------
1 | ############DEBUGGING#####################
2 | # # Describe Problem
3 | # def my_function():
4 | # for i in range(1, 20):
5 | # if i == 20:
6 | # print("You got it")
7 | # my_function()
8 |
9 | # # The Solution
10 | # def my_function():
11 | # for i in range(1, 21):
12 | # if i == 20:
13 | # print("You got it")
14 | # my_function()
15 |
16 | # # Reproduce the Bug
17 | # from random import randint
18 | # dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
19 | # dice_num = randint(1, 6)
20 | # print(dice_imgs[dice_num])
21 |
22 | # # Solution
23 | # from random import randint
24 | # dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
25 | # dice_num = randint(1, 5)
26 | # print(dice_imgs[dice_num])
27 |
28 | # # Play Computer
29 | # year = int(input("What's your year of birth?"))
30 | # if year > 1980 and year < 1994:
31 | # print("You are a millenial.")
32 | # elif year > 1994:
33 | # print("You are a Gen Z.")
34 |
35 | # # Solution
36 | # year = int(input("What's your year of birth?\n"))
37 | # if year > 1980 and year < 1994:
38 | # print("You are a millenial.")
39 | # elif year >= 1994:
40 | # print("You are a Gen Z.")
41 |
42 | # # Fix the Errors
43 | # age = input("How old are you?")
44 | # if age > 18:
45 | # print("You can drive at age {age}.")
46 |
47 | # # Solution
48 | # age = int(input("How old are you?"))
49 | # if age > 18:
50 | # print(f"You can drive at age {age}.")
51 |
52 | # #Print is Your Friend
53 | # pages = 0
54 | # word_per_page = 0
55 | # pages = int(input("Number of pages: "))
56 | # word_per_page == int(input("Number of words per page: "))
57 | # total_words = pages * word_per_page
58 | # print(total_words)
59 |
60 | #Check with print
61 | # pages = 0
62 | # word_per_page = 0
63 | # pages = int(input("Number of pages: "))
64 | # word_per_page == int(input("Number of words per page: "))
65 | # total_words = pages * word_per_page
66 | # print(pages)
67 | # print(word_per_page)
68 | # print(total_words)
69 |
70 | # Solution
71 | # pages = 0
72 | # word_per_page = 0
73 | # pages = int(input("Number of pages: "))
74 | # word_per_page = int(input("Number of words per page: "))
75 | # total_words = pages * word_per_page
76 | # print(total_words)
77 |
78 | # #Use a Debugger
79 | # def mutate(a_list):
80 | # b_list = []
81 | # for item in a_list:
82 | # new_item = item * 2
83 | # b_list.append(new_item)
84 | # print(b_list)
85 |
86 | # mutate([1,2,3,5,8,13])
87 |
88 | # #Use a Debugger
89 | def mutate(a_list):
90 | b_list = []
91 | for item in a_list:
92 | new_item = item * 2
93 | b_list.append(new_item)
94 | print(b_list)
95 |
96 | mutate([1,2,3,5,8,13])
97 |
--------------------------------------------------------------------------------
/Day014-Higher-lower-game:
--------------------------------------------------------------------------------
1 | from game_data import data
2 | import random
3 | from art import logo, vs
4 | from replit import clear
5 |
6 | def get_random_account():
7 | """Get data from random account"""
8 | return random.choice(data)
9 |
10 | def format_data(account):
11 | """Format account into printable format: name, description and country"""
12 | name = account["name"]
13 | description = account["description"]
14 | country = account["country"]
15 | # print(f'{name}: {account["follower_count"]}')
16 | return f"{name}, a {description}, from {country}"
17 |
18 | def check_answer(guess, a_followers, b_followers):
19 | """Checks followers against user's guess
20 | and returns True if they got it right.
21 | Or False if they got it wrong."""
22 | if a_followers > b_followers:
23 | return guess == "a"
24 | else:
25 | return guess == "b"
26 |
27 |
28 | def game():
29 | print(logo)
30 | score = 0
31 | game_should_continue = True
32 | account_a = get_random_account()
33 | account_b = get_random_account()
34 |
35 | while game_should_continue:
36 | account_a = account_b
37 | account_b = get_random_account()
38 | if account_a == account_b:
39 | account_b = get_random_account()
40 |
41 | print(f"Compare A: {format_data(account_a)}.")
42 | print(vs)
43 | print(f"Against B: {format_data(account_b)}.")
44 |
45 | guess = input("Who has more followers? Type 'A' or 'B': ").lower()
46 | a_follower_count = account_a["follower_count"]
47 | b_follower_count = account_b["follower_count"]
48 | is_correct = check_answer(guess, a_follower_count, b_follower_count)
49 |
50 | clear()
51 | print(logo)
52 | if is_correct:
53 | score += 1
54 | print(f"You're right! Current score: {score}.")
55 | else:
56 | game_should_continue = False
57 | print(f"Sorry, that's wrong. Final score: {score}")
58 |
59 | game()
60 |
61 |
62 | # Generate a random account from the game data.
63 |
64 | # Format account data into printable format.
65 |
66 | # Ask user for a guess.
67 |
68 | # Check if user is correct.
69 | ## Get follower count.
70 | ## If Statement
71 |
72 | # Feedback.
73 |
74 | # Score Keeping.
75 |
76 | # Make game repeatable.
77 |
78 | # Make B become the next A.
79 |
80 | # Add art.
81 |
82 | # Clear screen between rounds.
83 |
--------------------------------------------------------------------------------
/Day015-Coffee_Machine.py:
--------------------------------------------------------------------------------
1 | MENU = {
2 | "espresso": {
3 | "ingredients": {
4 | "water": 50,
5 | "coffee": 18,
6 | },
7 | "cost": 1.5,
8 | },
9 | "latte": {
10 | "ingredients": {
11 | "water": 200,
12 | "milk": 150,
13 | "coffee": 24,
14 | },
15 | "cost": 2.5,
16 | },
17 | "cappuccino": {
18 | "ingredients": {
19 | "water": 250,
20 | "milk": 100,
21 | "coffee": 24,
22 | },
23 | "cost": 3.0,
24 | }
25 | }
26 |
27 | profit = 0
28 | resources = {
29 | "water": 300,
30 | "milk": 200,
31 | "coffee": 100,
32 | }
33 |
34 |
35 | def is_resource_sufficient(order_ingredients):
36 | """Returns True when order can be made, False if ingredients are insufficient."""
37 | for item in order_ingredients:
38 | if order_ingredients[item] > resources[item]:
39 | print(f"Sorry there is not enough {item}.")
40 | return False
41 | return True
42 |
43 |
44 | def process_coins():
45 | """Returns the total calculated from coins inserted."""
46 | print("Please insert coins.")
47 | total = int(input("how many quarters?: ")) * 0.25
48 | total += int(input("how many dimes?: ")) * 0.1
49 | total += int(input("how many nickles?: ")) * 0.05
50 | total += int(input("how many pennies?: ")) * 0.01
51 | return total
52 |
53 |
54 | def is_transaction_successful(money_received, drink_cost):
55 | """Return True when the payment is accepted, or False if money is insufficient."""
56 | if money_received >= drink_cost:
57 | change = round(money_received - drink_cost, 2)
58 | print(f"Here is ${change} in change.")
59 | global profit
60 | profit += drink_cost
61 | return True
62 | else:
63 | print("Sorry that's not enough money. Money refunded.")
64 | return False
65 |
66 |
67 | def make_coffee(drink_name, order_ingredients):
68 | """Deduct the required ingredients from the resources."""
69 | for item in order_ingredients:
70 | resources[item] -= order_ingredients[item]
71 | print(f"Here is your {drink_name} ☕️. Enjoy!")
72 |
73 |
74 | is_on = True
75 |
76 | while is_on:
77 | choice = input("What would you like? (espresso/latte/cappuccino): ")
78 | if choice == "off":
79 | is_on = False
80 | elif choice == "report":
81 | print(f"Water: {resources['water']}ml")
82 | print(f"Milk: {resources['milk']}ml")
83 | print(f"Coffee: {resources['coffee']}g")
84 | print(f"Money: ${profit}")
85 | else:
86 | drink = MENU[choice]
87 | if is_resource_sufficient(drink["ingredients"]):
88 | payment = process_coins()
89 | if is_transaction_successful(payment, drink["cost"]):
90 | make_coffee(choice, drink["ingredients"])
91 |
92 |
93 |
94 | # TODO: 1. Prompt user by asking “What would you like? (espresso/latte/cappuccino):”
95 | # a. Check the user’s input to decide what to do next.
96 | # b. The prompt should show every time action has completed, e.g. once the drink is
97 | # dispensed. The prompt should show again to serve the next customer.
98 |
99 | # TODO: 2. Turn off the Coffee Machine by entering “off” to the prompt.
100 | # a. For maintainers of the coffee machine, they can use “off” as the secret word to turn off
101 | # the machine. Your code should end execution when this happens.
102 | # if choice == "off":
103 | # repeat = False
104 |
105 | # TODO:3. Print report.
106 | # a. When the user enters “report” to the prompt, a report should be generated that shows
107 | # the current resource values. e.g.
108 | # Water: 100ml
109 | # Milk: 50ml
110 | # Coffee: 76g
111 | # Money: $2.5
112 | # if choice == "report":
113 | # repeat = False
114 | # print(f'Water: {resources["water"]}ml\nMilk: {resources["water"]}ml\nCoffee: {resources["coffee"]}g\n Money: ${money}')
115 |
116 | # TODO:4. Check resources sufficient?
117 | # a. When the user chooses a drink, the program should check if there are enough
118 | # resources to make that drink.
119 | # b. E.g. if Latte requires 200ml water but there is only 100ml left in the machine. It should
120 | # not continue to make the drink but print: “Sorry there is not enough water.”
121 | # c. The same should happen if another resource is depleted, e.g. milk or coffee.
122 |
123 |
124 | # TODO: 5. Process coins.
125 | # a. If there are sufficient resources to make the drink selected, then the program should
126 | # prompt the user to insert coins.
127 | # b. Remember that quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01
128 | # c. Calculate the monetary value of the coins inserted. E.g. 1 quarter, 2 dimes, 1 nickel, 2
129 | # pennies = 0.25 + 0.1 x 2 + 0.05 + 0.01 x 2 = $0.52
130 |
131 | # TODO: 6. Check transaction successful?
132 | # a. Check that the user has inserted enough money to purchase the drink they selected.
133 | # E.g Latte cost $2.50, but they only inserted $0.52 then after counting the coins the
134 | # program should say “Sorry that's not enough money. Money refunded.”.
135 | # b. But if the user has inserted enough money, then the cost of the drink gets added to the
136 | # machine as the profit and this will be reflected the next time “report” is triggered. E.g.
137 | # Water: 100ml
138 | # Milk: 50ml
139 | # Coffee: 76g
140 | # Money: $2.5
141 | # c. If the user has inserted too much money, the machine should offer change.
142 | # E.g. “Here is $2.45 dollars in change.” The change should be rounded to 2 decimal
143 | # places.
144 |
145 | # TODO: 7. Make Coffee.
146 | # a. If the transaction is successful and there are enough resources to make the drink the
147 | # user selected, then the ingredients to make the drink should be deducted from the
148 | # coffee machine resources.
149 | # E.g. report before purchasing latte:
150 | # Water: 300ml
151 | # Milk: 200ml
152 | # Coffee: 100g
153 | # Money: $0
154 | # Report after purchasing latte:
155 | # Water: 100ml
156 | # Milk: 50ml
157 | # Coffee: 76g
158 | # Money: $2.5
159 | # b. Once all resources have been deducted, tell the user “Here is your latte. Enjoy!”. If
160 | # latte was their choice of drink.
161 |
--------------------------------------------------------------------------------
/Day016-OOP-Coffee_Machine.py:
--------------------------------------------------------------------------------
1 | from menu import Menu, MenuItem
2 | from coffee_maker import CoffeeMaker
3 | from money_machine import MoneyMachine
4 |
5 | coffee_maker = CoffeeMaker()
6 | money_machine = MoneyMachine()
7 | menu = Menu()
8 | is_on = True
9 |
10 | while is_on:
11 | options = menu.get_items()
12 | choice = input(f"What would you like? ({options}): ")
13 | if choice == "off":
14 | is_on = False
15 | elif choice == "report":
16 | coffee_maker.report()
17 | money_machine.report()
18 | else:
19 | drink = menu.find_drink(choice)
20 | is_resource_enough = coffee_maker.is_resource_sufficient(drink)
21 | is_money_enough = money_machine.make_payment(drink.cost)
22 | if is_resource_enough and is_money_enough:
23 | coffee_maker.make_coffee(drink)
24 |
25 | # TODO 1. Prompt user by asking “What would you like? (espresso/latte/cappuccino):”
26 | # a. Check the user’s input to decide what to do next.
27 | # b. The prompt should show every time action has completed, e.g. once the drink is
28 | # dispensed. The prompt should show again to serve the next customer.
29 |
30 | # TODO 2. Turn off the Coffee Machine by entering “off” to the prompt.
31 | # a. For maintainers of the coffee machine, they can use “off” as the secret word to turn off
32 | # the machine. Your code should end execution when this happens.
33 |
34 | # TODO 3. Print report.
35 | # a. When the user enters “report” to the prompt, a report should be generated that shows
36 | # the current resource values. e.g.
37 | # Water: 100ml
38 | # Milk: 50ml
39 | # Coffee: 76g
40 | # Money: $2.5
41 |
42 | # TODO 4. Check resources sufficient?
43 | # a. When the user chooses a drink, the program should check if there are enough
44 | # resources to make that drink.
45 | # b. E.g. if Latte requires 200ml water but there is only 100ml left in the machine. It should
46 | # not continue to make the drink but print: “Sorry there is not enough water. ”
47 | # c. The same should happen if another resource is depleted, e.g. milk or coffee.
48 |
49 | # TODO 5. Process coins.
50 | # a. If there are sufficient resources to make the drink selected, then the program should
51 | # prompt the user to insert coins.
52 | # b. Remember that quarters = $0.25, dimes = $0.10, nickles = $0.05, pennies = $0.01
53 | # c. Calculate the monetary value of the coins inserted. E.g. 1 quarter, 2 dimes, 1 nickel, 2
54 | # pennies = 0.25 + 0.1 x 2 + 0.05 + 0.01 x 2 = $0.52
55 |
56 | # TODO 6. Check transaction successful?
57 | # a. Check that the user has inserted enough money to purchase the drink they selected.
58 | # E.g Latte cost $2.50, but they only inserted $0.52 then after counting the coins the
59 | # program should say “Sorry that's not enough money. Money refunded. ”.
60 | # b. But if the user has inserted enough money, then the cost of the drink gets added to the
61 | # machine as the profit and this will be reflected the next time “report” is triggered. E.g.
62 | # Water: 100ml
63 | # Milk: 50ml
64 | # Coffee: 76g
65 | # Money: $2.5
66 | # c. If the user has inserted too much money, the machine should offer change.
67 | # E.g. “Here is $2.45 dollars in change.” The change should be rounded to 2 decimal
68 | # places.
69 |
70 | # TODO 7. Make Coffee.
71 | # a. If the transaction is successful and there are enough resources to make the drink the
72 | # user selected, then the ingredients to make the drink should be deducted from the
73 | # coffee machine resources.
74 | # E.g. report before purchasing latte:
75 | # Water: 300ml
76 | # Milk: 200ml
77 | # Coffee: 100g
78 | # Money: $0
79 | # Report after purchasing latte:
80 | # Water: 100ml
81 | # Milk: 50ml
82 | # Coffee: 76g
83 | # Money: $2.5
84 | # b. Once all resources have been deducted, tell the user “Here is your latte. Enjoy!”. If
85 | # latte was their choice of drink.
86 |
87 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 100-days-of-code-in-python
2 | ##### Udemy Angela Yu's course that has 100 projects for students to make each day with classes of 1-2 hours duration.
3 | ###### This repository will store all the related projects. If you are interested in any code files, please run the code in an IDE for Python, though I recommend running it on Replit as some modules are imported based on the website.