I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter does not get saved into a variable so that when I enter another value it gets added onto a previous input. Code is below:
Purchase = int(input("How much was your purchase? "))
credit_balance = 0
credit_limit = 2000
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total == credit_limit:
print("You have reached your credit limit!", Total)
You'll need to introduce a while loop to keep it going. Try this:
credit_limit = 2000
credit_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total >= credit_limit:
print("You have reached your credit limit!", Total)
Note that this will keep it going indefinitely. You'll need to add logic for the user to input a command to exit. You can use something like:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? Or type Exit to exit."))
Then:
if Purchase == 'Exit':
exit()
Edit:
Here's a version that retains the balance each time. The key difference is that a variable can equal its previous value plus a change. I rewrote a few things for clarity.
credit_limit = 2000
current_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
current_balance = current_balance + Purchase
print("Your account value right now: ", current_balance)
if current_balance == credit_limit:
print("You have reached your credit limit!", current_balance)
You can get user input infinitely if you use a while loop:
credit_balance = 0
credit_limit = 2000
while True:
purchase = int(input("How much was your purchase? "))
credit_balance += purchase # add purchase to credit_balance
print("Your account value right now: ", credit_balance)
if credit_balance >= credit_limit:
print("You have reached/exceeded your credit limit!", Total)
A good exercise would be to add some logic to ensure purchases don't exceed the credit limit.
Related
I am working on my first project where I ask users if they are want to calculate an investment or bond. Within this I've tried to nest another if/elif/else statement after they input investment or bond to get the user to input the necessary information for either for me to make the calculation but Python is registering an error for when I want to ask users about the bond calculation. I've tried to make it as clear as possible below:
import math
#Menu Option for Users
print("Investment: Calculate the amount of interest you'll earn on your investment")
print("Bond: Calculate the amount you'll have to pay on your home loan")
type = input("Please input either Investment or Bond to proceed:")
#casefold removes case sensitivity so user can input with or without caps.
#Investment Calculation
if type.casefold() == "Investment":
#if user inputs investment, they need to input the following information
money = input("Please input your deposit amount: ")
ir = input("Please input your interest rate as a percentage: ")
time = input("Please input how long you plan to invest for in years: ")
interest = input("Please input if you would like simple or compound interest: ")
#initialisations
simple_ir_calc = 0
comp_ir_calc = 0
if interest.casefold() == "simple":
simple_ir_calc = money (1 + ((ir/100) * time))
print(f"You will make {simple_ir_calc} on your investment")
elif interest.casefold() == "compound":
comp_ir_calc = money * math.pow((1+ (ir/100)), time)
print(f"You will make {comp_ir_calc} on your investment")
else:
print("Error. Either enter simple or compound.")
#Bond calculation
elif type.casefold() == "Bond":
#user inputs info needed to calc bond
pv = input("Please enter the present value of your property: ")
ir_b = input("Please input the interest rate as a percentage: ")
time_m = input("Please enter the number of months needed to repay the bond: ")
repayment = 0
repayment = ((ir_b/12) * pv) / math.pow(1 - (1 +(ir_b/12)), (-time))
print(f"You will have to pay {repayment} each month.")
else:
print("Error. Either input investment or bond.")
I tried to fix the indentations - so now the only 2 problems that python highlights is the expressions on line 34 and 44.
Also as a sidenote the bond repayment formula is meant to be X = (ir.pv)/(1-(1+ir)^(-time))
I just included -time at the end but I have no idea if my formula works within python
I know this is probably riddled with errors, so if you see anything else please let me know! I am very new to both python and stackoverflow so sorry for so many questions within one :(
I think this sorts out the indentation but only you know your intentions. A general comment - the code all fails if the user does not enter precisely one of your expected answers. You should pick up input errors. This might be easiest using 'Enter 1 for A, 2 for B etc'.
import math
#initialisations
simple_ir_calc = 0
comp_ir_calc = 0
#Menu Option for Users
print("Investment: Calculate the amount of interest you'll earn on your investment")
print("Bond: Calculate the amount you'll have to pay on your home loan")
choose = input("Please input either Investment or Bond to proceed:")
#casefold removes case sensitivity so user can input with or without caps.
print(choose.casefold())
#Investment Calculation
if choose.casefold() == "investment":
#if user inputs investment, they need to input the following information
money = input("Please input your deposit amount: ")
ir = input("Please input your interest rate as a percentage: ")
time = input("Please input how long you plan to invest for in years: ")
interest = input("Please input if you would like simple or compound interest: ")
if interest.casefold() == "simple":
simple_ir_calc = money (1 + ((ir/100) * time))
print(f"You will make {simple_ir_calc} on your investment")
elif interest.casefold() == "compound":
comp_ir_calc = money * math.pow((1+ (ir/100)), time)
print(f"You will make {comp_ir_calc} on your investment")
else:
print("Error. Either enter simple or compound.")
#Bond calculation
elif choose.casefold() == "bond":
#user inputs info needed to calc bond
pv = input("Please enter the present value of your property: ")
ir_b = input("Please input the interest rate as a percentage: ")
time_m = input("Please enter the number of months needed to repay the bond: ")
repayment = ((ir_b/12) * pv) / math.pow(1 - (1 +(ir_b/12)), (-time_m))
print(f"You will have to pay {repayment} each month.")
else:
print("Error. Either input investment or bond.")
Looks like indents are totally messed.
It should look like that:
# Condition
if a == 0:
b = 1
elif a == 1:
b = 2
else:
# Nested conditions
if c:
b = 3
else:
b = 9
I'm very new to python. Need to get this working.
The program asks user how many tickets they want, after they input they get that ticket amount and transaction amount (tickets are 5 dollars). so far so good. Program works as is supposed to.
Program then asks user if they want to continue, if they say yes, program will start over. If they say no, program will then sum all transactions and output results of number of tickets purchased and dollar amount.
That's where I get stuck. How do I get the program to loop and output the sum of all amounts?
I know I should be adding them to some kind of list that will sum. But how do I do this? :(
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
print(f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
continuePurchase = input("Would you like to continue? Y/N \n")
while True:
if continuePurchase == "Y":
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
print(
f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
continue
elif continuePurchase == "N":
Since you always set the total tickets from the most recent user input, you are not going to be able to get the total tickets from more than one user inputs. You need to add items to a list. It can be any size and you can add new elements to it (in our case, new tickets being purchased)
It is also wise to avoid loops that use {while true}. Since we always want to loop when the user input is Y, then that can be the condition of the loop. Loop until the user input is not Y (I would add a function to make sure the user is entering Y or N. If they do not, ask the question again)
continuePurchase = "Y"
purchaseList = []
'TODO I would check if there is a valid input. Is it y/n? Should the upper/lower case matter'
while continuePurchase == "Y":
tickets = input("How many tickets would you like?")
purchaseList.append(int(tickets))
totalTicket = (tickets * 5)
print(f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
continuePurchase = input("Would you like to continue? Y/N \n")
'Answer was N, so now we can add up all the tickets'
print("You have purchased ", sum(purchaseList), " tickets total")
Here, this is a slightly modified code of yours. This works:
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
while True:
continuePurchase = input("Would you like to continue? Y/N \n").lower()
if continuePurchase == "y":
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
continue
else:
break
print(f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
So I created a procedure which would ask the user the amount of money they want to with draw from their checking account. And if do the procedure the checking should subtracted by the amount withdrawed. But when I used global it did not change the value of the variable even after the procedure.I already have established the all the variables
my code is here:
checking = 10000
savings = 10000
user_ammount_w = 0
user_currency_w = ""
def withdraw_saving (amount, country):
global checking
if country == "HKD":
if checking >= amount:
checking = checking - amount
print("The amount of money left in your checking is", checking)
else:
print("Your request of", "$"+ str(amount), country, "is greater than the amount in your
checking account this withdraw will not work")
user_choice = input("Welcome to the ATM. Type 1 for withdrawing")
if user_choice == "1":
user_currency_w= input("Which currency would you like to withdraw from. For testing purposes
its only HKD")
user_amount_w= int(input("How much money do you want to withdraw"))
withdraw_saving (user_ammount_w, user_currency_w)
When you call your function again recursivly you are allwyas passing the amount to be subtracted as 0 as you are passing in user_ammount_w which you set globally as 0. instead i suspect you want to pass in user_amount_w which is the variable name which you have used to capture the user input.
checking = 10000
savings = 10000
user_ammount_w = 0 #<----this is the value you passing to your function
user_currency_w = ""
def withdraw_saving (amount, country):
global checking
if country == "HKD":
if checking >= amount:
checking = checking - amount
print("The amount of money left in your checking is", checking)
else:
print("Your request of", "$"+ str(amount), country, "is greater than the amount in your checking account this withdraw will not work")
user_choice = input("Welcome to the ATM. Type 1 for withdrawing")
if user_choice == "1":
user_currency_w= input("Which currency would you like to withdraw from. For testing purposes its only HKD")
user_amount_w= int(input("How much money do you want to withdraw")) #<--you never pass this value.
withdraw_saving (user_ammount_w, user_currency_w)
withdraw_saving(20, 'HKD')
However using globals is not a good idea and there is probably a better way to design this.
so i'm writing a program that's supposed to take 2 inputs of data as int's for a user's debt. the variables are debt1 and debt2. it's supposed to add these two values together and then depending on the user's input, it's supposed to give out a specific response using the "if/else" loop i've created. the problem is that the program only prints out the response from the first "if" statement no matter what the input is, it always prints out "your debt is dangerously high". how do i correct this?
** Here is my code **
Name = input("Please enter your name: ")
debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))
totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)
if (totalDebt > 900,000):
print("Your debt is dangerously high ", Name)
elif((totalDebt >= 450,000 and totalDebt < 900,000)):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
Don't use commas in numbers:
if totalDebt > 900000:
print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
As #rdas said, you can use _ for long numbers, in place of ,
This is a module in part of a larger "vending machine" I am working on. I have ran into some issues, though. If they do not pay enough ($1.75) they are asked to enter an additional amount of money. Part of my problem is that I don't know what operations I should do to change the deficit inside of a loop. All of the things I've tried has resulted in errors like "input expected at most 1 arguments, got 3" and so forth.
selection = 5
loopCount = 0
deposit = 0
cost = 1.75
print("It costs $",cost,".")
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n"))
deficit = cost - deposit
change = deposit - cost
if deposit < cost:
while deficit > 0 and loopCount < 1:
??? = float(input("Please enter an additional $",deficit,"."))
loopCount += 1
if deposit >= cost:
print("Thank you for purchasing item#",selection,". Your change is $",change,".")
This works for me. Do make sure to increase the loopCount, as right now, it will not loop more than once.
selection = 5
loopCount = 0
deposit = 0
cost = 1.75
print("It costs $",cost,".")
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n"))
deficit = cost - deposit
change = deposit - cost
if deposit < cost:
while deficit > 0 and loopCount < 1:
deficit -= float(input("Please enter an additional ${}.".format(deficit)))
loopCount += 1
if deposit >= cost:
print("Thank you for purchasing item#",selection,". Your change is $",change,".")
Assuming you don't want to break from the loop until they pay enough money you could do this:
while abs(deficit) < cost:
added = float(input("Please enter an additional $",deficit,"."))
deficit = cost - deposit - added
The abs function will output the absolute value so you can compare it directly to cost.
Somethings to note though, you might want to do error checking on your inputs.
Also, if you do want to be able provide a mechanism for the user to break from the loop, you could add a boolean true or false (instead of loop count) that is attached to some other input like "Do you want to insert more money? y or n"