New to programming and I am having a conceptual bl

2019-09-05 05:52发布

问题:

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?

回答1:

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.



标签: python range