height = float(input("Enter your height in m: "))
weight = float(input("Enter your weight in kg: "))
BMI = float(weight) / float(height)**2
BMI_round = round(BMI, 2)
if BMI_round < 18.5:
print(f"Your BMI is {BMI_round}, you are underWeight.")
elif BMI_round < 25:
print(f"Your BMI is {BMI_round}, you have a normal weight.")
elif BMI_round < 30:
print(f"Your BMI is {BMI_round}, you slightly overweight.")
elif BMI_round < 35:
print(f"Your BMI is {BMI_round}, you are obese.")
else:
print(f"Your BMI is {BMI_round}, you are clinically obese. ")
Calculating the numbers of years left till you reach 90
age = input("What is your current age? \n")
TotalDays = (90*365)
ageEntered = (int(age)*365)
daysLeft = (TotalDays-ageEntered)
weeksLeft=int(daysLeft/7)
monthsLeft=int(daysLeft/365*12)
yearsLeft=int(daysLeft/365)
print(f"You have {daysLeft} days or {weeksLeft} weeks or {monthsLeft} months or {yearsLeft} years left till you 90.")
Tip Calculator
-------------------------------------------------
print("Welcome to the tip calculator.")
bill= float(input("What is the total bill? R"))
tip = int(input("What percentage tip would you like to give? 10, 12 or 15. "))
people = int(input("How many people to split the bill? "))
bill_with_tip = tip/100 * bill + bill
bill_per_person = bill_with_tip / people
final_amount1 = round(bill_per_person,2)
# this will display two figures in the decimal place
# eg. instead of 33.6 it will give 33.60
final_amount2 = "{:.2f}".format(bill_per_person)
print(f"Each person should pay: R{final_amount1}")
print(f"Each person should pay: R{final_amount2}")
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 = 60
print("Child tickets are R60.")
elif age <= 18:
bill = 120
print("Youth tickets are R120.")
elif age >= 45 and age <= 55:
bill = 0
print("Everything is going to be ok. Have a free ride on us!")
else:
bill = 150
print("Adult tickets are R150.")
wants_photo = input("Do you want a photo taken? Y or N. ")
if wants_photo == "Y":
bill = bill + 80
print(f"Your final bill is R{bill}")
else:
print("Sorry, you have to grow taller before you can ride.")
Modulo Function
------------------------------------------
number = int(input("Which number do you want to check? "))
if number %2 == 0:
print("This number is EVEN!")
else:
print("This number is ODD!")
Is it a Leap year?
---------------------------------------
year = int(input("Which year do you want to check? "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("This is a Leap year")
else:
print("Not a leap year")
else:
print("This is a Leap year")
else:
print("This NOT a leap year")
Pizza Deliveries order
-------------------------------------------
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
extra_cheese = input("Do you want extra cheese? Y or N ")
bill = 0
if size == "S":
bill += 80
if size == "M":
bill += 105
else:
bill += 120
if add_pepperoni == "Y":
if size == "S":
bill += 20
else:
bill += 30
if extra_cheese == "Y":
bill += 15
print(f"Your total will be R{bill}.")
Love Calculator!
------------------------------------------
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
if (int_score < 10) or (int_score > 90) :
print(f"Your score is {int_score}, you go together like coke and mentos.")
elif (int_score >= 40) and (int_score <= 50):
print(f"Your score is {int_score}, you are alright together")
else:
print(f"Your score is {int_score}")
Treasure Island
---------------------------------
print('''
*********************************************************************
____/______/______/_____/______/_______/______/______/______/_______/___
/______/______/______/______/_______/______/______/______/______/_______
____/______/______/______/__ ____/_____/______/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_
____/______/______/_____/______/_______/______/______/______/_______/___
/______/______/______/______/_______/______/______/______/______/_______
____/______/______/______/__ ____/_____/______/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_
********************************************************************
''')
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.")
Random Function
------------------------------------
import random
# Split string method
names_string = input("Give me everybody's names, seperated by a comma. ")
names = names_string.split(", ")
#Get the total number of items in list.
num_items = len(names)
#Generate random numbers between 0 and the last index.
random_choice = random.randint(0, num_items - 1)
#Pick out random person from list of names using the random number.
person_who_will_pay = names[random_choice]
print(person_who_will_pay + " is going to buy the meal today!")
Random Name Selector
-------------------------------------------------
import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# total_height = sum(student_heights)
total_height =0
for height in student_heights:
total_height += height
# print(total_height)
# number_of_students = len(student_heights)
number_of_students =0
for students in student_heights:
number_of_students += 1
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
highest_score = 0
for score in student_scores:
if score > highest_score:
highest_score = score
print(f"The highest score in the class is: {highest_score}")
FizzBuzz Game.
-------------------------------------------------
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)
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"))
#Eazy Level
# password = ""
# for char in range(1, nr_letters + 1):
# password += random.choice(letters)
# for char in range(1, nr_symbols + 1):
# password += random.choice(symbols)
# for char 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)
# This is saved as main.py #and the list of words would have been save in hangman_words.py
import random
from hangman_art import stages, logo
from hangman_words import word_list
from replit import clear
display = []
for _ in range(word_length):
display += "_"
while not game_is_finished:
guess = input("Guess a letter: ").lower()
#Use the clear() function imported from replit to clear the output between guesses.
clear()
if guess in display:
print(f"You've already guessed {guess}")
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(f"{' '.join(display)}")
if guess not in chosen_word:
print(f"You guessed {guess}, that's not in the word. You lose a life.")
lives -= 1
if lives == 0:
game_is_finished = True
print(f"You lose. The word was: {chosen_word}")
if not "_" in display:
game_is_finished = True
print("You win.")
print(stages[lives])
Calc No. of Paint Tins.
-------------------------------------------------
import math
def paint_calc(height, width, cover):
area = height * width
num_of_cans = math.ceil(area/cover)
print(f"You will need {num_of_cans} cans to paint the wall.")
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)
Prime Number Checker.
-------------------------------------------------
def prime_checker(number):
is_prime = True
for i in range(2,number):
if number % i == 0:
is_prime = False
if is_prime:
print("It is a prime Number.")
else:
print("It is NOT a prime Number.")
n = int(input("Check this number: "))
prime_checker(number=n)
totFlower = 0
for x in range(1,Tn+1):
y=int(x+1)
Flower = pow(2,y)
totFlower += Flower
print(f"The number for Flower Effect will be {totFlower}")
print (f"The number for Triangle will be {triFormula}")
print (f"The number for Square will be {squFormula}")
print (f"The number for Rectangle will be {rectFormula}")
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:
position = alphabet.index(char)
new_position = position + 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
restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
if restart == "no":
should_end = True
print("Goodbye")
Highest Bid.
-------------------------------------------------
from replit import clear
from art import logo
print(logo)
bids = {}
bidding_finished = False
def find_highest_bidder(bidding_record):
highest_bid = 0
winner = ""
# bidding_record = {"Angela": 123, "James": 321}
for bidder in bidding_record:
bid_amount = bidding_record[bidder]
if bid_amount > highest_bid:
highest_bid = bid_amount
winner = bidder
print(f"The winner is {winner} with a bid of ${highest_bid}")
while not bidding_finished:
name = input("What is your name?: ")
price = int(input("What is your bid?: $"))
bids[name] = price
should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
if should_continue == "no":
bidding_finished = True
find_highest_bidder(bids)
elif should_continue == "yes":
clear()
Capitalize the first letter.
-------------------------------------------------
def new_name(f_name,l_name):
if f_name == "" or l_name =="":
return "You didn't provide a valid input."
new_f_name_adj = f_name.title()
new_l_name_adj = l_name.title()
return f"{new_f_name_adj} {new_l_name_adj}"
print(new_name(input("Enter your name? "), input("What is your last name? ")))
Calc No. of days in a month.
-------------------------------------------------
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):
if month > 12 or month < 1:
return "Invalid 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]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
Calculator
-------------------------------------------------
#Calculator
from art import logo
#Add
def add(n1,n2):
return n1+n2
if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to restart. : ") == "y":
num1 = answer
else:
should_continue =False
calculator()
calculator()
Blackjack
-------------------------------------------------
import random
from replit import clear
from art import logo
def deal_card():
"""Returns a random card from the deck."""
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
def calculate_score(cards):
"""Take a list of cards and return the score calculated from the cards"""
if sum(cards) == 21 and len(cards) == 2:
return 0
if 11 in cards and sum(cards) > 21:
cards.remove(11)
cards.append(1)
return sum(cards)
def compare(user_score, computer_score):
if user_score > 21 and computer_score > 21:
return "You went over. You lose"
if user_score == computer_score:
return "Draw "
elif computer_score == 0:
return "Lose, opponent has Blackjack"
elif user_score == 0:
return "Win with a Blackjack "
elif user_score > 21:
return "You went over. You lose "
elif computer_score > 21:
return "Opponent went over. You win "
elif user_score > computer_score:
return "You win "
else:
return "You lose "
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not is_game_over:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f" Your cards: {user_cards}, current score: {user_score}")
print(f" Computer's first card: {computer_cards[0]}")
if user_score == 0 or computer_score == 0 or user_score > 21:
is_game_over = True
else:
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == "y":
user_cards.append(deal_card())
else:
is_game_over = True
print(f" Your final hand: {user_cards}, final score: {user_score}")
print(f" Computer's final hand: {computer_cards}, final score: {computer_score}")
print(compare(user_score, computer_score))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clear()
play_game()
Higher or Lower
-------------------------------------------------
import random
from art import logo,vs
from game_data import data
from replit import clear
def random_data():
return random.choice(data)
def data_format(account):
name = account["name"]
description = account["description"]
country = account["country"]
return f"{name}, a {description} from {country}"
def check_guess(guess,a_count,b_count):
if a_count > b_count:
return guess == "a"
else:
return guess == "b"
guess = input (f"Who has the most followers? Type 'A' or 'B': ").lower()
a_follower_count = account_a["follower_count"]
b_follower_count = account_b["follower_count"]
clear()
print(logo)
if is_correct:
score += 1
print(f"You Right!, your score is {score}.")
else:
still_playing = False
print(f"Sorry...you wrong!, your final score is {score}." )
def is_resource_sufficient(order_ingredients):
"""Returns True when order can be made, False if ingredients are insufficient."""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"Sorry there is not enough {item}.")
return False
return True
def process_coins():
"""Returns the total calculated from coins inserted."""
print("Please insert coins.")
total = int(input("how many quarters?: ")) * 0.25
total += int(input("how many dimes?: ")) * 0.1
total += int(input("how many nickles?: ")) * 0.05
total += int(input("how many pennies?: ")) * 0.01
return total
def is_transaction_successful(money_received, drink_cost):
"""Return True when the payment is accepted, or False if money is insufficient."""
if money_received >= drink_cost:
change = round(money_received - drink_cost, 2)
print(f"Here is ${change} in change.")
global profit
profit += drink_cost
return True
else:
print("Sorry that's not enough money. Money refunded.")
return False
def make_coffee(drink_name, order_ingredients):
"""Deduct the required ingredients from the resources."""
for item in order_ingredients:
resources[item] -= order_ingredients[item]
print(f"Here is your {drink_name} ☕️. Enjoy!")
is_on = True
while is_on:
choice = input("What would you like? (espresso/latte/cappuccino): ")
if choice == "off":
is_on = False
elif choice == "report":
print(f"Water: {resources['water']}ml")
print(f"Milk: {resources['milk']}ml")
print(f"Coffee: {resources['coffee']}g")
print(f"Money: ${profit}")
else:
drink = MENU[choice]
if is_resource_sufficient(drink["ingredients"]):
payment = process_coins()
if is_transaction_successful(payment, drink["cost"]):
make_coffee(choice, drink["ingredients"])