I have a quick question for you all. I'm currently working on an sample Airline reservation system and I'm having difficulties displaying the total amount discounted if the user is a frequent flyer (10% discount rate). Below is my code:
user_people = int(raw_input("Welcome to Ramirez Airlines! How many people will be flying?"))
user_seating = str(raw_input("Perfect! Now what type of seating would your party prefer?"))
user_luggage = int(raw_input("Thanks. Now for your luggage, how many bags would you like to check in?"))
user_frequent = str(raw_input("Got it. Is anyone in your party a frequent flyer with us?"))
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
luggage_total = user_luggage * 50
import time
print time.strftime("Date and time confirmation: %Y-%m-%d %H:%M:%S")
seats_total = 0
if user_seating == 'economy':
seats_total = user_people * 916
print ('The total amount for your seats is: $'),seats_total
elif user_seating == 'business':
seats_total = user_people * 2650
print ('The total amount for your seats is: $'),seats_total
else:
print ('The total amount for your seats is: $'),user_people * 5180
print ('The total amount of your luggage is: $'),luggage_total
print ('Your subtotal for your seats and luggage is $'), luggage_total + seats_total
discount_amount = 0
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
after_discount = before_discount * discount_rate
discount_amount = before_discount - after_discount
print discount_amount
else:
print ('Sorry, the discount only applies to frequent flyers!')
While I'm not receiving an error, my output is incorrect. This is what is being displayed:
Discount amount of 1738.8
This obviously is incorrect as that is the price after the discount. I'm trying to display the total DISCOUNT as well as the price AFTER the discount has been applied.
Any help would be appreciated! Thanks!
You have more than one bug. First, in the else of the first if, you don't compute seat_total, so following computations will crash -- you just do
print ('The total amount for your seats is: $'),user_people * 5180
rather than the obviously needed
seat_total = user_people * 5180
print ('The total amount for your seats is: $'), seat_total
(the parentheses are useless but they don't hurt so I'm letting them be:-).
Second, look at your logic for discounts:
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
after_discount = before_discount * discount_rate
discount_amount = before_discount - after_discount
You're saying very explicitly that with a discount the user pays 1/10th of the list price -- then you complain about it in your Q!-)
It is, again, obvious (to humans reading between the lines -- never of course to computers:-), that in sharp contrast to what you say, what you actually mean is:
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
discount_amount = before_discount * discount_rate
after_discount = before_discount - discount_amount
Related
I'm trying to write a script that acts as a crypto program that generates a pseudo price of bitcoin, saves the bitcoin into a wallet, and monitors buying/selling transactions done by the script into a ledger, all via a menu. I've already created other classes (Wallet, MyDate, GetLive) that work to store bitcoins, display the live date and time, and generate a random live price for bitcoin per activity (buy/sell/deposit). For the Ledger class, I set up an empty list, trans, that acts as an empty list that will store each transaction done via the append statement, and have the history() function set up so that it prints out each transaction in the trans list. When I try to perform this, all it prints out is just the statement "Transaction History" and not the list of the buy/sell transactions, but when I use the print statement within a for loop to print out the list, things come out twice, which confuses me. I even tried replicating this in the "buy" and "sell" options, and they correctly show how I want the transactions to show up. I think there's something I'm not understanding properly, as I feel the solution is likely simple for this. Does anyone know the best way to go about setting up the Ledger class to properly print out the transaction history?
I have my whole coding displayed below for the crypto program:
from datetime import datetime
import random
balance = 75000 # This provides the user with $75,000 to invest.
num_coins = 0 # This is the amount of BTC the user starts out with.
z = 0 # This initializes the seed value for the random price for bitcoin that is determined by the GetLive() class.
trans = [] # This will be the empty list to which the buy/sell transactions will be added to.
class Wallet: # This class will 1) store the ticker symbol for the bitcoin 2) store how many coins the user has
# 3) prints the information out, including ticker symbol (BTC) for the coin and number of coins currently in wallet,
# and 4) use a setter function to add coins to wallet and a getter function to fetch number of coins in wallet.
symbol = "(BTC)"
def getinfo(self):
print(self.symbol, " : ", self.num_coins)
def set_coins(self, x):
self.num_coins = x
def get_coins(self):
return self.num_coins
class MyDate: # This class returns both the date and time.
def __init__(self):
self.now = datetime.now()
def dmy(self):
self.now = datetime.now()
dt = self.now.strftime("%m/%d/%Y")
print("Date:", dt)
return dt
def hms(self):
self.now = datetime.now()
t = self.now.strftime("%H:%M:%S")
print("Time:", t)
return t
class GetLive: # This class generates a random, live price for Bitcoin.
def price(self): # This method will as a pseudo random price for bitcoin (between 55-65K)
random.seed(z) # This sets the initial random seed that will be used to generate a random price for bitcoin
return random.randint(55000, 65000) # Returns a random live price for bitcoin
class Ledger: # This class defines the Ledger as a class that will store buy/sell transactions and print the history.
def __init__(self):
self.trans = []
def add(self, tran):
self.trans.append(tran)
def multiadd(self, *tranargs):
self.trans.extend(tranargs)
def multiadd2(self, tranargs):
self.trans.extend(tranargs)
def getTrans(self):
return self.trans
def history(self): # This prints the history of the buy and sell transactions, including date & time.
d = MyDate()
print("\nTransaction History\n")
for i in self.trans:
for buy in i:
print("On", d.dmy(), " at ", d.hms(), ", you bought " + str(buy), "" + Wallet.symbol, "for $",
buy_amount)
for sell in i:
print("On", d.dmy(), " at ", d.hms(), ", you sold " + str(sell), "" + Wallet.symbol, "for $",
sell_amount)
# Here, this is where the main section of the Bitcoin program is to be run.
while True:
current_price = GetLive()
L = Ledger()
print("********* Menu ************")
print(" 0 - Price of Bitcoin", Wallet.symbol)
print(" 1 - Buy ")
print(" 2 - Sell ")
print(" 3 - Deposit cash")
print(" 4 - Display # of bitcoins in my wallet")
print(" 5 - Display balance")
print(" 6 - Display transaction history")
print(" 7 - Exit")
i = int(input("Please enter your choice: "))
if i == 0:
print("\nCurrent price of Bitcoin", Wallet.symbol, "= $", current_price.price(), "\n")
elif i == 1:
buy = float(input("\nEnter how much BTC you want to buy: "))
buy_amount = int(current_price.price()) * (float(buy))
print("\nThe total cost for " + str(buy) + " " + Wallet.symbol + " is $", buy_amount, ". Transaction complete."
"\n")
if buy_amount < balance:
d = MyDate()
balance -= float(buy_amount)
num_coins += float(buy)
z = z + 1 # This changes the random seed value so that the GetLive class will generate a new random price
trans.append([d.dmy(), d.hms(), ", you bought", buy, Wallet.symbol, "for $", buy_amount])
print("On", d.dmy(), " at ", d.hms(), ", Bought " + str(buy), "" + Wallet.symbol, "for $", buy_amount)
else:
print("\nError: you have an insufficient balance...\n")
elif i == 2:
sell = float(input("\nEnter how much BTC you want to sell: "))
sell_amount = int(current_price.price()) * (float(sell))
print("\nThe total value for " + str(sell) + " " + Wallet.symbol + " is $", sell_amount, ". Transaction "
"complete.\n")
if num_coins > 0:
d = MyDate()
balance += float(sell_amount)
num_coins -= float(sell)
z = z + 1 # This changes the random seed value so that the GetLive class will generate a new random price
trans.append([d.dmy(), d.hms(), ',', "you sold", sell, Wallet.symbol, "for $", sell_amount])
print("On", d.dmy(), " at ", d.hms(), ", Sold " + str(sell), "" + Wallet.symbol, "for $", sell_amount)
else:
print("\nError: you have insufficient coins...\n")
elif i == 3:
cash = float(input("\nEnter how much cash you want to deposit: $"))
balance = float(balance) + cash
z = z + 1 # This changes the random seed value so that the GetLive class will generate a new random price
print("\nYou deposited $", cash, ". Your new balance is $", balance, "\n")
elif i == 4:
print("\nYou currently have", num_coins, Wallet.symbol, "in your wallet.")
elif i == 5:
print("\nCurrent Balance: $", balance, "\n")
elif i == 6:
for y in trans:
print(" >> ", trans)
# L.history() This is supposed to display the list of buy and sell transactions
elif i == 7:
exit(0)
else:
print("Wrong input")
And this is what comes out as I attempt each option, including the Ledger class in option 6:
********* Menu ************
0 - Price of Bitcoin (BTC)
1 - Buy
2 - Sell
3 - Deposit cash
4 - Display # of bitcoins in my wallet
5 - Display balance
6 - Display transaction history
7 - Exit
Please enter your choice: 0
Current price of Bitcoin (BTC) = $ 61311
********* Menu ************
0 - Price of Bitcoin (BTC)
1 - Buy
2 - Sell
3 - Deposit cash
4 - Display # of bitcoins in my wallet
5 - Display balance
6 - Display transaction history
7 - Exit
Please enter your choice: 1
Enter how much BTC you want to buy: 0.5
The total cost for 0.5 (BTC) is $ 30655.5 . Transaction complete.
Date: 12/19/2021
Time: 22:28:25
Date: 12/19/2021
Time: 22:28:25
On 12/19/2021 at 22:28:25 , Bought 0.5 (BTC) for $ 30655.5
********* Menu ************
0 - Price of Bitcoin (BTC)
1 - Buy
2 - Sell
3 - Deposit cash
4 - Display # of bitcoins in my wallet
5 - Display balance
6 - Display transaction history
7 - Exit
Please enter your choice: 2
Enter how much BTC you want to sell: 0.2
The total value for 0.2 (BTC) is $ 11440.2 . Transaction complete.
Date: 12/19/2021
Time: 22:28:33
Date: 12/19/2021
Time: 22:28:33
On 12/19/2021 at 22:28:33 , Sold 0.2 (BTC) for $ 11440.2
********* Menu ************
0 - Price of Bitcoin (BTC)
1 - Buy
2 - Sell
3 - Deposit cash
4 - Display # of bitcoins in my wallet
5 - Display balance
6 - Display transaction history
7 - Exit
Please enter your choice: 6
>> [['12/19/2021', '22:28:25', ', you bought', 0.5, '(BTC)', 'for $', 30655.5], ['12/19/2021', '22:28:33', ',', 'you sold', 0.2, '(BTC)', 'for $', 11440.2]]
>> [['12/19/2021', '22:28:25', ', you bought', 0.5, '(BTC)', 'for $', 30655.5], ['12/19/2021', '22:28:33', ',', 'you sold', 0.2, '(BTC)', 'for $', 11440.2]]
Transaction History
********* Menu ************
0 - Price of Bitcoin (BTC)
1 - Buy
2 - Sell
3 - Deposit cash
4 - Display # of bitcoins in my wallet
5 - Display balance
6 - Display transaction history
7 - Exit
Please enter your choice: 7
Process finished with exit code 0
I am trying to challenge myself by creating a program from scratch to help work out errors, etc.
So I did a simple stamp shop which has different values for various books of stamps. I now want to calculate the price per piece after collecting taxes. I have tried to setup an if/elif/else statement to calculate the price per stamp. Here is the code that I have so far.
'''
# what is the price per stamp including taxes
number_of_stamps_purchased = 10
# calculate government sales taxes on stamps 13%
sales_tax = 0.13
# number of stamps in each booklet
single_stamp = 1
book_of_five = 5
book_of_ten = 10
book_of_fifteen = 15
book_of_twenty = 20
# pricing chart for each book of stamps
single = 1.50
five = 7.00
ten = 10.00
fifteen = 14.00
twenty = 16.00
# price list for customers
print('''Welcome to my stamp shop!
Please review our price list:
Single Stamp $1.50
Book of 5 Stamps $7.00
Book of 10 Stamps $10.00
Book of 15 Stamps $14.00
Book of 20 Stamps $16.00
(Does not include sales tax)''')
# conditions for total price calculation of stamps purchased
def stamp_cost(price_per_piece):
if number_of_stamps_purchased <= 4:
print('''
Your stamp cost:''',((single * sales_tax / single_stamp) + single) * number_of_stamps_purchased)
elif number_of_stamps_purchased == 5:
print('''
Your stamp cost:''',((five * sales_tax) + five))
elif number_of_stamps_purchased == 10:
print('''
Your stamp cost:''',((ten * sales_tax) + ten))
elif number_of_stamps_purchased == 15:
print('''
Your stamp cost:''',((fifteen * sales_tax) + fifteen))
elif number_of_stamps_purchased == 20:
print('''
Your stamp cost:''',((twenty * sales_tax) + twenty))
else:
print('Error')'''
# calculate the per piece price based on their savings when purchasing a book
print(total_price / number_of_stamps_purchased)
'''
You never declare a variable with the name total_price, so when you try and print with print(total_price / number_of_stamps_purchased) Python warns you about never defining it. You can fix this by defining a total_price before the last line. Perhaps like so:
def stamp_cost(): # I have removed the argument as it was unused.
if number_of_stamps_purchased <= 4:
total_price = ((single * sales_tax / single_stamp) + single) * number_of_stamps_purchased
print('''
Your stamp cost:''', total_price)
# The rest of the function with the same modification
return total_price
total_price = stamp_cost()
print(total_price / number_of_stamps_purchased)
Something like that should work a little better. The main problem as it as been previously pointed is that you never call your fonction stamp_cost. So, what you need to do is affect the result of what you are doing with stamp_cost to your variable total_price.
# calculate government sales taxes on stamps 13%
sales_tax = 0.13
# pricing chart for each book of stamps
single = 1.50
five = 7.00
ten = 10.00
fifteen = 14.00
twenty = 16.00
# number of stamps in each booklet
single_stamp = 1
book_of_five = 5
book_of_ten = 10
book_of_fifteen = 15
book_of_twenty = 20
# price list for customers
print('''Welcome to my stamp shop!
Please review our price list:
Single Stamp $1.50
Book of 5 Stamps $7.00
Book of 10 Stamps $10.00
Book of 15 Stamps $14.00
Book of 20 Stamps $16.00
(Does not include sales tax)
''')
# conditions for total price calculation of stamps purchased
def stamp_cost():
if number_of_stamps_purchased <= 4:
total_price = (single * sales_tax / single_stamp + single) * number_of_stamps_purchased
print('Your total cost:', total_price)
elif number_of_stamps_purchased == 5:
total_price = five * sales_tax + five
print('Your total cost:',total_price)
elif number_of_stamps_purchased == 10:
total_price = ten * sales_tax + ten
print('Your total cost:', total_price)
elif number_of_stamps_purchased == 15:
total_price = fifteen * sales_tax + fifteen
print('Your total cost:',total_price)
elif number_of_stamps_purchased == 20:
total_price = twenty * sales_tax + twenty
print('Your total cost:',total_price)
else:
print('Error')
return total_price
number_of_stamps_purchased = 10
print('Number of stamp purchase:',number_of_stamps_purchased)
total_price = stamp_cost()
# calculate the per piece price based on their savings when purchasing a book
print('Price per piece:',round(total_price / number_of_stamps_purchased,2))
I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()
I have some code written for a school project but it shows errors on all of the cost parts of my code
fullname = input("whats your name?")
print("hello",fullname,)
print("room 1")
width=input("how wide is the room?")
length=input("how long is the room?")
area = float(length)*float(width)
print("the total area is",area,)
q = input("do you want another room?")
if q == "yes":
print("room 2 ")
widtha=input("how wide is the room?")
lengtha=input("how long is the room?")
areaa = float(lengtha) * float(widtha)
print("the total area is",areaa,".")
else:
flooring=input("do you want to have wood flooring(10) or tiled flooring(15)")
if flooring == "wood":
costaa = float(area)+ float(areaa)*10
print("total cost is ",costaa,)
if flooring == "tiled":
costab = float(area)+ float(areaa)*15
print("total cost is £",costab,)
It will show NameError:costab or NameError:costaa as not defined depending which I select.
The answer to your problem is simple.
When the computer says: Do you want another room? and you say no, you are not defining the value of areaa at all. Therefore, the areaa does not exist because you didn't specify it. I've made some changed to your code to make it working, hope it help!
fullname = input("Whats Your Name?")
print("Hello", fullname)
print("\nRoom 1")
width = input("How wide is the room?")
length = input("How long is the room?")
area = float(length) * float(width)
print("The Total Area is", area)
q = input("\nDo you want Another Room? (y/n)")
if q == "y":
print("\nRoom 2")
width2 = input("How wide is the room?")
length2 = input("How long is the room?")
area2 = float(length2) * float(width2)
print("The Total Area is", area2,".")
flooring=input("\nDo you want to have Wood Flooring(10) or Tiled Flooring(15)? (wood/tiled)")
if flooring == 'wood':
cost = area + area2 * 10
print("Total Cost is ",cost)
if flooring == 'tiled':
cost2 = area + area2 * 15
print("Total Cost is ",cost2)
else:
flooring=input("\nDo you want to have Wood Flooring(10) or Tiled Flooring(15)? (wood/tiled)")
if flooring == 'wood':
cost = area * 10
print("Total Cost is ",cost)
if flooring == 'tiled':
cost2 = area * 15
print("Total Cost is ",cost2)
I have tested your code and runs ok on my pc. Maybe it's your configurations.
For python 2
input_variable = raw_input("Enter your name: ")
If you are using Python 3.x, raw_input has been renamed to input
I'm doing a project where I need to figure if my transactions will earn me a profit or hit me for a loss. It's based on buying and selling stocks with commission. I got the basic math concept all worked out. What I am struggling with is the last equation where I subtract the sale price from the purchase price. I need a statement (or two) that if the answer is positive, it will go to output saying I gained x amount of money. If the answer is negative, it will go to output saying I lost x amount of money.
What statements could I use where the Python program will know to send positive number to gain output and negative number to loss output?
Here's the code I wrote with your suggestion for if statement
number_of_shares = input("Enter number of shares: ")
purchase_price = input("Enter purchase price: ")
sale_price = input("Enter sale price: ")
price = number_of_shares * purchase_price
first_commission = price * .03
final_price = price - first_commission
sale = number_of_shares * sale_price
second_commission = sale * .03
last_price = sale - second_commission
net = final_price - last_price
if (net > 0):
print("After the transaction, you gained", net, "dollars.")
if (net < 0):
print("After the transaction, you lost", net, "dollars.")
I didn't realize I was putting the loss as a gain and vice versa so I swapped it around and changed the wording to make it more clear. I'm still stuck here's my updated code
number_of_shares = input("Enter number of shares: ")
purchase_price = input("Enter purchase price: ")
sale_price = input("Enter sale price: ")
price = number_of_shares * purchase_price
first_commission = price * .03
buy_price = price - first_commission
sale = number_of_shares * sale_price
second_commission = sale * .03
sell_price = sale - second_commission
net = sell_price - buy_price
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net, "dollars.")
After doing the code on paper, I saw my mistake (with the commission) and made changes. Now my issue is when the net is for a loss, the output gives me an negative number. How do i make it not negative? since I already have the statement- you lost x dollars. Hmm multiplying by negative 1? Here's what I did
number_of_shares = int(input("Enter number of shares: "))
purchase_price = float(input("Enter purchase price: "))
sale_price = float(input("Enter sale price: "))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .03)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .03)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")
Without seeing the code you have so far it's a bit hard to give you help, but I'll try anyways.
It sounds like you're looking for an if statement. The following will probably do what you want:
# Assuming total_money is the output of everything before
# positive number is gain, negative is loss
if total_money > 0:
print 'You gained ${}'.format(total_money)
else:
print 'You lost ${}'.format(total_money)
This is part of a concept called flow control. To learn more about it, you can look at https://docs.python.org/2/tutorial/controlflow.html
Try the following format:
net_change = sell_price - buy_price - commission
if (net_change >0):
print('Money! Money in the bank!\nYou have made $'+str(net_change))
else if (net_change <0):
print('Oh, sad deleterious day!\nYou have lost $'+str(net_change))
else:
print('You did not accomplish anything. You have broken even.')
This is a flow control path for three outcomes, Positive, Negative, and Neutral.
You'll find that flow control such as this is key to creating robust programs, it prevents the program from going to a place that it shouldn't.
Here is the code that worked
number_of_shares = int(input("Enter number of shares:"))
purchase_price = float(input("Enter purchase price:"))
sale_price = float(input("Enter sale price:"))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .03)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .03)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")