Python: Performing user-defined addition to a variable in a loop - python

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"

Related

Nesting an if condition within an if condition gone wrong? +(Investment and Bond Repayment Calculations in Python)

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

Having inputs add onto each other in python

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.

While true in python does not stop on condition

The program is to accept a choice from the user.
Choice 1 to check the deposit
Choice 2 to make a deposit - when I entered choice two it should accept a deposit that is greater than 0 but less than 100,000, if this condition is not met then the program should prompt the user to enter the deposit until the condition is met.
If the condition is met, then the program should add the deposit entered to 30,000 and print the result.
My problem is even if the deposit is greater than 100,000 or less than 0, it is still printing the result and it should only prompt the user to enter the deposit until it is greater than 0 or less than 100,000.
What could be the error or problem in my code?
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
if choice == 2:
while True:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
if(deposit < 0 and deposit > 100000):
continue;
newbalance = deposit + balance
print("Your balance is $", newbalance)
Hey please see below for the code I think you want. From what I understand in terms of what you want, your problem was that your script was still going to print the deposit irrespective of invalid values.
In your code, after the first if statement you are telling python to just continue, even if the first if statement evaluates to true.
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
if choice == 2:
while True:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
#if(deposit < 0 and deposit > 100000):
#continue;
newbalance = deposit + balance
print("Your balance is $", newbalance)
break
The problem here is in the 2nd if condition of while loop. You shall use or logical operator instead of and as
if(deposit < 0 and deposit > 100000):
means that simultaneously deposit < 0 and greater than 100000 which is false always.
Secondly don't use ; after continue
The code should be as follows:
if (deposit < 0 or deposit > 100000):
Hope this helps you!
Fixing conditions in original code:
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
elif choice == 2:
while True:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
newbalance = deposit + balance
print("Your balance is $", newbalance)
But the above code will keep on adding, better code can be:
while True:
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
elif choice == 2:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
newbalance = deposit + balance
print("Your balance is $", newbalance)
Always check user input. You need to offer the user some way of exiting the program (menu option)
You may find this pattern instructive:
balance = 30_000
MAX = 100_000
while True:
try:
option = int(input('Enter 1 to check balance\nEnter 2 to deposit\nEnter 3 to withdraw\nEnter 9 to exit\n: '))
if not option in {1, 2, 3, 9}:
raise ValueError('Invalid option')
if option == 9:
break
if option != 1:
amount = float(input('Enter amount: '))
if amount < 0 or amount > MAX:
raise ValueError(f'Amount cannot be negative of over {MAX}')
if option == 2:
balance += amount
else:
balance -= amount
print(f'Current balance = {balance:.2f}')
except ValueError as e:
print(e)
Firstly, You have the same condition in the two if statments on line 17 and 21. It can be replaced with one single IF statment.
So you're checking if the deposit is less than 0 or greater than 100000. If it fits that condition you want display an error message and re-prompt the user for the deposit withnin the stipulated range. When the user enters a number withnin the stipulated range the program should 'break' out of the while loop and print the balance.
If it fits the condition, display the error message and the use the 'continue' statment to restart the loop and prompt the user continously for a deposit until the user enters a number which fits the condition. if the user enters a deposit greater than 0 or less than 100000. You would want to break out of the loop using the 'break' statment and display the new deposit.
if(deposit < 0 or deposit > 100000):
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
else:
break
Also I think you intended to place the line 25 and 26 where you are calculating th new deposit and displaying the deposit outside the while loop. Lines 25 and 26 should only be exceuted once the the user has entered the correct deposit which is withnin the stipulated range. So it should be outside the while loop
Your full code should similar to this:
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
if choice == 2:
while True:
deposit = float(input("Enter the deposit you would like to make:"))
if(deposit < 0 or deposit > 100000):
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
else:
break
newbalance = deposit + balance
print("Your balance is $", newbalance)
List item

I require assistance in understanding what's wrong with my code (if statements)

