I don't understand why I can't use my variable c.

code:

from turtle import * speed(0) hideturtle() c = 450 def grid(x,y,a): seth(0) pu() goto(x,y) pd() for i in range(4): forward(a) rt(90) for i in range(c/10): seth(0) forward(10) rt(90) forward(c) backward(c) for i in range(c/10): seth(0) rt(90) forward(10) rt(90) forward(c) backward(c) pu() goto(a+10,0) write("x") goto(0,a+10) write("y") pd() grid(0,0,c) grid(-c,0,c) grid(-c,c,c) grid(0,c,c) 

I get the following error message:

Traceback (most recent call last): File "C:\Users\nick\Desktop\gridv2.py", line 35, in <module> grid(0,0,c) File "C:\Users\nick\Desktop\gridv2.py", line 15, in grid for i in range(c/10): TypeError: 'float' object cannot be interpreted as an integer 

4 Answers

In:

for i in range(c/10): 

You're creating a float as a result - to fix this use the int division operator:

for i in range(c // 10): 
1

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10 45.0 >>> range(450 / 10) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object cannot be interpreted as an integer 

Make the value an integer again:

for i in range(int(c / 10)): 

or use the // floor division operator:

for i in range(c // 10): 
0

As shown below, range only supports integers:

>>> range(15.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: range() integer end argument expected, got float. >>> range(15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> 

However, c/10 is a float because / always returns a float.

Before you put it in range, you need to make c/10 an integer. This can be done by putting it in int:

range(int(c/10)) 

or by using //, which returns an integer:

range(c//10) 
0

It is also possible to fix this with np.arange() instead of range which works for float numbers:

import numpy as np for i in np.arange(c/10): 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy