Exception handling for different inputs in Python - python

i am a beginner in python and i've tried to create a BMICalculator program and i am currently facing an issue
first up when you open the program it asks the user for their height and weight input
and i have created a try-exception handling for when a user tries to put a string into their Height/Weight input
But the problem is, when a user enters their Height properly, and then uses a string for their Weight, my ValueError exception does show up, but makes the user enter their Height again which is not user friendly,
So what i want to do but don't know how is:
To ask the user again for their Weight input not Height, as they have already entered that
My Code:
import math
import time
def BMICalculator():
print("BMI Calculator!")
try:
Height = float(input("Enter your Height: "))
Weight = float(input("Enter your Weight: "))
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))
if Result <= 18.5:
print("You are underweight")
elif Result <= 24.9:
print("You are healthy")
elif Result <= 29.9:
print("You are overweight")
elif Result > 29.9:
print("You are obese")
except ValueError:
print("Please enter a valid number")
BMICalculator_NoWelcomingMessage()
def BMICalculator_NoWelcomingMessage():
try:
Height = float(input("Enter your Height: "))
Weight = float(input("Enter your Weight: "))
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))
if Result <= 18.5:
print("You are underweight")
elif Result <= 24.9:
print("You are healthy")
elif Result <= 29.9:
print("You are overweight")
elif Result > 29.9:
print("You are obese")
except ValueError:
print("Please enter a valid number")
BMICalculator_NoWelcomingMessage()
def enter_again():
user = input("Do you want to enter again?: ").lower()
while user not in ['yes', 'y', 'no', 'n']:
print("Please enter a valid input")
user = input("Do you want to enter again?: ").lower()
if user not in ['yes', 'y']:
print("Have a nice day!")
time.sleep(1)
elif user not in ['no','n']:
BMICalculator_NoWelcomingMessage()
enter_again()
BMICalculator()
enter_again()

Well, the reason that happens is because you have a single catch statement for both the inputs, and if either of them throws an error, you restart the entire process.
You can fix this with a minor modification, have the two inputs in separate catch blocks, and have a while true loop to keep asking for a valid input till you get one.
Here's what I said in code:
def BMICalculator():
print("BMI Calculator!")
while True:
try:
Height = float(input("Enter your Height: "))
break
except ValueError:
print("Please enter a valid number")
while True:
try:
Weight = float(input("Enter your Weight: "))
break
except ValueError:
print("Please enter a valid number")
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))
Note: You can probably parse the input in a separate function, and call that function when taking input for weight and height, would make the code cleaner. Something like this perhaps:
def parse_input(InputName):
while True:
try:
value = float(input(f"Enter your {InputName}: "))
break
except ValueError:
print("Please enter a valid number")
return value
def BMICalculator():
print("BMI Calculator!")
Height = parse_input("Height")
Weight = parse_input("Weight")
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))

Related

bmi calculator how do restart the calculator to go back to yes/no at the top

Take_Bmi=(input("Take bmi yes or no "))
if Take_Bmi == "yes":
name1=input(" enter your name")
height_m1=input(" enter your height in m")
weight_kg1=input(" enter your weight")
def bmi_calculator(name1,height_m1,weight_kg1):
bmi = float(weight_kg1) / (float(height_m1)** 2)
#The input function returns a string. So to get your output you
#need to use "float()" for height and weight:
print("bmi: ")
if bmi < 25 :
print(bmi)
return name1 + " not overweight"
else:
print(bmi)
return name1 + " is overweight"
result= bmi_calculator(name1,float(height_m1),float(weight_kg1))
print(result)
else:
print("thank you")
how do i like repeat this test like print(do you wan to take again)
goes back to would you like to take bmu yes /no at the top
The input function returns a string.
So to get your output you need to use "float()" for height and weight:
bmi = float(weight_kg1) / (float(height_m1)** 2)
Also, you have to call your function, e.g.
bmi_calculator(name1,float(height_m1),float(weight_kg1))
After printing the result
You can add a if else condition where you can take input from the user and ask them, then accordingly you can recall your function or else exit it.
Like this:-
Take_Bmi=(input("Take bmi yes or no "))
if Take_Bmi == "yes":
def takeBMI():
name1=input(" enter your name")
height_m1=input(" enter your height in m")
weight_kg1=input(" enter your weight")
def bmi_calculator(name1,height_m1,weight_kg1):
bmi = float(weight_kg1) / (float(height_m1)** 2)
if bmi < 25 :
print(bmi)
return name1 + " not overweight"
else:
print(bmi)
return name1 + " is overweight"
result= bmi_calculator(name1,float(height_m1),float(weight_kg1))
print(result)
again=(input("Take bmi again yes or no "))
if again=="yes":
takeBMI()
else:
exit(0)
takeBMI()
else:
print("thank you")