I'm not sure what I did wrong in this code, but for some reason, Eclipse keeps on telling me that the if statement is just bad. I'm not sure why, when I look at the examples, it looked fine to me.
penny = .01
nickel = .05
dime = .1
quarter = .25
print("Enter how many coins you want to use to make a dollar.")
e_pen = int(input("Enter the amount of pennies you want: "))
e_nic = int(input("Enter the amount of nickels you want: "))
e_dim = int(input("Enter the amount of dimes you want: "))
e_qua = int(input("Enter the amount of quarters you want: "))
doll = float((e_pen * penny) + (e_nic * nickel) + (e_dim *dime) + (e_qua * quarter))
if doll > 1 # every conditional needs a : per the answer below
print("The total value is greater than 1 dollar.") # notice the indentation
else # same here
print("Try again.")
If statements require a colon and proper indentation, see:
if doll > 1:
print("blah")
else:
Print ("Try again")
Note, the indentation is 4 spaces.

Can someone explain this python while loop to me?

I am a python/programming beginner. I was assigned a problem on MIT open courseware to:
Write a program that calculates the minimum fixed monthly payment in order to pay off a credit card balance within 12 months.
Take as raw_input() the following floating point numbers:
1) the outstanding balance on the credit card
2) the annual interest rate as a decimal
Print out the fixed minimum payment, number of months(at most 12 and possibly less than 12) it takes to pay off the debt, and the balance (likely to be a negative number).
Assume the interest is compounded monthly according to the balance at the start of the month(before the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme.
THE ANSWER IS:
balance = float(raw_input('Enter the outstanding balance on your credit card: '))
interest = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
minPay = 10
newBalance = balance
while balance > 0:
for month in range(1,13):
newBalance = newBalance*(1+(interest/12))-minPay
if newBalance <=0:
break
if newBalance <= 0:
balance = newBalance
else:
newBalance = balance
minPay = minPay+10
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: ' + str(minPay)
print 'Number of months needed: ' + str(month)
print 'Balance: ' + str(round(balance,2))
MY QUESTIONS:
1) Using 1200 as the raw input balance, and .18 as the interest rate. Could someone explain in words how you would arrive at minPay = 120, month = 11, and balance = - 10.05?
I am confused by the newBalance = newBalance* (1 +(interest/12)) - minPay.
Using 1200 as the balance would make newBalance = 1200 * (1 +(.18/12)) - 10 = 1218 - 10 = 1208.
2) Since newBalance is not <= 0 the program would then proceed to the else statement. What is happening with the newBalance = balance part of the else statement. Does that assign newBalance back to 1200(original balance input).
I am having some trouble understanding this problem. Any insight whatsoever would be appreciated.
I would strongly recommend going through each line of the code as a python interpreter would and then seeing, why the program does perform as expected.
If you are lazy for that, try to put a print statement within the loop itself to see what the values of each variable are at every step. This always helps me figure out, what the code is doing.
As for your questions,
Yes, New balance does have the value that you expect it to have
Yes, it does get reassigned to balance, in the else part. You might want to change this.
As, I do not understand what the code is actually trying to do, I cannot help you with what the correct approach is, but try to add print statements, and it should help. Good Luck!
What is happening with the newBalance = balance part of the else statement? Does that assign newBalance back to 1200(original balance input).
Yes that's it. Then the minPay is increased and the loop starts again.
As minPay increases at each iteration, newBalance will end being negative.
balance = 3329
annualInterestRate = 0.2
minimum_fixed_payment = 10
unpaid_balance = balance
MonthlyInterestRate = annualInterestRate / 12
month_count = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
while balance > 0:
for month in month_count:
unpaid_balance = unpaid_balance - minimum_fixed_payment
interest = MonthlyInterestRate * unpaid_balance
unpaid_balance = unpaid_balance + interest
if unpaid_balance <= 0:
break
if unpaid_balance <= 0:
balance = unpaid_balance
else:
unpaid_balance = balance
minimum_fixed_payment = minimum_fixed_payment + 10
print "Lowest Payment: %s" % (minimum_fixed_payment)
The easiest way to answer this question would be to see it from this angle and that is, using the minimum fixed payment, we subtract the minimum fixed payment from the unpaid balance every month and check if the value left is lesser than 0. if it is not we increase the minimum fixed payment by 10 and repeat the process until we have a balance that is lesser than or equal to zero.
That is the modification I made to the code.

Categories

Resources