dubg
dubg

Reputation: 21

Why does the for loop accept a single letter int variable as opposed to a multi-letter?

I'm learning about basic for-loops in python and noticed that the variable 'x' works without error as opposed to the variable "sides". How come?

I've googled for loops and have learned about the difference between range and xrange, but nothing that seems relevant to my question.The following shows the 1st piece of code with the error:

ZeroDivisionError: integer division or modulo by zero on line...

# This code leads to the ZeroDivisionError
import turtle
wn = turtle.Screen()
mikey = turtle.Turtle()

sides = int(input("How many sides would you like your regular  
polygon to have?"))
length = int(input("How long would you like the sides to be?"))
color = ("What color would you like to fill the polygon?")

for sides in range(sides):

    mikey.down()
    mikey.forward(length)
    mikey.left(360/sides)
# this code works fine
import turtle
wn = turtle.Screen()
mikey = turtle.Turtle()

sides = int(input("How many sides would you like your regular  
polygon to have?"))
length = int(input("How long would you like the sides to be?"))
color = ("What color would you like to fill the polygon?")
x = sides

for sides in range(sides):

    mikey.down()
    mikey.forward(length)
    mikey.left(360/x)

How come the latter works fine but not the former?

Upvotes: 0

Views: 85

Answers (2)

sedavidw
sedavidw

Reputation: 11741

In your second code block x is being written with by what WAS in sides (from the input). Then sides is being overwritten from the iterable from range. So in the first code block sides gets re-written (to be 0 the first time through) and then it's the ZeroDivisionError

mikey.left(360/sides) # sides = 0 here

In the second code block you're using x instead which isn't being overwritten at all and only has a non zero number (and it doesn't change)

Upvotes: 0

Cameron
Cameron

Reputation: 203

In the first example, mikey.left(360/sides) would be zero the first time, as you're starting at 0 and going up to whatever value sides is.

In the second example, x is equal to whatever integer sides is, the entire time you're stepping through.

Though in either case you shouldn't use sides as the iterator variable, as it is already being used.

Upvotes: 1

Related Questions