When making an and statement, I get an Syntax Error - python

When making a tax calculator, I seem to continue to be getting an error at the "=" in the following line of code:
elif int(vermogen) >= 30001 and <= 100800:
But I can't see a way to fix this. I've tried removing the integers but that didn't help, I've also tried to change my symbols to > and < instead of <= >= but that also didn't help. I think I made an obvious mistake but I don't seem to find it. When removing the "=" behind the "<" The syntax error moves from the "=" to the "<". I hope to hear from you soon. Here is the code I've been using/ It's in dutch, but that shouldn't affect anything.
vermogen = input('Hoeveelheid vermogen: ')
N_schijf1 = 30000
N_schijf2 = 70800
N_schijf3 = 877200
P_schijf2 = 424.8
P_schijf3 = 11403.6
if int(vermogen) <= 30000:
print("Je betaalt 0 euro aan vermogensbelasting")
elif int(vermogen) >= 30001 and <= 100800:
vermogen_betalen = int(vermogen) - N_schijf1
betalen_vermogen = vermogen_betalen * 0.006
print("Je betaalt",betalen_vermogen,"euro aan vermogensbelasting")
elif int(vermogen) >= 100801 and <= 978000:
vermogen_betalen = int(vermogen) - N_schijf1 - P_schijf2
betalen_vermogen = vermogen_betalen * 0.013
tebetalen_vermogen = P_schijf2 + betalen_vermogen
print("Je betaalt",tebetalen_vermogen,"euro aan vermogensbelasting")
elif int(vermogen) >= 978001:
vermogen_betalen = int(vermogen) - N_schijf1 - P_schijf2 - P_schijf3
betalen_vermogen = vermogen_betalen * 0.0161
tebetalen_vermogen = P_schijf2 + P_schijf3 + betalen_vermogen
print("Je betaalt",tebetalen_vermogen,"euro aan vermogensbelasting")
print("Test")

You must have a complete condition on each side of the and. Operands don't carry across the and into the next condition.
You could write:
int(vermogen) >= 30001 and int(vermogen) <= 100800
Or just:
30001 <= int(vermogen) <= 100800
since Python supports chaining of comparisons

you need to change your if from:
elif int(vermogen) >= 100801 and <= 978000:
elif int(vermogen) >= 30001 and <= 100800:
to
elif int(vermogen) >= 100801 and int(vermogen) <= 978000:
elif int(vermogen) >= 30001 and int(vermogen) <= 100800:

Related

Exact Change in Python

