简体   繁体   English

使用 for 循环遍历变量

[英]Iterating with for loop through variables

I'm fairly new to coding.我对编码相当陌生。 I'm trying to iterate the variable k through my function and store the results in a list.我正在尝试通过我的函数迭代变量 k 并将结果存储在列表中。 k starts with k=1 and ends with k=40. k 以 k=1 开始,以 k=40 结束。 But something isnt working.但有些东西不起作用。 My list only contains 0s.我的列表只包含 0。 Hopefully you can help me希望你能帮助我

Here is a Screenshot of my code这是我的代码的屏幕截图

Here is another attempt这是另一个尝试

Tn = []
for k in range(1, 40):
    x = ((40+0.2) / ((k-0.4))* (17/40))
    Tn.append(x)
    
print Tn

Your k variable is a range object, not an index.您的 k 变量是一个范围对象,而不是索引。

Try putting your variable inside a list, and then iterate through that list.尝试将您的变量放在一个列表中,然后遍历该列表。 You don't even have to use the range object to iterate through a list :您甚至不必使用 range 对象来遍历列表:

lst = [10, 20, 30, 40]

for item in lst:
    print(item) # print item if you use Python 2

And if you want to use an index :如果你想使用索引:

for index in range(len(lst)):
    print(lst[index]) # print lst[index] if you use Python 2

If you want to use variables :如果要使用变量:

a = 10
b = 20
c = 30
d = 40
lst = [a, b, c, d]

for item in lst:
    print(item) # print item if you use Python 2

Side note : you seem to be using Python 2. I would highly recommend you use Python 3.x (the latest the version the better).旁注:您似乎在使用 Python 2。我强烈建议您使用 Python 3.x(最新版本更好)。 The transition is not difficult at all, and even easier if you're new to coding.转换一点也不困难,如果您不熟悉编码,则更容易。 Python 3.x has way more to offer than Python 2 and you will quickly see its limitations. Python 3.x 比 Python 2 提供更多功能,您很快就会看到它的局限性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM