Python if statement syntax? - python

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.

Related

my condiotional statement wont work for some wierd reason

im new to coding and am learning python atm. I was writing this simple code for a discount system and it wont work for some weird reason. pls tell me whats wrong with this code
price = (input('Please type the value of your item.'))
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
print('You need to pay' + price + '$ for your item')
price = (price + ((price) * (10/100) )
This statement isn't valid:
elif price >= 200 and < 300:
It would correctly be written as:
elif price >= 200 and price < 300:
Note that for this to work, price needs to be a numeric value; you need to convert your input() result to a float or int before trying anything mathematical with it!
However, specifying price < 300 isn't necessary in the first place, since this is an elif that can only happen if price >= 300 was false (hence price < 300 is logically implied to be true).
You can also simplify the arithmetic down; this:
price = (price + ((price) * (30/100) )
is really just the same (algebraically) as:
price = price * (1 + 30/100)
which is the same as:
price *= 1.3
Since you're going to end up with floating point numbers in most cases, you probably want to round this output to 2 decimal places:
print('You need to pay' + price + '$ for your item')
which you can do easily with an f-string:
print(f'You need to pay ${price:.2f} for your item')
All together:
price = float(input('Please type the value of your item.'))
if price >= 300:
price *= 1.3
elif price >= 200:
price *= 1.2
elif price >= 100:
price *= 1.1
print(f'You need to pay ${price:.2f} for your item')
change from this:
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
to this:
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and price < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and price < 200:

Return value homework in Python

Write a function that returns the type of clothing you should wear, based on the parameter temperature. If the temperature is below -10, you will wear a parka and toque (return “parka and toque”). If the temperature is between -10 and 0, wear a toque (return “toque”). If the temperature is greater than 0 but less than 10, wear a sweater (return “sweater”). If the temperature is between 10 and 20, wear a t-shirt (return “t-shirt”). If the temperature is greater than 20, wear shorts (return “shorts”).
For example:
wear_the_right_thing(25) == "shorts"
wear_the_right_thing(-25) == "parka and toque"
wear_the_right_thing(-5) == "toque"
here is my code:
def wear_the_right_thing(temperature):
if temperature < -10:
return "parka and toque"
if temperature >= -10:
return "toque"
if temperature > -10 and temerature <= 0:
return "sweater"
if temperature > 10 and temperature <= 20:
return "t-shrit"
if temperature > 20:
return "shorts"
Here is my result (not the output this just my marked):
Result Actual Value Expected Value Notes
Fail 'toque' 'shorts' wear_the_right_thing(25)
Fail 'toque' 't-shirt' wear_the_right_thing(20)
Fail 'toque' 't-shirt' wear_the_right_thing(15)
Fail 'toque' 't-shirt' wear_the_right_thing(10)
Fail 'toque' 'sweater' wear_the_right_thing(9)
Fail 'toque' 'sweater' wear_the_right_thing(1)
Pass 'toque' 'toque' wear_the_right_thing(0)
Pass 'toque' 'toque' wear_the_right_thing(-10)
Pass 'parka and toque' 'parka and toque' wear_the_right_thing(-11)
Pass 'parka and toque' 'parka and toque' wear_the_right_thing(-30)
You passed: 40.0% of the tests
so i fail the test so can help me to get 100 thank you very much
You have over lapping conditions. "toque" is always reported if temperature is above -10. You also have spelling mistakes, e.g. "temperature".
def wear_the_right_thing(temperature):
if temperature < -10:
return "parka and toque"
elif temperature >= -10 and temperature <= -5:
return "toque"
elif temperature > -10 and temperature <= 0:
return "sweater"
elif temperature > 0 and temperature <= 20:
return "t-shrit"
elif temperature > 20:
return "shorts"
You need to use the and to give multiple condition in one if statement.
Example
if temperature > -10 and temperature < 0 :
return "toque"
There are many issues with your conditions, try something like this
def wear_the_right_thing(temperature):
if temperature < -10:
return "parka and toque"
elif -10 <= temperature <= -5:
return "toque"
elif -5 < temperature <= 0:
return "sweater"
elif 0 < temperature <= 20:
return "t-shrit"
elif temperature > 20:
return "shorts"

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

When making an and statement, I get an Syntax Error

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:

Trying to print, but says my function name is not defined?

name = str(input("What is your name? "))
age = int(input("What is your age? "))
weight_float = float(input("What is your weight in pounds? "))
height_float = float(input("What is your height in inches? "))
Pounds2Kilogram = weight_float * 0.453592
Inches2Meter = height_float * 0.0254
weight = Pounds2Kilogram
height = Inches2Meter
class calcBMI:
def __init__(self, name, age, weight, height):
self.__name = name
self.__age = age
self.__weight = weight
self.__height = height
def getBMI(self):
return self.__weight / (self.__height **2)
def getStatus(self):
if getBMI() < 18.5:
self.__getStatus = "Underweight"
elif 18.5 < getBMI() < 24.9:
self.__getStatus = "Normal"
elif 25.0 < getBMI() < 29.9:
self.__getStatus = "Overweight"
elif getBMI() > 30:
self.__getStatus = "Obese"
def getName(self):
return self.__name
def getAge(self):
return self.__age
def getWeight(self):
return self.__weight
def getHeight(self):
return self.__height
a = calcBMI(name, age, weight, height)
print("The BMI for ", a.getName(), " is ", a.getBMI(), "which is ", a.getStatus())
I have a bit of an issue when trying to print for this BMI calculator, at the very end it should look like,
"The BMI for (name) is (BMI number), which is (status, basically if they're underweight, overweight etc.)"
In the getStatus() i am trying to take the numeric value from getBMI() and use it in the if statement. (I don't know why this is big and bold lettered)
The problem arises when I try to print, it's prompts me to input my name, age, weight, and height like normal.
This is what it outputs: NameError: name 'getBMI' is not defined
The reason is in the getStatus function, you are calling getBmi but you should be calling self.getBmi()
The getStatus function should look like this:
def getStatus(self):
if self.getBMI() < 18.5:
self.__getStatus = "Underweight"
elif 18.5 < self.getBMI() < 24.9:
self.__getStatus = "Normal"
elif 25.0 < self.getBMI() < 29.9:
self.__getStatus = "Overweight"
elif self.getBMI() > 30:
self.__getStatus = "Obese"
return self.__getStatus
Also, as input automatically returns a string, you can just say
name = input("What is your name? ")
getBMI is not defined as a global function, and so a NameError is thrown when you try to refer to it as just getBMI. The method of this name cannot be referenced nakedly like this in the way that C++ methods can. Instead, an instance must refer to its methods as attributes of self, i.e. as self.getBMI() in this case.

Categories