Python syntax errors - coin machine problem - python

I know these are very basic questions but cannot figure out what I'm doing wrong. I'm just beginning to learn python and don't understand why I am getting a syntax error every time I try to subtract something.
When I try to run this:
```#def variables - input cash entered and item price in float parentheses
cash = float(400)
price = float(215)
#change calculation
def cash_owed(cash - price)```
I get a
SyntaxError: invalid syntax with the ^ pointing to the - sign.
I can't find any information about why using a subtraction sign would return a syntax error in this context. What am I doing wrong?
I am trying to create a coin machine program where the cash is entered in integers representing cents (i.e $5 = 500) returns the required change in the most convenient coin denominations. This is the rest of the code that I wrote, but I can't even get past that first syntax error.
cash = float(400)
price = float(215)
#change calculation
def cash_owed(cash - price)
c = cash_owed
#display amount recieved, cost of item, required change
print ("Amount recieved : " + str(cash)) \n
print ("Cost of item : " + str(float)) \n
print("Required change : " + str(c)) \n
#calculate toonies owed
def calculate_toonies(c//200)
round(calculate_toonies)
print("Toonies x " + str(calculate_toonies))
c = c%200
#calculate loonies owed
def calculate_loonies(c//100)
round(calculate_loonies)
print("Loonies x " + str(calculate_loonies))
c = c%100
#calculate quarters owed
def calculate_quarters(c//25)
round(calculate_quarters)
print("Quarters x " + str(calculate_quarters))
c = c%25
#calculate dimes owed
def calculate_dimes(c//10)
round(calculate_dimes)
print("Dimes x " + str(calculate_dimes))
c = c%10
#calculate nickles owed
def calculate_nickles(c//5)
round(calculate_nickles)
print("Nickles x " + str(calculate_nickles))
c = c%5```

Your function definition is wrong. The parameter cannot do an operation & should contain a colon.
Change
def cash_owed(cash - price)
To
def cash_owed(cash, price):
new_price = cash - price

You have to put a colon after function
You can try this:
def cash_owed(cash, price):
return(cash - price)

Related

How to combine 'get' methods into one

Looking for a solution to combine two 'get' methods to have a single method.
The program calculate present value, future value, and future value of an annuity. Currently I have two methods "getAmount" and "getTerm", which are float and integer values respectively, that receive and validate user input. I think it is possible to combine them into a single method by evaluating them as a string. Am I on the right track?
This is my code to find the present value. The first thing I tried was to validate the input as a number but I quickly found that was not the way to go about it as I received the error float cannot be converted to int.
#Present Value
amount = getAmount("Amount to be received: ") #float value
rate = getAmount("Annual Interest Rate (6%=6): ") #float value
term = getTerm() #integer value
pv = calcPV(amount,rate,term)
df = 1 + rate) ** term
print("An amount of amount: " + amount)
print("to be received in " + str(term) + " months "
+ "with an annual cost of money of: " + rate
+ "has a value today of: " + pv)
print("That includes a discount of: " + df)
def calcPV(amount,rate,term):
monthlyRate = rate / 100 / 12
pv = amount / ((1 + monthlyRate) ** term)
return pv
def getAmount(prompt):
amt = -1
while (amt <= 0):
try:
amt = float(input(prompt))
if (amt <= 0):
print("Positive values only")
except ValueError:
print("Illegal input: the amount must be greater than 0.")
amt = -1
return amt
def getTerm():
amt = -1
while (amt <= 0):
try:
amt = int(input("Term (in month): "))
if (amt <= 0):
print("Positive values only")
except ValueError:
print("Illegal input: the amount must be greater than 0.")
amt = -1
return amt

Using functions in 'while' loop python

So I want to create a code that would calculate the minimum monthly payment and remaining balance, given an annual interest rate, principal amount and monthly payment rate. The desired output is:
Month: 1
Minimum monthly payment: 168.52
Remaining balance: 4111.89
Month: 2
Minimum monthly payment: 164.48
Remaining balance: 4013.2
and so on until month 12.
I know there's a way to do it without defining functions but the whole function thing was just messing me up so I wanted to try it. My current code is -
a=0
while a<=11:
def min_mth_pay(balance,monthlyPaymentRate):
x = balance * monthlyPaymentRate
return x
def balance(balance,min_mth_pay,annualInterestRate):
y=(balance - min_mth_pay)*((annualInterestRate/12)+1)
return y
a +=1
print('Month:' + str(a) + 'Minimum monthly payment:' + str(x) + 'Remaining balance:' + str('y'))
I'm not even sure if I can use functions in such a format? The error pops out saying the name 'x' is undefined. Really new at Python here obviously would appreciate any clarifications! :)
You're confusing defining functions with calling them. You should define then functions separately, then call them from within your loop.
def min_mth_pay(balance,monthlyPaymentRate):
x = balance * monthlyPaymentRate
return x
def balance(balance,min_mth_pay,annualInterestRate):
y=(balance - min_mth_pay)*((annualInterestRate/12)+1)
return y
a=0
while a<=11:
a +=1
x = min_mth_pay(balance,monthlyPaymentRate)
y = balance(balance,min_mth_pay,annualInterestRate)
print('Month:' + str(a) + 'Minimum monthly payment:' + str(x) + 'Remaining balance:' + str(y))
Note that it's not clear where balance, monthlyPaymentRate, min_mth_pay, and annualInterestRate are coming from in your code.

Basic Python Issue (UnboundLocalError: local variable 'normal' referenced before assignment)

I am having a pretty basic issue and I know you guys will easily be able to spot the error.
Right now I am trying to write a script that calculates overtime pay for me. I haven't written very much code so I am just trying to stick with basic problems for now. I have went through code academy and I will be starting Learn Python the Hard way, however I think I need to just make more projects in order to better get an understanding.
This is my code right now. I am confused as to why it thinks a variable hasn't been defined yet, because I clearly am defining the three variables I need at the top.
### California overtime payment calculator.
### Based on an 8 hour normal day, 1.5x day rate after 8 hours, and 2x pay after 12 hours.
### Enter your rate, then the number of hours you worked and you will get a result.
rate = raw_input("Enter your current rate:")
print "This is your rate: %s" % (rate)
normal = 0
overtime = 0
doubleOT = 0
def enteredHours():
userInput = raw_input("Enter your hours for given day: ")
if int(userInput) >= 12:
print "Greater than 12"
normal = normal + 8
overtime = overtime + 4
doubleOT = doubleOT + (userInput - 12)
elif int(userInput) >= 8:
print "Greater or equal to 8"
normal = normal + 8
overtime = overtime + (userInput - 8)
elif int(userInput) < 8:
normal = normal + userInput
elif str(userInput) == "calculate":
hoursTotal = normal + overtime + doubleOT
print "Total amount of hours is: " + str(hoursTotal)
payTotal = (normal * 250) + (overtime * 250 * 1.5) + (doubleOT * 250 * 2)
print "Total amount of pay is: " + str(payTotal)
return normal
return overtime
return doubleOT
enteredHours()
enteredHours()
This is a very common issue for beginners. Those variables are out of scope of the function.
Either define them inside of your function like so:
def enteredHours():
normal = 0
overtime = 0
doubleOT = 0
or use the global keyword to put them in scope:
normal = 0
overtime = 0
doubleOT = 0
def enteredHours():
global normal
global overtime
global doubleOT
Because you appear to be using these variables to accumulate over multiple invocations of the enteredHours function, you should choose the second option with the global keyword.
EDIT: You also have some other issues. Your code will return on the first return statement:
return normal # exit function here
return overtime # not executed!
return doubleOT # not executed!
If you want to return all 3 values, you need to return them with the same return statement:
return normal, overtime, doubleOT
EDIT #2
Don't run your code recursively (by calling enteredHours at the end of the function - this statement isn't run anyway since the function exits at the return statement). Instead run it in a while loop:
def enteredHours():
...
while True:
enteredHours()
The reason for this is that your stack grows with each recursive call, and eventually you will hit a "stack overflow" :)

Calculating Compound Interest using Python functions

Write a function that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
I am having the error " ValueError: unsupported format character 'I' (0x49) at index 28"
Here is my code so far.
def BankBalance():
InputB = 1000
return InputB
print("Your initial balance is $1000")
def Interest():
InputI = 0.05
return InputI
print("The rate of interest is 5%")
def CountNumber():
InputN = float(input("Please enter the number of times per year you would like your interest to be compounded: "))
return InputN
def Time():
InputT = float(input("Please enter the number of years you need to compund interest for:"))
return InputT
def Compount_Interest(InputB, InputI, InputT, InputN):
Cinterest = (InputB*(1+(InputI % InputN))**(InputN * InputT))
print("The compound interest for %.InputT years is %.Cinterest" %Cinterest)
B = BankBalance()
I = Interest()
N = CountNumber()
T = Time()
Compount_Interest(B, I, N, T)
Here is how you would do it.
def main():
# Getting input for Balance
balance = float(input("Balance: $ "))
# Getting input for Interest Rate
intRate = float(input("Interest Rate (%) : "))
# Getting input for Number of Years
years = int(input("Years: "))
newBalance = calcBalance(balance, intRate, years)
print ("New baance: $%.2f" %(newBalance))
def calcBalance(bal, int, yrs):
newBal = bal
for i in range(yrs):
newBal = newBal + newBal * int/100
return newBal
# Program run
main()
You are trying to use your variable as a function.
Try this instead :
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
Python, and most other programming languages, don't assume that two adjacent mathematical expressions with no operator between them means multiplication. You are missing a multiplication operator (*) between InputB and the rest of the expression:
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
# Here -------------^

Python 3 - Getting multiple inputs for a variable

I'm trying to get the user to be able to input several values into the cash register. When they are done, all they have to type in is -1 and it won't request any more values to be input. Once this is done, the program adds up the total of the numbers input, and then spits them out in a message as netPrice. grossPrice however adds them up but adds 10% GST to the end value. I've had no experience with raw_input or continuing variables, and searching here I found some information that I attempted to apply to the code, however failed for me.
#x = continued input ("Enter in net price of items for the cash register: ")
#if x -1:
# stop;
#netPrice = x
#grossPrice = netPrice + (0.1 * netPrice)
#print ("The net price of all items is: $",netPrice)
#print ("The gross price of all items (this includes GST) is: $",grossPrice)
x = raw_input("Enter in net price of items for the cash register: ")
if x >=-1:
stop;
netPrice = x
grossPrice = netPrice + (0.1 * netPrice)
print ("The net price of all items is: $",netPrice)
print ("The gross price of all items (this includes GST) is: $",grossPrice)
You can do something as follows:
values = []
while True:
x = float(input('Enter in net price of items for the cash register: '))
if x == -1:
break
values.append(x)
print ("The net price of all items is: " + str(sum(values)))

Categories