New to programming and I am having a conceptual block with the range function (explicit values versus iterations)

冷暖自知 提交于 2019-12-11 19:23:57

问题


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.



来源:https://stackoverflow.com/questions/17075618/new-to-programming-and-i-am-having-a-conceptual-block-with-the-range-function-e

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!