I am trying to write a code in Python to where it outputs exact change using the fewest coins and one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. I also have to use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. When I input 45 and ran the code, I got an error saying (Your program produced no output). Here is my code:
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 100:
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(dollar + ' Dollar')
elif dollar > 1:
print(dollar + ' Dollars')
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(quarter + ' Quarter')
elif quarter > 1:
print(quarter + ' Quarters')
elif quarter_change >= 10:
dime = quarter_change // 10
dime_change = quarter_change % 10
if dime == 1:
print(dime + ' Dime')
elif dime > 1:
print(dime + ' Dimes')
elif dime_change >= 5:
nickel = dime_change // 5
nickel_change = dime_change % 5
if nickel == 1:
print(nickel + ' Nickel')
elif nickel > 1:
print(nickel + ' Nickels')
elif nickel_change >= 1:
penny = nickel_change // 1
if penny == 1:
print(penny + ' Penny')
else:
print(penny + ' Pennies')
total = int(input())
if total == 0:
print("No change")
else:
denominations = [(100, "Dollar", "Dollars"), (25, "Quarter", "Quarters"), (10, "Dime", "Dimes"), (5, "Nickel", "Nickels"), (1, "Penny", "Pennies")]
for d in denominations:
coins = total // d[0]
total %= d[0]
if coins > 1:
print(f"{coins} {d[2]}")
elif coins == 1:
print(f"1 {d[1]}")
In this answer, I created a list full of tuples of all the coins and their values in cents. I then created a for loop which runs through all the tuples in the list, dividing the total removing the remainder for the number of coins
like this:
*coins = total // d[0] #returns the number of coins of the current iteration
Then, in order for the loop to continue to the next iteration and do the calculations correctly, I set the total in cents equal to the remainder of the total divided by the current iteration.
like this:
total %= d[0] #can also be written as total = total % d[0]
Then, I take the number of coins and check if the value is greater than one. If the conditional is met, it prints the number of coins followed by the corresponding "plural version" of the word.
like this:
if coins > 1:
print(f"{coins} {d[2]}")
#d[2] refers to the third item in the tuple of the current iteration
Finally, I use an else-if conditional to return 1 plus the "singular version" of the word
like this:
elif coins == 1:
print(f"1 {d[1]}")
#d[1] refers to the second item in the tuple of the current iteration
Your code has numerous problems that needed to be resolved, including the lack of a condition for input values 0 < total_change < 100, problems with indentation (the elif blocks should be aligned), unnecessary variables (you do not need variables like nickel_change and dime_change - total_change is all that matters), and you tried to print dollar + ' Dollar' even though dollar was a numeric variable.
I wanted to improve on the issues in your code and make it, well, functional, but without entirely rewriting your work. So, the basic framework of the code I'm going to provide is the same.
I used the method of recursion. I have the following function with all of your (cleaned) code:
def printCurrency(total_change):
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(str(dollar) + ' Dollar')
printCurrency(total_change-1*100)
elif dollar > 1:
print(str(dollar) + ' Dollars')
printCurrency(total_change-dollar*100)
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(str(quarter) + ' Quarter')
printCurrency(total_change-1*25)
elif quarter > 1:
print(str(quarter) + ' Quarters')
printCurrency(total_change-quarter*25)
elif dollar_change >= 10:
dime = dollar_change // 10
dime_change = dollar_change % 10
if dime == 1:
print(str(dime) + ' Dime')
printCurrency(total_change-1*10)
elif dime > 1:
print(str(dime) + ' Dimes')
printCurrency(total_change-dime*10)
elif dollar_change >= 5:
nickel = dollar_change // 5
nickel_change = dollar_change % 5
if nickel == 1:
print(str(nickel) + ' Nickel')
printCurrency(total_change-1*5)
elif nickel > 1:
print(str(nickel) + ' Nickels')
printCurrency(total_change-nickel*5)
elif dollar_change >= 1:
penny = dollar_change // 1
if penny == 1:
print(str(penny) + ' Penny')
printCurrency(total_change-1*1)
else:
print(str(penny) + ' Pennies')
printCurrency(total_change-penny*1)
Notice how every time a line is printed, the function is ran again but after subtracting out the change we've already processed.
A few examples:
>>> printCurrency(45)
1 Quarter
2 Dimes
>>> printCurrency(101)
1 Dollar
1 Penny
>>> printCurrency(349)
3 Dollars
1 Quarter
2 Dimes
4 Pennies
And to tie this into your original framework with an input...
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 0:
printCurrency(total_change)
Let me know if you have any questions about the changes I've made to your code!
This is more of an answer that zybooks is looking for considering what it has taught up to this point. All that I have done here is decrement total_change each time I go down the list of coins. If there were no coins for that set then print a statement on the previous line.
total_change = int(input())
if total_change <= 0:
print('No change')
else:
dollar = total_change // 100
if dollar == 1:
print(dollar, 'Dollar')
total_change = total_change - (dollar * 100)
elif dollar <= 0:
print(end='')
else:
print(dollar, 'Dollars')
total_change = total_change - (dollar * 100)
quarter = total_change // 25
if quarter == 1:
print(quarter, 'Quarter')
total_change = total_change - (quarter * 25)
elif quarter <= 0:
print(end='')
else:
print(quarter, 'Quarters')
total_change = total_change - (quarter * 25)
dime = total_change // 10
if dime == 1:
print(dime, 'Dime')
total_change = total_change - (dime * 10)
elif dime <= 0:
print(end='')
else:
print(dime, 'Dimes')
total_change = total_change - (dime * 10)
nickel = total_change // 5
if nickel == 1:
print(nickel, 'Nickel')
total_change = total_change - (nickel * 5)
elif nickel <= 0:
print(end='')
else:
print(nickel, 'Nickels')
total_change = total_change - (nickel * 5)
penny = total_change // 1
if penny == 1:
print(penny, 'Penny')
total_change = total_change - (penny * 1)
elif penny <= 0:
print(end='')
else:
print(penny, 'Pennies')
total_change = total_change - (penny * 1)

What is causing the Colon Expected Error in Python?

