Not Getting Desired Result in Python Random Number Generator [duplicate] - python

I wrote this simple program to calculate one's BMI. But I am unable to execute it complete. Below is my program,
PROGRAM
h = input("Please Enter your height in meters:")
q = raw_input("Do you want to enter your weight in kg or lbs?")
if q=="kg":
w1 = input("Please Enter your weight in kgs:")
bmi1 = w1/(h*h)
print "Your BMI is", bmi1
if bmi1 <= 18.5:
print "Your are underweight."
if bmi1 > 18.5 & bmi1 < 24.9:
print "Your weight is normal."
if bmi1 > 25 & bmi1 < 29.9:
print "Your are overweight"
if bmi1 >= 30:
print "Your are obese"
if q=="lbs":
w2 = input("Please Enter your weightin lbs:")
bmi2 = w2/((h*h)*(39.37*39.37)*703)
print "Your BMI is:", bmi2
if bmi2<= 18.5:
print "Your are underweight."
if bmi2>18.5 & bmi2<24.9:
print "Your weight is normal."
if bmi2>25 & bmi2<29.9:
print "Your are overweight"
if bmi2>=30:
print "Your are obese"
OUTPUT
Please Enter your height in meters:1.52
Do you want to enter your weight in kg or lbs?kg
Please Enter your weight in kgs:51
Your BMI is 22.074099723
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bmi.py", line 11, in <module>
if bmi1 > 18.5 & bmi1 < 24.9:
TypeError: unsupported operand type(s) for &: 'float' and 'float'
Where am I going wrong? Anyone just let me know..
Thanks :).

& is a bitwise operator, I think you were looking for the boolean and.
But notice that Python also supports the following syntax:
if 18.5 < bmi1 < 24.9:
# ...
Since you seemed to have trobled with indentation this is how your script might look like:
h = raw_input("Please enter your height in meters: ")
h = float(h)
w_unit = raw_input("Do you want to enter your weight in kg or lbs? ")
w = raw_input("Please enter your weight in {}: ".format(w_unit))
w = int(w)
if w_unit == "kg":
bmi = w / (h*h)
elif w_unit == "lbs":
bmi = w / ((h*h) * (39.37 * 39.37) * 703)
print "Your BMI is {:.2f}".format(bmi)
if bmi <= 18.5:
print "Your are underweight."
elif 18.5 < bmi <= 25:
print "Your weight is normal."
elif 25 < bmi < 30:
print "Your are overweight"
elif bmi >= 30:
print "Your are obese"
There are a couple of slight improvements:
The explicit conversion (since in Python 3 the input function behave like raw_input and there's nothing like the Python 2 input, it might be a good habit to write your input like that)
What really changes is the bmi value, so there's no need to write two times the same thing.
Something left to do, might be wrap the whole script into functions :)

Related

How can I make the code loop from the beginning of the calculation (input height and weight)? I tried to use def main but I may used it wrong

