My variable is coming back as undefined in Python - python

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))

Related

How to use a class to print out elements of a list that contains transactions?

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

Arithmetic not being done on first dictionary entry?

class creditCard:
def __init__(self, limit, apr, balance):
self.limit = limit
self.apr = apr
self.balance = balance
self.charges = {}
self.payments = {}
def charge(self, amount, day):
# Charges the card, and stores the charge and day the charge was made in a dictionary.
# Returns false if the amount charged is greater than the limit.
if amount > self.limit - self.balance:
return False
self.charges[day] = amount
self.balance += amount
def payment(self, amount, day):
# When a payment is made the payment is stored in the payments dictionary with the corresponding day.
# Returns false is the payment amount is greater than the balance owed/limit.
if amount > self.limit - self.balance:
return False
self.payments[day] = amount
self.balance -= amount
def interest(self, balance):
# calculates and returns interest
return (balance * self.apr) / 365
def days_balance(self, balance_day):
balance_to_date = 0
months_interest = 0
for day in range(1, balance_day+1):
balance_to_date += self.charges.get(day, 0)
balance_to_date -= self.payments.get(day, 0)
months_interest += self.interest(balance_to_date)
if day % 30 == 0:
balance_to_date += months_interest
months_interest = 0
balance_to_date = round(balance_to_date, 2)
return "${}".format(balance_to_date)
I am supposed to be returning 411.99 for my second test case and I am getting 411.89 due to the dictionary not applying the interest for the first day. I can not figure out why it is doing that what so ever. Any help would be greatly appreciated. Below is my test case.
customer opens a credit card with 1k limit and 35% APR
customer charges $500 on opening day
15 days after opening he pays $200 (balance now 300)
25 days after opening he charges another $100 (balance now 400)
total balance at the end of the month is 411.99
customer1 = creditCard(1000, 0.35, 0)
customer1.charge(500, 1)
print(customer1.days_balance(30))
for i in customer1.charges:
print(customer1.charges.keys(), customer1.charges.values())
customer2 = creditCard(1000, 0.35, 0)
customer2.charge(500, 1)
customer2.payment(200, 15)
customer2.charge(100, 25)
print("Customers Balance on Day 26: " + customer2.days_balance(26))
print("Customers Balance on Day 30 with Interest: " +
customer2.days_balance(30))

Applying a discount and showing discounted rate in Python 2.7

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

MIT opencourseware - stuck on a basic issue, credit card minimum payment over a year calculation

Basically I'm pretty stuck on this issue, I've linked the question below, it's part 'b' I'm stuck on, or the second question in the document:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-4-machine-interpretation-of-a-program/MIT6_00SCS11_ps1.pdf
If I'm honest it's just got to the point where I'm totally confused! I've put my code below:
balance = float(raw_input('Vot is the outstanding balance? '))
InrAn = float(raw_input('Vot is the annual interest rate as a decimal? '))
month = 1
monthPay = 10
monthInr = InrAn/12.0
newBalance = balance
while balance > 0:
newBalance = newBalance * (1 + monthInr) - monthPay
month +=1
if month > 12:
month = 1
newBalance = balance
monthPay += 10
This does essentially nothing, I know, and it's not yet complete. If I add a 'print month' statement it just seems to show that the code just goes up to 12, then starts at 1 again. Any tips/prods in the right direction?
monthly_payment = 10.0
while True:
current_balance = start_balance
for month in range(1, 13):
current_balance = current_balance * (1. + monthly_rate) - monthly_payment
current_balance = round(current_balance, 2)
if current_balance <= 0.0:
break
if current_balance <= 0.0:
print("RESULT")
print("Monthly payment to pay off debt in 1 year: {}".format(int(monthly_payment)))
print("Number of months needed: {}".format(month))
print("Balance: {:0.2f}".format(current_balance))
break
monthly_payment += 10.0

Not getting right output...logic correct

My code is giving right results except for balance=3926. Lowest Payment: 370 whereas it should be 360.The program should print lowest monthly payment for given annual interest rate .Given an initial balance, code should compute the balance at the end of the year. we are trying our initial balance with a monthly payment of $10. If there is a balance remaining at the end of the year, we write code that would reset the balance to the initial balance, increase the payment by $10, and try again (using the same code!) to compute the balance at the end of the year, to see if this new payment value is large enough
annualInterestRate = 0.2
balance = 3926
monthlyinterestrate = annualInterestRate/12.0
remainingBalance = balance
month = 1
total = 0
payment = 10
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while(payment*12 < balance):
payment += 10
return payment
payment = CheckMinimumPayment(payment,balance)
while(month <= 12):
remainingBalance = remainingBalance - payment + (annualInterestRate / 12.0) * (remainingBalance - payment)
month += 1
total += payment
payment = CheckMinimumPayment(payment,total+remainingBalance)
print("Lowest Payment: " + str(payment))
The problem is that you're not re-iterating through the interest loop (what you have as while(month <= 12)) each time you try a new payment. Write that loop into a function, and call it each time you try a new payment. The total owed balance depends on the payment, since a larger payment each month means less interest added each month. Here's what I used:
annualInterestRate = 0.2
init_balance = 3926
monthlyInterestRate = annualInterestRate/12.0
init_payment = 10
def owedBalance(payment,balance):
""" Calculate total owed balance after one year
given an initial balance and montly payment"""
for month in range(12):
balance = (balance - payment) * (monthlyInterestRate + 1)
return payment*12 + balance
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while (payment*12 < owedBalance(payment, balance)):
payment += 10
return payment
min_payment = CheckMinimumPayment(init_payment,init_balance)
print("Lowest Payment: {}".format(min_payment))

Categories

Resources