I am trying to get my head around Expected Colon Error in the following code. Any help appreciated.
The code is -
if df.loc['pivot'] > df.loc['Open'] :
df.loc['Signal'] = 1
elif df.loc[['Open'] > df.loc['IB'] and df.loc['Open'] > df.loc['pivot'] and df.loc['Open'] < df.loc['OB']:
df.loc['Signal'] = 0
elif (((df.loc['Open']) <= (((df.loc['2_pips']) - 5)/ 1000)) * (df.loc['pivot'])) and ((df.loc['Open']) >= (((df.loc['1_pips']) + 10)/ 1000 * (df.loc['pivot']))) and ((df.loc['Open']) >= (df.loc['pivot'])) :
df.loc['Signal'] = 1
elif (df.loc['Open'] <= ((df.loc['1_pips'] * df.loc['pivot']) + df.loc['pivot'] )) and (df.loc['Open'] > (((df.loc['1_pips'] - 10) * df.loc['pivot']) + df.loc['pivot'])) :
df.loc['Signal'] = 1
elif ((df.loc['Open'] < OB) and (df.loc['Open'] < df.loc['pivot'])):
df.loc['Signal'] = -1
elif ((df.loc['Open'] <= OB) and (df.loc['Open'] >= IB) and (df.loc['Open'] < df.loc['pivot'])):
df.loc['bs'] = 0
elif (df.loc['Open'] < ((df.Loc['2_pips'] - 5) * df.loc['pivot']) + df.loc['pivot']) and (df.loc['Open'] > ((df.loc['1_pips'] + 10) * pivot) + df.loc['pivot']) and (df.loc['Open'] < df.loc['pivot']):
df.loc['Signal'] = -1
elif (df.loc['Open'] <= (df.loc['1_pips'] * df.loc['pivot']) + df.loc['pivot']) and (df.loc['Open'] > ((df.loc['1_pips'] - 10) * df.loc['pivot']) + df.loc['pivot']):
df.loc['Signal'] = -1
else:
df.loc['Signal'] = 0
Thanks!
On line 4, you have df.loc[['Open'] which I guess is one square bracket too much.
You can also simplify that line as:
elif df.loc['Open'] > df.loc['IB'] and df.loc['pivot'] < df.loc['Open'] < df.loc['OB']:
And generally, you have way too many parentheses. I'm guessing that it's actually because you were trying to find the issue.
In general, when you get a compiler syntax error like an (un)expected token, you have a structural issue just above it. It is parsing the line it's complaining about as the continuation of the previous statement. Unmatched (), [] or {}. To find it, one could have reduced the code with the error and noticed that it was still failing with the same error, meaning that the actual error was in fact from the previous line(s).

Python DateTime if statement behaves different in Azure.(Django WebApp)

So i'm writing a little Django webApp. It uses JSON data from a API to render everything. In localhost, everything runs fine. But in Azure it does not.
The is somewhere in this code:
for appointment in appointmentsMaandag:
starttijd = (datetime.datetime.fromtimestamp(appointment['start'])).strftime('%H%M')
SuMa = 0
if 800 <= int(starttijd) < 850:
SuMa = 0
elif 850 <= int(starttijd) < 940:
SuMa = 1
elif 940 <= int(starttijd) < 1050:
SuMa = 2
elif 1050 <= int(starttijd) < 1140:
SuMa = 3
elif 1140 <= int(starttijd) < 1240:
SuMa = 4
elif 1240 <= int(starttijd) < 1350:
SuMa = 5
elif 1350 <= int(starttijd) < 1440:
SuMa = 6
elif 1440 <= int(starttijd) < 1530:
SuMa = 7
else:
SuMa = 8
break
In azure, this always outputs the ELSE. SuMa = 8 in this case. In Localhost it does work. Since I have no experience whatsoever with azure, I was wondering if any of you could help me.
I use VS 2015 with Python Tools.
It should be a timezone issue. As when we need to parse timestamp to datetime object, it will need the timezone setting, and by default it will leverage the system timezone. And the timezone on Azure services are all the same as America/Los_Angeles.
So you need to set your local timezone in your code, E.G:
import pytz
localtz = pytz.timezone('Asia/Hong_Kong')
starttijd = (datetime.datetime.fromtimestamp(appointment['start'],tz=localtz)).strftime('%H%M')
print starttijd
...

Python if statement syntax?

I am working on a BMI calculator and have a bunch of if statements for the "status" part of it. For some reason I am getting an error through Eclipse saying that "Expected:)" but I have no clue what is missing.
Here is a sample of the code which is throwing the error:
BMI = mass / (height ** 2)
if(BMI < 18.5):
status = "Underweight"
if(BMI => UNDERWEIGHT and BMI < NORMAL):
status = "Normal"
if(BMI => NORMAL & BMI < OVERWEIGHT):
status = "Overweight"
elif(BMI >= 30):
status = "Obese"
As already noted on other answers, the error is caused by =>, and & is a bitwise operator which is not what you want in this context. But as per #Blckknght's comment, you can probably simplify this anyway by only comparing to the maximum value each time. Also, get rid of the parentheses as these are not needed in Python.
BMI = mass / (height ** 2)
if BMI < UNDERWEIGHT:
status = "Underweight"
elif BMI < NORMAL:
status = "Normal"
elif BMI < OVERWEIGHT:
status = "Overweight"
else:
status = "Obese"
=> does not mean anything in Python. "Greater than or equal to" is instead written >=.
You might change:
if(BMI => NORMAL & BMI < OVERWEIGHT):
to:
if(BMI >= NORMAL and BMI < OVERWEIGHT):
With some of the other suggestions, you might re-write the entire statement as:
if BMI < UNDERWEIGHT:
status = "Underweight"
elif BMI >= UNDERWEIGHT and BMI < NORMAL:
status = "Normal"
elif BMI >= NORMAL and BMI < OVERWEIGHT:
status = "Overweight"
elif BMI >= OVERWEIGHT:
status = "Obese"
BMI = mass / (height ** 2)
if (BMI < 18.5):
status = "Underweight"
elif (UNDERWEIGHT < BMI < NORMAL):
status = "Normal"
elif (NORMAL < BMI < OVERWEIGHT):
status = "Overweight"
else
status = "Obese"
In python we can check whether a number is in the range, like this
if 0 < MyNumber < 2:
This will be Truthy only when MyNumber is some number between 0 and 2.

Using Bisection Search on Lowest Payments on Credit Card debt and

My code:
monthlyInterestRate = annualInterestRate/12.0
low = balance/12
high = (balance*(1+monthlyInterestRate)**12)/12
guess = (low+high)/2
unpaidBalance = balance
month = 1
while True:
unpaidBalance= unpaidBalance-guess
while month < 13:
if unpaidBalance <= -0.1:
low = guess
month += 1
elif unpaidBalance >= 0.1:
high = guess
month += 1
else:
break
guess = (low + high)/2
print "Lowest Payment: " + str(round(guess, 2))
When I test it it gets stuck at the line "while month < 13:"
Why does it do this and how do I fix it?
If you break at each loop of inner while, you remains less than 13.
And this goes on and on since you proceed While True and do not update your guess.
I fear you are facing infinite looping there.
Your break statement breaks the closest loop, that is the While month < 13 loop. The next line is not read. guessis not updated. The while True is not broken.
Maybe you wanted to say
while month < 13:
unpaidBalance= unpaidBalance-guess
if unpaidBalance <= -0.1:
low = guess
elif unpaidBalance >= 0.1:
high = guess
month += 1
guess = (low + high)/2
here you are
No is the best solution, but it works
monthlyPaymentRate = (balance*annualInterestRate/12)/((1-(1+annualInterestRate/12)**-12))
interest = monthlyPaymentRate * (annualInterestRate/12)
#print (monthlyPaymentRate)
#print (interest)
monthlyPaymentRate = (monthlyPaymentRate - interest) +1
#print (monthlyPaymentRate)
balanceInit = balance
epsilon = 0.01
low = monthlyPaymentRate
while low*12 - balance > epsilon:
balances = balanceInit
for i in range(12):
minpay = monthlyPaymentRate
unpaybal = balances - minpay
interest = (annualInterestRate /12) * unpaybal
smontfinal = unpaybal + interest
balances = smontfinal
#print('Remaining balance: ' ,round(balances,2) )
if balances <0:
low = -1
break
if balances < 0 :
low = -1
else:
monthlyPaymentRate =monthlyPaymentRate + 0.001
print('Lowest Payment:' ,round(monthlyPaymentRate,2) )

Categories