Python Spent Fuel Exercise

Asked

Viewed 835 times

-1

I’m starting in Python and I’m doing some exercises, I did this spent fuel, but it does not show me the end of the program, ie the result, what is the error?

nome = input("Qual é o seu nome?")

gasto = input("{}, digite o tempo gasto na viagem (em horas): ".format(nome))

velocidade = input('{}, digite agora a velocidade média praticado na viagem: '.format(nome))

consumo = float(velocidade/12)

print("Foram gastos ", consumo, " litros de combustível.")

The error generated is:

Traceback (Most recent call last): File "/home/Ralf/Pycharmprojects/Projetopython/Gasto_combustivel.py", line 4, in consumption = float (speed / 12) Typeerror: Unsupported operand type(s) for /: str and 'int'

2 answers

1

It’s very simple. The function input returns at all times a string, regardless of whether the user typed only numbers. In Python it is not possible to perform arithmetic operations with strings ( even if they are numbers in the format of string ). To fix this error, you must convert it to float or int. Example:

This code will give the same error:

print("98.3"/12)

This code nay make a mistake:

print(float("98.3")/12)

Now that we know about it, what would your corrected code look like ? It would look like this:

nome = input("Qual é o seu nome?")

gasto = float(input("{}, digite o tempo gasto na viagem (em horas): ".format(nome)))

velocidade = float(input('{}, digite agora a velocidade média praticado na viagem: '.format(nome)))

consumo = velocidade/12

print("Foram gastos ", consumo, " litros de combustível.")

It is also important to say that, split operations (/) in Python at all times will return a float. Therefore conversion is not necessary in the division calculation. Example:

>>> 10/2
5.0
  • Certainly, this was my mistake, thank you for the clarification, Jean.

0

Hello, you must convert to speed for int or float:

velocidade = int(input('{}, digite agora a velocidade média praticado na viagem: '.format(nome)))

Or

velocidade = float(input('{}, digite agora a velocidade média praticado na viagem: '.format(nome)))

Or else:

consumo = float(int(velocidade)/12)
  • 1

    But why you need to convert the split result, which is already a float, to another float?

Browser other questions tagged

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