Issue
I am building a simple BMI calculator program and I wish it to take users back to the input field if they try zero division. i defined what output should be at that situation but it still prints out ZeroDivisionError
def bmi_calculator():
user_height = float(input('Enter your height in cm: ')) # user height in cm
user_weight = float(input('Enter your weight in kg: ')) # user weight in kb
bmi = user_weight / (user_height / 100) ** 2 # BMI formula
while user_height <= 0 or user_weight <= 0:
try:
print("your weight or height can't be below or equal 0 \n enter your credentials again... ")
user_height = float(input('Enter your height in cm: '))
user_weight = float(input('Enter your weight in kg: '))
except ZeroDivisionError:
print("You can't divide by 0")
user_height = float(input('Enter your height in cm: ')) # user height in cm
user_weight = float(input('Enter your weight in kg: ')) # user weight in kb
print(f'Your BMI is: {bmi}')
print(bmi_calculator())
Solution
I have already specified the problem in your code here, additionly:-
You are asking for the input from the user every time uneccesarily here's a short answer:
def bmi_calculator():
while True:
try:
error="your weight or height can't be below or equal 0"
height = float(input('Enter your height in cm: '))
weight = float(input('Enter your weight: '))
bmi=weight / (height / 100) ** 2
if weight==0:
print(error)
continue
print(f'Your BMI is {bmi}')
except ZeroDivisionError:
print(error)
bmi_calculator()
Note:- The BMI can be displayed in negative number which isn't correct I leave it to tackle that exception upon you. If you aren't able to solve that you can comment below this answer and I will update my answer accordingly.
Answered By - Aditya Yadav
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.