Passing 'ValueError' & 'continue' in a function and call it

I am trying to check user inputs to ensure that:
1) It is a floating number
2) Floating number is not negative
I am trying to put above 2 checks into a function and call it after user has input into a variable.
However, I cant seem to put 'ValueError' & 'continue' in a function that I can call. Is this possible?
I have tried below code, but it repeats from the top when I key in 't' for salCredit, or any of the next few variables. The code will work if I were to repeat 'ValueError' & 'continue' for every variable. I'm just wondering if there is a shorter way of doing do?
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
#checkInputError(accBal)
salCredit = float(input("Enter your Salary: "))
#checkInputError(salCredit)
creditCard = float(input("Credit Card Spend (S$): "))
#checkInputError(creditCard)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
interestCalculator()
Expected results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Salary: 500
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a valid number.
Enter your Salary: 500
Current results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Account Balance:
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a positive number.
Credit Card Spend (S$):
You could create a function that continues prompting for input until a valid float is input
def get_float_input(prompt):
while True:
try:
user_input = float(input(prompt))
if user_input < 0:
print("Please enter a positive number.")
continue # start the while loop again
return user_input # return will break out of the while loop
except ValueError:
print("Please enter a valid number.")
mul_AccBal = get_float_input("Enter your Account Balance: ")
salCredit = get_float_input("Enter your Salary: ")
creditCard = get_float_input("Credit Card Spend (S$): ")
Try this:
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
invalid = True
while invalid:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
salCredit = float(input("Enter your Salary: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
creditCard = float(input("Credit Card Spend (S$): "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
return True
return False
interestCalculator()
you need to break you while loop if all the input is successful (also note that the continue at the end of the while loop is unnecessary). and if you want to have a validation for every number separately, you could do something like this:
def get_float(message, retry_message="Please enter a valid number."):
while True:
try:
ret = float(input(message))
if ret >= 0:
return ret
else:
print(retry_message)
except ValueError:
print(retry_message)
def interestCalculator():
mul_AccBal = get_float("Enter your Account Balance: ")
salCredit = get_float("Enter your Salary: ")
creditCard = get_float("Credit Card Spend (S$): ")

BMI with exception handling python

I need help with this code I am trying to apply, a short time ago I ran a bmi calculator in index and now I am trying to update that code with exception handling. So far the portions don't give me errors they just run strangely together. For example, when it prompts "Enter the user's name or '0' to quit" it doesn't actually end the process it continues on to the exception process. Can someone help me write this more efficiently. here is my code this is updated, the issue I am specifically having now is the program is not terminating when the user enters '0':
def bmi_calculator():
end = False
print("Welcome to the BMI Calculator!")
while end == False:
user = input("Enter student's name or '0' to quit: ")
if user == "0":
print("end of report!")
end = True
else:
print("Lets gather your information,", user)
break
flag='yes'
while flag != 'no':
#Exception block for catching non integer inputs
try:
#Prompting user to input weight
weight = int(input('Enter your weight in pounds : '))
if weight == 0:
raise ValueError
except ValueError:
print ('Oops!! Kindly enter non-zero numbers only.')
flag = input('Do you want to try again? yes/no : ')
continue
try:
#Prompting user to input height
height = float(input('Enter your height in inches : '))
if height == 0:
raise ValueError
except ValueError:
print ('Oops!! Kindly enter non-zero numbers only.')
flag = input('Do you want to try again? yes/no : ')
continue
#Formula for calculating BMI
BMI = round(weight * 703/(height*height), 2)
return (BMI)
print(" Your bmi is:", bmi_calculator())

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

The loop for 10 times is not working, displaying a text, and having an exception error in python

My program wants to repeat it 10 times which I tried to do by putting in for i in range(10):, it doesnt do it 10 times
Also I need to have an exception error like if a user enters forty instead of 40, I can display "error, you must enter the value as an integer" but my cmd prompt says I have an inconsistent use of tabs and indentation.
my last one is that when I try to display my conversions to a text, it says the variable isn't defined which makes no sense... for example outfile.write(str(miles) + "\n"), my cmd prompt states that the name miles is not defined and i define miles in the code
Here's my code:
# constants for the menu choices
Mi_to_km_choice=1
F_to_C_choice=2
Gallons_to_liters_choice=3
Pounds_to_Kilograms_choice=4
Inches_to_Centimeters_choice=5
Quit_choice=6
#open a new file named conversions.txt
outfile= open("conversions.txt" , "w")
#the main function
def converting():
for i in range(10):
#a.converting Miles to Kilometers
#choice variable controls the loop
choice=0
while choice != Quit_choice:
#display the menu
display_menu()
#get the user's choice
choice= int(input("Enter your choice:"))
#perform the selected action
#miles to km
if choice == Mi_to_km_choice:
counter = 1
miles = int(input("Enter a value for miles "))
while miles < 0:
print("Error, you can't enter a negative value for miles")
miles = eval(input("Enter the correct value for miles "))
counter+=1
if counter > 3:
break
if counter <= 3:
kilometers= miles * 1.6
print(miles , "miles is", kilometers , "kilometers")
except ValueError:
print("Error: Miles must be an integer")
else:
print("You have the exceeded error count")
#b.converting Fahrenheit to Celsius
elif choice == F_to_C_choice:
counter = 1
fahrenheit = int(input("Enter a value for fahrenheit "))
while fahrenheit > 1000:
print("Error, you can't enter a value above 1000 degrees fahrenheit")
fahrenheit = eval(input("Enter the correct value for fahrenheit "))
counter+=1
if counter > 3:
break
if counter <= 3:
celsius= (fahrenheit-32) * 5/9
print(fahrenheit , "degrees fahrenheit is", celsius , "degrees celsius")
else:
print("You have exceeded the error count")
#c.converting Gallons to Liters
elif choice == Gallons_to_liters_choice:
counter=1
gallons= int(input("Enter a value for gallons "))
while gallons < 0:
print("Error, you can't enter a negative for gallons")
gallons = eval(input("Enter the correct value for gallons "))
counter+=1
if counter > 3:
break
if counter <= 3:
liters= gallons * 3.9
print(gallons , "gallons is", liters , "liters")
else:
print("You have exceeded the error count")
#d. converting Pounds to Kilograms
elif choice == Pounds_to_Kilograms_choice:
counter=1
pounds= int(input("Enter a value for pounds "))
while pounds < 0:
print("Error, you can't enter a negative for pounds")
pounds = eval(input("Enter the correct value for pounds "))
counter+=1
if counter > 3:
break
if counter <= 3:
kilograms= pounds * .45
print(pounds , "pounds is", kilograms , "kilograms")
else:
print("You have exceeded the error count")
#e.converting Inches to Centimeters
elif choice == Inches_to_Centimeters_choice:
counter=1
inches= int(input("Enter a value for inches "))
while inches < 0:
print("Error, you can't enter a negative negative value for inches")
inches=eval(input("Enter the correct value for inches "))
counter+=1
if counter > 3:
break
if counter <=3:
centimeters= (inches * 2.54)
print(inches, "inches is", centimeters, "centimeters")
else:
print("You have exceeded the error count")
elif choice == Quit_choice:
print("Exiting the program...")
else:
print("Error: invalid selection. ")
#display the menu
def display_menu():
print(" Menu")
print("1) Miles to Kilometers")
print("2) Fahrenheit to Celsius")
print("3) Gallons to Liters")
print("4) Pounds to Kilograms")
print("5) Inches to Centimeters")
print("6) Quit")
#write the conversions to the file
outfile.write(str(miles) + "\n")
outfile.write(str(kilometers) + "\n")
outfile.write(str(gallons) + "\n")
outfile.write(str(liters) + "\n")
outfile.write(str(pounds) + "\n")
outfile.write(str(kilograms) + "\n")
#close the file
outfile.close()
print("Data written to conversions.txt")
#call the main function
converting()
Your prompt is telling you exactly what's wrong...
Your indentation is wrong, you have different amounts of indentation in different parts of the program.
In Python indentation matters, so you will need to go through your program and see that you have the right amount of spaces. Normally one level of indentation is 4 spaces. Most Python editors will handle this for you.
And your indentation fault is that your except ValueError is one space wrong to the left:
if counter <= 3:
kilometers= miles * 1.6
print(miles , "miles is", kilometers , "kilometers")
except ValueError:
print("Error: Miles must be an integer")
Start by making the indentation right, it will help your error searching for the rest of the program.
The range function you are using will set i in to 0,1,2...9 so it will run 10 times.
In your write function miles (and the others) are not defined because they are defined in another function, in another scope, so your display function cannot reach them, hence the error.

Categories

Resources