how to execute a class with some condition statements in python? - python

#Making a program "(subscribing for an entertainment)like Netflix" that would ask for users name then age.before they enter they should be on a legal age then if not print ("sorry you are not allowed to have a subscription").
If not. The code will continue then will ask for the users for their amount of money that they will pay and the higher the money the higher the discount price. Then will also asked how many months they will subscribe for the entertainment restricted (1,3,6,12 only) else the program will stop.
class Entertainment:
def __init__(self, subscription, price, term):
self.subscription = subscription
self.price = price
self.term = term
nameUser = input("Your name is,")
ageUser = int(input("Age:"))
if ageUser < 13:
return total_amount
subscription = float(input("Money Available: "))
if subscription <= 100:
price = subscription - 0.5
elif subscription in range(101 - 200):
price = subscription - 0.10
elif subscription in range(201 - 300):
price = subscription - 0.15
elif subscription >= 400:
price = subscription - 0.20
def MonthlySubs():
# Making this strictly 1,3,6,12 only and other numbers will not be accepted
use_months = float(input("(1,3,6,12) Only "))
if use_months == 1:
return price / 1
elif use_months == 3:
return price / 3
elif use_months == 6:
return price / 6
elif use_months == 12:
return price / 12
else:
print("Invalid Months of subscription")
break
#MAKING SOMETHING LIKE HOW PEOPLE SUBSCRIBE FOR PREMIUM BENEFITS
#problem is I don't understand how I will make these conditions connect to become a whole program
# Help me how I will have an output like this using classes:
>#Name: Mitchel
> #Age: 21
> #Money: 200
> #subscription months = 3
> #your payment amount is 209.5

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

I want to create a simple inventory management system using classes and data structures. I am new to OOP in python

The code should Capture products in stock (i.e. name, price, date supplied, supplier name, quantity), Retrieve the price when name is given upon each purchase and deducts the quantity in
stock, Calculate the total price for each purchase and prints value indicating date and time of
purchase, Sends an alert when quantity reaches 5 to shopkeeper and places order to supplier.
My code right now is not looping so that I can add a number of products then be able to access them, I tried using a while loop but it is running forever. Kindly help
import datetime
class Stock:
def __init__(self, name, price, supplier, quantity,date):
self.name = name
self.price = price
self.date = date
self.supplier = supplier
self. quantity = quantity
def check_item(self, name):
for i in range(len(ls)):
if (ls[i].name == name):
return i
def sale(self):
n = int(input("How many products to sale: "))
total = 0
for j in range(n):
name = input("Enter Product name : ")
quantity = int(input("Enter quantity: "))
i = obj.check_item(name)
if i and ls[i].quantity >= quantity:
ls[i].quantity -= quantity
if ls[i].quantity < 5:
print("Low Stock! Low Stock! Order Placed")
obj.place_order(name, ls[i].supplier, quantity+10)
print("....Uncle G Shop....")
print(datetime.date.today())
print("Product Name | Quantity | Cost $")
print(ls[i].name, end=" ")
print(quantity, end=" ")
print(ls[i].price * quantity)
total += ls[i].price * quantity
print("\n")
print("Total Cost----->", "$" + total)
else:
print("Product out of stock or not enough quantity")
def purchase(self):
name = input("Enter Product name: ")
date = datetime.date.today()
i = obj.check_item(name)
if i:
ls[i].quantity += int(input("Enter quantity: "))
ls[i].price = int(input("Enter product price: "))
ls[i].date = date
else:
quantity = int(input("Enter quantity: "))
price = int(input("Enter product price: "))
supplier = input("Enter Supplier: ")
ob = Stock(name, price, supplier, quantity, date)
ls.append(ob)
def place_order(self,name, supplier, quantity):
return name, supplier, quantity
def print_products(self):
def __repr__(self):
return str(self.name) + str(self.price) + str(supplier) + str(self.quantity) + str(self.date)
return __repr__
def main(self):
print("Welcome To Uncle G Shop")
print("choose an option below")
print("\n1.Enter a Product\n2.Make a sale \n3.See all Products\n4.Exit")
option = int(input("Enter option here: "))
while True:
if option == 1:
obj.purchase()
elif option == 2:
obj.sale()
elif option == 3:
obj.print_products()
elif option == 4:
print("Have a good day")
break
else:
print("Enter a valid input!")
# A list to add Products
ls = []
# an object of Stock class
obj = Stock('', 0, 0, 0, '')
obj.main()
Your main menu doesn't have a break from the while loop for option 4.
You also need to think again about how to use your class. At present, you have multiple methods referring to a variable, ls, created outside of the class. Either treat Stock as a class to deal with individual purchase records, or to deal with stock overall. You could maintain in the class itself a list of instances of the class and offer class methods, as well as instance methods, to manage that overall stock.

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

questions repeated 4x, float not callable, error on code

I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare

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

Categories

Resources