Why when I inform "1.93" gives error when converting to integer?

Asked

Viewed 53 times

-1

print('Calculadora de IMC')
peso = input('Insira o seu peso (em kg): ')
altura = input('Insira sua altura (em metros): ')

IMC = int(peso) / int(altura)**2

When I set the height value to "1.93" an error appears talking like this:

    IMC = int(peso) / int(altura)**2
ValueError: invalid literal for int() with base 10: '1.93'

You have to leave the code so I can put the broken values?

  • Yes. The value "1.93" is not a valid integer value, so it is expected to give the cited error.

  • how can I write to put this broken value?

  • Don’t treat him as whole... maybe as float.

  • @orbitB374 Use the type float.

  • thank you guys :) I’m new in python, so I’m learning everything yet

1 answer

3


As you can see in official documentation:

class int([x]) / class int(x, base=10)

Return an integer Object constructed from a number or string x, or Return 0 if no Arguments are Given. If x defines __int__(), int(x) Returns x.__int__(). If x defines __trunc__(), it Returns x.__trunc__(). For floating point Numbers, this Truncates Towards zero.

If x is not a number or if base is Given, then x must be a string, bytes, or bytearray instance Representing an integer literal in Radix base.

The parameter can be a number or a string. If the parameter implements the method __trunc__(), the value will be returned x.__trunc__(), which is the case when you pass a number with floating point.

If the parameter defines __int__() then you will be returned x.__int__().

If the parameter is of type string, bytes or bytearray, then the conversion will be made according to the informed base, which by default is 10, decimal base, which we use in day-to-day. When passing a figure like '1.93', due to the presence of quotation marks, this will be a string and therefore the conversion of that string to integer in base 10 will be attempted. As the value 1.93 is invalid in base 10 (because the character . does not exist in base 10), gives the cited error.

But this was only to explain why the error, because the solution is simpler than this, given that it is a logic error even, since a decimal input is expected and is being treated as integer. Just. Then, treat it properly as decimal. For this, one of the ways to do is by using float.

An alternative is to use the library decimal, python native.

  • Hmmm got it, damn you explained very well thanks friend, really, I managed to assemble the calculator right here. have a good day :D

  • 1

    @orbitB374 do not forget to signal as a favorite answer if this was the best solution for you.

  • 1

    @orbitB374 And first of all, please do the [tour].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.