如何打印变量的值??(注意:使用for循环将变量声明为全局变量)



我如何自动打印变量值(从w1到w5(,而不是单独键入命令print(w1)print(w5)

i = 0
for j in range(5):
i += 1
globals()["w"+str(i)] = list(range(1,20))
print(w1)
print(w2)
print(w3)
print(w4)
print(w5)

真的不明白如何使用

for x in range(1, 5): print(globals()[f"w{x}"])

在问题中的代码中,没有变量w。它只是一根绳子的一部分。

如果要将w设置为具有可调用元素的变量,则将其用作列表,如下所示:

w = []  # set w to an empty list
for j in range(5):
w.append(j)  # fill the list

# print the whole list
print(w)
# print one element from the list
print(w[2])

这将返回:

[0, 1, 2, 3, 4]
2

另外需要注意的是,您可以通过使用global关键字生成一个变量global,但这通常用于函数内部的作用域。

w = [0,1,2,3,4]
def some_function():
global w
print('inside function:', w)
some_function()

它会返回这个:

inside function: [0, 1, 2, 3, 4]

最新更新