Kennerdol
Kennerdol

Reputation: 130

How to solve ValueError: invalid literal for int() with base 10: '1.81'?

# Body Mass Index Calculator

def BMI_calculator( ):
    name = input('Enter your name: ')
    weight_kg = int(input('Enter your weight in kg: '))
    height_m = int(input('Enter your height in meters: '))
    print('The BMI for ' + name + ' is: ')
    BMI = int(weight_kg) / height_m ** 2
    return BMI

print(BMI_calculator())

My error is:

Traceback (most recent call last): 
  File "F:/Programming/Python 3 Tutorials/Tuturial/Automate the boring stuff with python/Others BMI_calculator.py", line 13, in <module>
    print(BMI_calculator())
  File "F:/Programming/Python 3 Tutorials/Tuturial/Automate the boring stuff with python/Others/BMI_calculator.py", line 7, in BMI_calculator
    height_m = int(input('Enter your height in meters: '))
ValueError: invalid literal for int() with base 10: '1.67'
Process finished with exit code 1

Upvotes: 0

Views: 1719

Answers (1)

Nathan
Nathan

Reputation: 3648

First of, next time be sure to explain what problems you're running into, something like this:

I'm having trouble converting my input into numbers, when I run it, I get this error:

Traceback (most recent call last):

File "C:/Users/Nathan/.PyCharmCE2019.2/config/scratches/scratch_35.py", line 13, in

print(BMI_calculator())

File "C:/Users/Nathan/.PyCharmCE2019.2/config/scratches/scratch_35.py", line 8, in BMI_calculator

height_m = int(input('Enter your height in meters: '))

ValueError: invalid literal for int() with base 10: '1.81'

The problem is that your input (in meters) is going to be something like 1.81, you cannot convert that to an integer (because of the .), so instead convert it to a float, like this:

height_m = float(input('Enter your height in meters: '))

On another note Your BMI calculator asks for my name, which is a little weird because you don't need my name to calculate my BMI. If I were to rewrite your code, I'd do something like:

# Body Mass Index Calculator

def BMI_calculator(weight_kg, height_m):
    BMI = int(weight_kg / height_m ** 2)
    return BMI

# Only run this code if your run this file
# This allows for easy importing of BMI_calculator in other files
if __name__ == '__main__':
    # Get the inputs to your function
    name = input('Enter your name: ')
    weight_kg = float(input('Enter your weight in kg: '))
    height_m = float(input('Enter your height in meters: '))

     # Calculate BMI
    bmi = BMI_calculator(weight_kg=weight_kg, 
                         height_m=height_m)

    # Print the results
    print(f'The BMI for {name} is: {bmi}')

The f-string (f'lalaal {variable}') prints the value of the variable directly into the string. It makes your life easier to do it this way and it's more readable.

Upvotes: 1

Related Questions