def p0(): macro.moduleStart("") empty = {} programming_dictionary = {} ##Python Dictionaries programming_dictionary = { "Bug": "An error in a program that prevents the program from running as expected.", "Function": "A piece of code that you can easily call over and over again.", "Loop": "The action of doing something over and over again." } # Retrieving items from dictionary. # print(programming_dictionary["Function"]) # Adding new items to dictionary. # Create an empty dictionary. empty_dictionary = {} # Wipe an existing dictionary # programming_dictionary = {} # print(programming_dictionary) # Edit an item in a dictionary programming_dictionary["Bug"] = "A moth in your computer." print(programming_dictionary)
def p4(): macro.moduleStart("FizzBuzz") for number in range(1, 100): if number % 3 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number)
def p0(): macro.moduleStart("Fruits") fruits = ["Apple", "Peach", "Pear"] for i in fruits: print(i) print(i + " Pie") print(fruits)
def p4(): macro.moduleStart("5") chosen_word = random.choice(hangman_words.word_list) print(f'Pssst, the solution is {chosen_word}.') display = [] word_length = len(chosen_word) for _ in range(word_length): display += "_" lives = 6 print(hangman_art.logo) while '_' in display: cls() guess = input("Choose a letter: ").lower() if guess in display: print( f"You have already chosen this letter [{guess}]! Choose a different letter." ) continue if guess not in chosen_word: lives -= 1 print(f"You chose a letter not in the word.! You lose a life.") if lives == 0: print(hangman_art.stages[lives]) print(display) print("You lose!") exit() for i in range(word_length): if chosen_word[i] == guess: display[i] = guess print(hangman_art.stages[lives]) print(display) print("You win!")
def p2(): macro.moduleStart("BMI calculator") height = float(input("enter your height in m: \n")) weight = float(input("enter your weight in kg: \n")) bmi = weight / height**2 bmiAsInt = int(bmi) print(bmiAsInt)
def p3(): macro.moduleStart("") travel_log = [ { "country": "France", "visits": 12, "cities": ["Paris", "Lille", "Dijon"] }, { "country": "Germany", "visits": 5, "cities": ["Berlin", "Hamburg", "Stuttgart"] }, ] # 🚨 Do NOT change the code above # TODO: Write the function that will allow new countries # to be added to the travel_log. 👇 def add_new_country(country, visits, cities): travel_log.append({ "country": country, "visits": visits, "cities": cities }) # 🚨 Do not change the code below add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"]) print(travel_log)
def p3(): macro.moduleStart("4") word_list = ["ardvark", "baboon", "camel"] chosen_word = random.choice(word_list) print(f'Pssst, the solution is {chosen_word}.') display = [] word_length = len(chosen_word) for _ in range(word_length): display += "_" lives = 6 while '_' in display: clear() guess = input("Choose a letter: ").lower() if guess not in chosen_word: lives -= 1 if lives == 0: print(hangman_art.stages[lives]) print(display) print("You lose!") exit() for i in range(word_length): if chosen_word[i] == guess: display[i] = guess print(hangman_art.stages[lives]) print(display) print(f"{''.join(display)}") print("You win!")
def p0(): macro.moduleStart("1") word_list = ["ardvark", "baboon", "camel"] chosen_word = random.choice(word_list) guess = input("Choose a letter: ").lower() for i in chosen_word: if i == guess: print("Right") else: print("Wrong")
def p2(): macro.moduleStart("Scores") scores = input("Input a list of scores. e.g 99 82. ").split() highest = -1 for i in range(0, len(scores)): scores[i] = int(scores[i]) for i in scores: if i > highest: highest = i print(f"The highest score is {highest}")
def p0(): macro.moduleStart("Function Outputs") def format_name(f_name, l_name): return f_name.title() + " " + l_name.title() print( format_name(input("what is your name ? \n"), input("what is your last name ? \n")))
def p3(): macro.moduleStart("Range") total = 0 for number in range(1, 101): total += number print(total) total = 0 for number in range(2, 100, 2): total += number print(total)
def p1(): macro.moduleStart("BMI") height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) bmi = round(weight / height**2) if bmi < 18.5: print(f"Your BMI is {bmi}, you are underweight.") elif bmi < 25: print(f"Your BMI is {bmi}, you have a normal weight.") elif bmi < 30: print(f"Your BMI is {bmi}, you overweight.") elif bmi < 35: print(f"Your BMI is {bmi}, you are obese.") else: print(f"Your BMI is {bmi}, you are clinically obese.")
def p2(): macro.moduleStart("Treasure") row1 = ["⬜", "⬜", "⬜"] row2 = ["⬜", "⬜", "⬜"] row3 = ["⬜", "⬜", "⬜"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") map[int(position[0]) - 1][int(position[1]) - 1] = "X" print(f"{row1}\n{row2}\n{row3}")
def p0(): macro.moduleStart("Scope") enemies = 1 def increase_enemies(): enemies = 2 print(f"enemies inside function: {enemies}") increase_enemies() print(f"enemies outside function: {enemies}") # Local Scope def drink_potion(): potion_strength = 2 print(potion_strength) drink_potion() print(potion_strength) # Global Scope player_health = 10 def game(): def drink_potion(): potion_strength = 2 print(player_health) drink_potion() print(player_health) # There is no Block Scope game_level = 3 # noinspection PyUnboundLocalVariable def create_enemy(): enemies = ["Skeleton", "Zombie", "Alien"] if game_level < 5: new_enemy = enemies[0] print(new_enemy) # Modifying Global Scope enemies = 1 def increase_enemies(): print(f"enemies inside function: {enemies}") return enemies + 1 enemies = increase_enemies() print(f"enemies outside function: {enemies}") # Global Constants PI = 3.14159 URL = "https://www.google.com" TWITTER_HANDLE = "@yu_angela"
def p1(): macro.moduleStart("Height") heights = input("Input a list of heights. e.g 160 170. ").split() for i in range(0, len(heights)): heights[i] = int(heights[i]) sum = 0 for i in heights: sum += i len = 0 for _ in heights: len += 1 print(f"Average height is {int(sum / len)}")
def p2(): macro.moduleStart("") def prime_checker(number): for i in range(2, number): if number % i == 0: print("Number is Not Prime") return print("Number is Prime") n = int(input("Check this number: ")) prime_checker(number=n)
def p1(): macro.moduleStart("Paint") def paint_calc(height, width, cover): import math area = height * width cans = math.ceil(area / cover) print(f"You'll need {cans} cans of paint.") test_h = int(input("Height of wall: ")) test_w = int(input("Width of wall: ")) coverage = 5 paint_calc(height=test_h, width=test_w, cover=coverage)
def p1(): macro.moduleStart("2") word_list = ["ardvark", "baboon", "camel"] chosen_word = random.choice(word_list) print(f'Pssst, the solution is {chosen_word}.') display = [] word_length = len(chosen_word) for _ in range(word_length): display += "_" guess = input("Choose a letter: ").lower() for i in range(word_length): if chosen_word[i] == guess: display[i] = guess print(display)
def p3(): macro.moduleStart("Rock-Paper-Scissors") import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' game_images = [rock, paper, scissors] user_choice = int( input( "What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n" )) if user_choice >= 3 or user_choice < 0: print("You typed an invalid number, you lose!") return print(game_images[user_choice]) computer_choice = random.randint(0, 2) print("Computer chose:") print(game_images[computer_choice]) if user_choice == 0 and computer_choice == 2: print("You win!") elif computer_choice == 0 and user_choice == 2: print("You lose") elif computer_choice > user_choice: print("You lose") elif user_choice > computer_choice: print("You win!") elif computer_choice == user_choice: print("It's a draw")
def p4(): macro.moduleStart("Auction") import art print(art.logo) bids = {} while input("Any more bids? Type 'yes' or 'no'. ") == "yes": bids[input("What is your name?: ")] = input("What will you pay?: $") else: winner = "Null" high_bid = 0 for i in bids: new_bid = int(bids[i]) if new_bid > high_bid: winner = i high_bid = new_bid print(f"The winner is {winner}, with a bid of {high_bid}!")
def p4(): macro.moduleStart("Pizza") print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") addPepperoni = input("Do you want pepperoni? Y or N ") extraCheese = input("Do you want extra cheese? Y or N ") bill = 0 if size == "S": bill += 15 elif size == "M": bill += 20 else: bill += 25 if addPepperoni == "Y": if size == "S": bill += 2 else: bill += 3 if extraCheese == "Y": bill += 1 print(f"Your bill is: ${bill}")
def p2(): macro.moduleStart("Calculator") from art import logo from util.macro import cls def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 operations = {"+": add, "-": subtract, "*": multiply, "/": divide} def calculator(): print(logo) num1 = float(input("What's the first number?: ")) for symbol in operations: print(symbol) should_continue = True while should_continue: operation_symbol = input("Pick an operation: ") num2 = float(input("What's the next number?: ")) calculation_function = operations[operation_symbol] answer = calculation_function(num1, num2) print(f"{num1} {operation_symbol} {num2} = {answer}") if input(f"Type 'y' to continue calculating with {answer}," f" or type 'n' to start a new calculation: ") == 'y': num1 = answer else: should_continue = False # print(space) cls() calculator() calculator()
def p1(): macro.moduleStart("DEBUGGING2") year = int(input("Which year do you want to check?")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year.") else: print("Not leap year.") else: print("Leap year.") else: print("Not leap year.") number = int(input("Which number do you want to check?")) if number % 2 == 0: print("This is an even number.") else: print("This is an odd number.") for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number)
def p5(): macro.moduleStart("Love") print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") combined = (name1 + name2).lower() t = combined.count("t") r = combined.count("r") u = combined.count("u") e = combined.count("e") true = t + r + u + e l = combined.count("l") o = combined.count("o") v = combined.count("v") e = combined.count("e") love = l + o + v + e score = int(str(true) + str(love)) if score < 10 or score > 90: print(f"Your score is {score}, you go together like coke and mentos.") elif score >= 40 or score <= 50: print(f"Your score is {score}, you are alright together.") else: print(f"Your score is {score}!")
def p4(): macro.moduleStart("Cipher End") 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'] def caesar(start_text, shift_amount, cipher_direction): end_text = "" if cipher_direction == "decode": shift_amount *= -1 for char in start_text: # TODO-3: What happens if the user enters a number/symbol/space? # Can you fix the code to keep the number/symbol/space when the text is encoded/decoded? # e.g. start_text = "meet me at 3" # end_text = "•••• •• •• 3" if char in alphabet: new_position = alphabet.index(char) + shift_amount end_text += alphabet[new_position] else: end_text += char print(f"Here's the {cipher_direction}d result: {end_text}") # TODO-1: Import and print the logo from art.py when the program starts. from art import logo print(logo) # TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program? # e.g. Type 'yes' if you want to go again. Otherwise type 'no'. # If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again? # Hint: Try creating a while loop that continues to execute the program if the user types 'yes'. should_end = False while not should_end: direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) # TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet? # Try running the program and entering a shift number of 45. # Add some code so that the program continues to work even if the user enters a shift number greater than 26. # Hint: Think about how you can use the modulus (%). shift = shift % 26 caesar(start_text=text, shift_amount=shift, cipher_direction=direction) restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n") if restart == "no": should_end = True print("Goodbye")
def p5(): macro.moduleStart("Password") import random 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' ] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] print("Welcome to the PyPassword Generator!") nr_letters = int( input("How many letters would you like in your password?\n")) nr_symbols = int(input(f"How many symbols would you like?\n")) nr_numbers = int(input(f"How many numbers would you like?\n")) # Easy # password = "" # for i in range(1, nr_letters+1): password += random.choice(letters) # for i in range(1, nr_symbols+1): password += random.choice(symbols) # for i in range(1, nr_numbers+1): password += random.choice(numbers) # print(password) # Hard Level password_list = [] for char in range(1, nr_letters + 1): password_list.append(random.choice(letters)) for char in range(1, nr_symbols + 1): password_list += random.choice(symbols) for char in range(1, nr_numbers + 1): password_list += random.choice(numbers) print(password_list) random.shuffle(password_list) print(password_list) password = "" for char in password_list: password += char print(f"Your password is: {password}")
def p1(): macro.moduleStart("Guess") import random print("Welcome to the number guessing game.") mode = input("Type 'easy' or 'hard'.\n") if mode == 'hard': lives = 5 else: lives = 10 target = random.randint(1, 100) while lives > 0: print(f"You have {lives} attempts remaining.") guess = int(input("Make a guess: ")) if guess == target: print("Correct! You win.") input("Press Enter to continue...\n") p1() if guess > target: print("Too high.") if guess < target: print("Too low.") lives -= 1 print("You lose! No attempts remain.") input("Press Enter to continue...\n") p1()
def p1(): macro.moduleStart("Leap") def is_leap(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False def days_in_month(year, month): month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if is_leap(year) and month == 2: return 29 return month_days[month - 1] # 🚨 Do NOT change any of the code below year = int(input("Enter a year: ")) month = int(input("Enter a month: ")) days = days_in_month(year, month) print(days)
def p6(): macro.moduleStart("Treasure") print(''' ******************************************************************************* | | | | _________|________________.=""_;=.______________|_____________________|_______ | | ,-"_,="" `"=.| | |___________________|__"=._o`"-._ `"=.______________|___________________ | `"=._o`"=._ _`"=._ | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______ | | __.--" , ; `"=._o." ,-"""-._ ". | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________ | |o`"=._` , "` `; .". , "-._"-._; ; | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______ | | |o; `"-.o`"=._`` '` " ,__.--o; | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________ ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____ /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_ ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____ /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_ ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____ /______/______/______/______/______/______/______/______/______/______/_____ / ******************************************************************************* ''') print("Welcome to Treasure Island.") print("Your mission is to find the treasure.") choice1 = input('You\'re at a cross road. Where do you want to go? Type "left" or "right" \n').lower() if choice1 == "left": choice2 = input( 'You\'ve come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across. \n').lower() if choice2 == "wait": choice3 = input( "You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose? \n").lower() if choice3 == "red": print("It's a room full of fire. Game Over.") elif choice3 == "yellow": print("You found the treasure! You Win!") elif choice3 == "blue": print("You enter a room of beasts. Game Over.") else: print("You chose a door that doesn't exist. Game Over.") else: print("You get attacked by an angry trout. Game Over.") else: print("You fell into a hole. Game Over.")
def p3(): macro.moduleStart("Rollercoaster") print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) bill = 0 if height >= 120: print("You can ride the rollercoaster!") age = int(input("What is your age? ")) if age < 12: bill = 5 print("Child tickets are $5.") elif age <= 18: bill = 7 print("Youth tickets are $7.") elif 45 <= age <= 55: print("Everything is going to be ok. Have a free ride on us!") else: bill = 12 print("Adult tickets are $12.") wantsPhoto = input("Do you want a photo taken? Y or N. ") if wantsPhoto == "Y": bill += 3 print(f"Your final bill is ${bill}") else: print("Sorry, you have to grow taller before you can ride.")