Instead of storing each value in it's own variable, I would suggest storing all of the values in a list
:
Storing in a list -
v = ["First", "Second", "Third"...]
To access the value in this list, you would use syntax similar to this (note that in python, lists start at index zero):
str = v[0]
# str will now be equal to "First"
Now when you use range
, you'll generate a sequence of numbers that can be used as the index of your list:
for x in range (0,11):
print(v[x])
So this loop will evaluate to print commands such as:
print(v[0]) # "First"
print(v[1]) # "Second"
print(v[2]) # "Third"
...
Accessing a list at a specific index will return the value stored at the same index.
Please note that I've changed range()
to start at zero since if you start at 1
you'll be skipping the first element at index zero. In addition, this code could further be improved by using the length of the list as the "end"
index for the range:
v = ["First", "Second", "Third"...]
num_items = len(v)
for x in range(0, num_items):
print(v[x])
Using this method, your v
list can be different sizes and you won't need to make any changes to the loop.
A final note thanks to a helpful commenter: The range function actually uses zero as a default first value, so the loop could be simplified even further:
for x in range(num_items):
print(v[x])