简体   繁体   中英

Python:How do I print not only the final value after running the for statement, but also the middle output?

everybody. I want to make a code with a different name every time the For Moon is executed.

for i in range(10):
    SD="Vega"+str(i)
    print(SD)

print(SD)

After executing the code above The result is as follows:

Vega0
Vega1
Vega2
Vega3
Vega4
Vega5
Vega6
Vega7
Vega8
Vega9
Vega9

What should I do if I want to print a value not just for VD9 but also for VD2 after all the for statements have been executed in the code above?

you can store all the SD values in a list and access it later via indexing.

 list_sd = [] # initialize empty list
 for i in range(10):
     SD="Vega"+str(i)
     print(SD)         # prints "Vega1", "Vega2" etc.
     list_sd.append(SD) # appends the respective SD value to your list
print(SD) # prints the last VD, "Vega9" in this case
print(list_sd[i]) # i being the index, so list_vd[1] prints "Vega1" and so on...

You should store the intermediate values somewhere.

stored_values = []
for i in range(10):
    SD="Vega" + str(i)
    stored_values.append(SD)
print(SD)

or if you just want them as a long string that looks just like a print statement

SD = ''
for i in range(10):
    SD+="Vega" + str(i) + "\n"
print(SD)

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.

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