0

I'm getting confused as to how range works in terms of iterating values.

This is where I all of a sudden had a problem. Here's the code for sine v. degrees in radians:

for angle in range(10):
    y = math.sin(math.radians(angle))
    print(y)

I understand this perfectly. Python will calculate a sine value for each degree from 0 to 9.

Where I'm having trouble is with this code:

def square(x):
    runningtotal = 0
    for counter in range(x):
        runningtotal = runningtotal + x

    return runningtotal

toSquare = 10
squareResult = square(toSquare)

This is simply a code to arrive at a square calculation by summing up 10 10 times to arrive at 100.

The problem I'm having is that in the sine code, when math.sin is called as it goes through the range, it looks at it conceptually as [0,1,2,3,4,5,6,7,....] and calculates the correct sine value for each number until it goes through the range.

But as I look at the squaring code, to me range(x), where square(ToSquare) is the same as square(10), should conceptually be equal to [0,1,2,3,4,5,6,7,8,9]. But clearly the code is looking at is as 10 iterations of the number 10.

Where am I getting confused?

millimoose
  • 39,073
  • 9
  • 82
  • 134
  • 1
    Please format your question correctly http://stackoverflow.com/help/asking – jsedano Jun 12 '13 at 21:26
  • `runningtotal = runningtotal + x` should be `runningtotal = runningtotal + counter`. Your problem is your code is incorrect, not with the concept of iterating over a range. – millimoose Jun 12 '13 at 21:27
  • @millimoose His code is not incorrect. It is attempting to multiple 10, 10 times. What you would suggest would calculate the factorial, maybe? – coder543 Jun 12 '13 at 21:33
  • @coder543: Not the factorial, just the running sum, aka triangle number. To get the factorial, you'd need `*`, not `+`, and of course you'd have to start with 1, not 0. But anyway, the OP's code is right, and I think your answer explains the problem pretty well. – abarnert Jun 12 '13 at 21:35
  • Sorry, I noticed it was poorly formatted and started editing, but you beat me to it. Thanks again. – user2480030 Jun 12 '13 at 21:35

1 Answers1

3

In the first code block, it says

for angle in range(10):

and then proceeds to say

y = math.sin(math.radians(angle))

Notice the variable angle is used as an argument to math.radians?

In the other code sample, counter is the variable, but it is never used. The value is ignored, and the important thing is that the code still generates 10 iterations.

coder543
  • 803
  • 6
  • 16