Lukáš Čimo
Lukáš Čimo

Reputation: 46

While loop change variables

I need to change the text in the variable after one round of the cycle. Like first round of loop a="A", second round a="B".

a = ("A")
a1 = ("B")
a2 = ("C")
a3 = ("D")
a4 = ("F")

i = 0
while i < 5:
    print(a)
    a += 1
    i += 1

Upvotes: 1

Views: 194

Answers (3)

foreverandthreedays
foreverandthreedays

Reputation: 101

Put the values in an array and access the values:

a = ['A', 'B', 'C', 'D', 'E']

i = 0
while i<5:
    print(a[i])
    i += 1

Upvotes: 3

olegr
olegr

Reputation: 2019

You could use lists in such kind of tasks:

a = "A"
a1 = "B"
a2 = "C"
a3 = "D"
a4 = "F"

values = [a, a1, a2, a3, a4] # This is the list of values that you could address by their index

i = 0
while i < len(values): # iterate while i is less than the amount of values
    print(values[i])
    i += 1

Read more about lists here

Upvotes: 0

Mercury
Mercury

Reputation: 310

Increasing a by one (in the line a += 1) will increase the contents of the variable, not change the name. You should instead use an array like

a = ['A', 'B', 'C', 'D', 'E']

and then iterate such as through

ans = a[i]
print(ans)

Upvotes: 0

Related Questions