[Tutor] Count for loops

Alan Gauld alan.gauld at yahoo.co.uk
Sat Apr 8 14:38:14 EDT 2017


On 08/04/17 13:49, Rafael Knuth wrote:

>> b = "3"+b[2:]  #Removing the decimal point so that there are digits only in
> 
> my_number = 3.14159

Here you assign a floating point number to mmy_number but
the code Sama wrote was for working with strings read
from a text file.

You would need to convert it first:

my_number = str(3.14159)

> my_number = "3"+my_number[2:]
> print(my_number)
> 
> This is the error code I got:
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/CODING/Python Code/PPC_56.py ==
> Traceback (most recent call last):
>   File "C:/Users/Rafael/Documents/01 - BIZ/CODING/Python
> Code/PPC_56.py", line 2, in <module>
>     my_number = "1"+my_number[2:]
> TypeError: 'float' object is not subscriptable

And that is what the error tells you, that you are trying
to index a float but it should be a string.

> In case of a text file, your code works, but if I apply the same to a
> float assigned to a variable, it does not work.

That's right, the set of operations applicable to numbers is
completely different to those applicable to strings, you cannot
mix 'n match. You need to convert between the types.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list