Instead of typing the command print(w1) to print(w5) individually, how can I print the value of variables (from w1 to w5) automatically?
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)
don't really understand how you gonna use
for x in range(1, 5): print(globals()[f"w{x}"])
in the code in the question, there is no variable w
. It is just part of a string.
if you want to set w
as a variable that has callable elements then use it as a list, like this:
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])
this would return:
[0, 1, 2, 3, 4]
2
As an extra note, you can make a variable global
by using the global keyword, but this would usually be used for scope inside of a function.
w = [0,1,2,3,4]
def some_function():
global w
print('inside function:', w)
some_function()
which would return this:
inside function: [0, 1, 2, 3, 4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.