[Tutor] Stuck on some basics re floats
Peter Otten
__peter__ at web.de
Wed Jul 18 03:34:40 EDT 2018
Matthew Polack wrote:
> Hi,
>
> I'm a teacher trying to learn Python with my students.
>
> I am trying to make a very simple 'unit calculator' program...but I get an
> error ..I think python is treating my num1 variable as a text string...not
> an integer.
>
> How do I fix this?
>
> Thanks!
>
> - Matt
>
> print ("How many inches would you like to convert? ")
> num1 = input('Enter inches here')
As you have guessed, at this point num1 is a string. You can convert it to a
float with
num1 = float(num1)
> print ("You have entered",num1, "inches")
> convert = num1 * 2.54
> print ("This is", convert, "centimetres")
>
>
> Traceback (most recent call last):
> File "convert.py", line 10, in <module>
> convert = num1 * 2.54
> TypeError: can't multiply sequence by non-int of type 'float'
Note that int is mentioned here because Python can multiply int with str,
though the result might surprise you:
>>> "spam" * 3
'spamspamspam'
So * also works as the repetition-operator just like + is also used to
concat strings.
More information about the Tutor
mailing list