A="Welcome"
B="Done by: "Name"
C="Class: "Class"
D="IT Final project - CP2"
E="A program that calculates the BMI and describes it as underweight, healthy, overweight, severly overweight, obese, severly obese"
print(A)
print(B)
print(C)
print(D)
print(E)
Height=input("Enter height in meters")
Height=float(Height)
Weight=input("Enter weight in kg")
Weight=float(Weight)
BMI=(Weight/Height**2)
if BMI <= 18.4:
print(BMI,"You are underweight")
elif BMI <= 24.9:
print(BMI,"You are healthy")
elif BMI <= 29.9:
print(BMI,"You are overweight")
elif BMI <= 34.9:
print(BMI,"You are severly overweight")
elif BMI <= 39.9:
print(BMI,"You are obese")
elif BMI > 39.9:
print(BMI,"You are severly overweight")
Repeat=input("Do you want to make a new calculation?(Yes/No)")
if "No":
print("Done")
exit()
elif: "yes":
What should I add here or anywhere else in the code?
So,
Your code is a little messed up at the start, lemme fix it real quickly
You shall remove the wrong placed (")
A="Welcome"
B="Done by: (Name) Jhon Smith"
C="Class: (Class) AB"
D="IT Final project - CP2"
E="A program that calculates the BMI and describes it as underweight, healthy, overweight, severly overweight, obese, severly obese"
Now that that's done, the main question.
You need to use while loops, while keeps running until the condition is false. In this case we want it to loop till the user types no.
So you will need to wrap your code with while 1:
Here it is: (Plus some edits to make the code work)
A="Welcome"
B="Done by: Name"
C="Class: Class"
D="IT Final project - CP2"
E="A program that calculates the BMI and describes it as underweight, healthy, overweight, severly overweight, obese, severly obese"
print(A)
print(B)
print(C)
print(D)
print(E)
while 1:
try:
height = float(input("Enter height in meters: "))
if height == 0:
print("Error, input not valid")
continue
except Exception:
print("Error, input not valid")
continue
try:
weight = float(input("Enter weight in kg: "))
if weight == 0:
print("Error, input not valid")
continue
except Exception:
print("Error, input not valid")
continue
bmi = (weight/height**2)
if bmi <= 18.4:
print(bmi, "You are underweight!")
elif bmi <= 24.9:
print(bmi, "You are healthy!")
elif bmi <= 29.9:
print(bmi, "You are overweight.")
elif bmi <= 34.9:
print(bmi, "You are severly overweight.")
elif bmi <= 39.9:
print(bmi, "You are obese.\nYou are severly overweight.")
while 1:
end = input("Repeat? (Yes/No): ")
if end.lower() == "yes":
break
elif end.lower() == "no":
print("Done.")
exit()
else:
print("Please type Yes/No")
```
This works perfect, if you need any help, post a comment!
PS: Press the check mark beside this answer to mark it as "helpful" / accept answer

How to remove a set of characters from a user inputted float - Python

I just started picking up python and I want to know how to do what I said in the title. The only background in programming I have is a semester long C++ class that I had in high school that I got a C in and forgot almost everything from. Here's my code:
while True:
try:
height_m = float(input("Enter your height in meters: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
while True:
try:
weight_kg = float(input("Enter your weight in kilograms: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
bmi = weight_kg / (height_m ** 2)
print ("Your bmi is",(bmi),".")
if bmi < 18.5:
print ("You are underweight.")
elif 18.5 <= bmi <=24.9:
print ("You are of normal weight.")
elif 25 <= bmi <= 29.9:
print ("You are overweight.")
else:
print ("You are obese.")
As you can see, it's just a basic BMI calculator. However, what I wanted to do was make it so that if someone were to input "1.8 m", "1.8 meters" or "1.8 ms" and the equivalent for kilograms, the program would remove the extra input and process it as if they hadn't added that. Also, any extra tips you have for me would be great. Thanks!
Replace the third line with this:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))
It works by removing all alphabets before converting to float.
In general, this works
Height_List = []
Height = input("What is your height")
for i in Height:
if i in "1234567890.":
Height_List.append(i)
Actual_Height = float("".join(Height_List))

Python 3.3: Invalid Syntax error in line 7 of the below code

Here is the code:
Weight = float(input("Enter weight in Kilograms: "))
Height = float(input("Enter height in meters: "))
BMI = (Weight / (Height**2))
print ("%.2f" %BMI)
if BMI < 18.5:
print ("You are under weight")
elif BMI >= 18.5 and < 25.0:
print ("You weight is normal")
elif BMI >= 25.0 and < 30.0:
print ("You are overweight")
elif BMI >= 30.0:
print ("You are overweight")
Getting invalid syntax at the line
elif BMI >= 18.5 and < 25.0:
>, <, and the rest are binary operators. It's looking for an operand on each side, and when it finds a keyword on its left and < 25.0 throws a SyntaxError.
The normal way to do this is:
if BMI >= 18.5 and BMI < 25.0:
But there is a shortcut for inequalities:
if BMT < 18.5:
# underweight
elif 18.5 <= BMI < 25.0:
# normal
elif 25.0 <= BMI < 30:
# overweight
elif 30 <= BMI:
# super overweight

Need help writing a python BMI calc

I am new to python and and currently learning to use functions properly.
I have been tasked with making a bmi calculator using python for my homework. This bmi calculator must give the option of whether to use metric or imperial units. based on this option it will then ask for your weight and height in the respectable unit type. This is where the problem stats - no matter what i input it still uses metric units and just seems to ignore my if/elif/else statments. so this is the first problem and i cant understand where i have gone wrong here.
after that problem is solved, the bmi that it calculates needs to be put into a category and then the program should tell you which category your bmi fits into, this part doesn't even work for the metric bmi it just says:
"""this is the error i keep getting, the actual code for the program is below"""
traceback (most recent call last):
File "C:/Python33/bmi calculator 2 2 2 2.py", line 54, in <module>
catagory(bmi)
File "C:/Python33/bmi calculator 2 2 2 2.py", line 45, in catagory
if bmi <18.5:
TypeError: unorderable types: tuple() < float()
"""this is a bmi calculator that works in both imperial and metric units
and can tell your bmi category"""
bmi = ()
metric = ("metric")
Metric = ("Metric")
imperial = ("imperial")
Imperial = ("Imperial")
MetricBMI = ()
ImperialBMI = ()
answer = input (" Do you want to work out you BMI using Metric or Imperial units?")
def BMI():
metric = ("metric")
Metric = ("Metric")
imperial = ("imperial")
Imperial = ("Imperial")
if answer.lower() == metric:
print("You have chose to calculate your bmi in metric units")
Weight_kg = float(input("What is your weight in kilograms (kg)"))
Height_m = float(input("What is your height in meters (m)?"))
bmi = Weight_kg/Height_m/Height_m
print("Your BMI is " + str(bmi))
elif answer.lower() == imperial:
print ("You have chosen to calculate your bmi in imperial units")
Weight_lbs = float(input("What is your weight in pounds (lbs)?"))
Height_inches = float(input("What is your height in inches??"))
bmi = Weight_lbs*703/Height_inches/Height_inches
print ("Your BMI is " + str(bmi))
else:
print ("please restart and enter either 'imperial' or 'metric'")
BMI()
def catagory(bmi):
if bmi <18.5:
return ("You are underweight")
elif bmi >=18.5 and bmi <25:
return ("You are normal weight")
elif bmi >= 25 and bmi <30:
return ("you are overweight")
elif bmi >=30:
return ("you are obese")
catagory(bmi)
Is this what you wish to do?
def catagory(BMI):
if BMI < 18.5:
print "You are underweight"
elif BMI >= 18.5 and BMI <25:
print "You are normal weight"
elif BMI >= 25 and BMI <30:
print "you are overweight"
elif BMI >= 30:
print "you are obese"
def BMI():
choice = raw_input("SI or Imperial? ")
weight = int(raw_input("weight: "))
height = int(raw_input("height: "))
if choice == "SI":
BMI = weight / (height * height)
if choice == "Imperial":
BMI = (weight * 703) / (height * height)
return BMI
BMI = BMI()
catagory(BMI)
Your BMI function dosn't return the value that was calculated for the BMI. To change this you can either let the function return the value of BMI to the main script, as shown above with "return BMI". Or you can declare BMI a global variable in your BMI function
Since your BMI function is modifying the global variable bmi, it needs to declare it:
def BMI():
global bmi
...
Without the global declaration, Python creates a local bmi variable, which is forgotten when the function finishes. The error you see is the result of the attempt to use the unchanged initial value of the global bmi variable. You would do well to remove this initialization altogether or get rid of the global variable altogether.

TypeError: unsupported operand type(s) for &: 'float' and 'float'

I wrote this simple program to calculate one's BMI. But I am unable to execute it complete. Below is my program,
PROGRAM
h = input("Please Enter your height in meters:")
q = raw_input("Do you want to enter your weight in kg or lbs?")
if q=="kg":
w1 = input("Please Enter your weight in kgs:")
bmi1 = w1/(h*h)
print "Your BMI is", bmi1
if bmi1 <= 18.5:
print "Your are underweight."
if bmi1 > 18.5 & bmi1 < 24.9:
print "Your weight is normal."
if bmi1 > 25 & bmi1 < 29.9:
print "Your are overweight"
if bmi1 >= 30:
print "Your are obese"
if q=="lbs":
w2 = input("Please Enter your weightin lbs:")
bmi2 = w2/((h*h)*(39.37*39.37)*703)
print "Your BMI is:", bmi2
if bmi2<= 18.5:
print "Your are underweight."
if bmi2>18.5 & bmi2<24.9:
print "Your weight is normal."
if bmi2>25 & bmi2<29.9:
print "Your are overweight"
if bmi2>=30:
print "Your are obese"
OUTPUT
Please Enter your height in meters:1.52
Do you want to enter your weight in kg or lbs?kg
Please Enter your weight in kgs:51
Your BMI is 22.074099723
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bmi.py", line 11, in <module>
if bmi1 > 18.5 & bmi1 < 24.9:
TypeError: unsupported operand type(s) for &: 'float' and 'float'
Where am I going wrong? Anyone just let me know..
Thanks :).
& is a bitwise operator, I think you were looking for the boolean and.
But notice that Python also supports the following syntax:
if 18.5 < bmi1 < 24.9:
# ...
Since you seemed to have trobled with indentation this is how your script might look like:
h = raw_input("Please enter your height in meters: ")
h = float(h)
w_unit = raw_input("Do you want to enter your weight in kg or lbs? ")
w = raw_input("Please enter your weight in {}: ".format(w_unit))
w = int(w)
if w_unit == "kg":
bmi = w / (h*h)
elif w_unit == "lbs":
bmi = w / ((h*h) * (39.37 * 39.37) * 703)
print "Your BMI is {:.2f}".format(bmi)
if bmi <= 18.5:
print "Your are underweight."
elif 18.5 < bmi <= 25:
print "Your weight is normal."
elif 25 < bmi < 30:
print "Your are overweight"
elif bmi >= 30:
print "Your are obese"
There are a couple of slight improvements:
The explicit conversion (since in Python 3 the input function behave like raw_input and there's nothing like the Python 2 input, it might be a good habit to write your input like that)
What really changes is the bmi value, so there's no need to write two times the same thing.
Something left to do, might be wrap the whole script into functions :)

Categories

Resources