I'm having a problem sizing down this block of code:

if POS == 1:
        POS1 = "->"
    else:
        POS1 = "  "

    if POS == 2:
        POS2 = "->"
    else:
        POS2 = "  "
        
    if POS == 3:
        POS3 = "->"
    else:
        POS3 = "  "

    if POS == 4:
        POS4 = "->"
    else:
        POS4 = "  "

    if POS == 5:
        POS5 = "->"
    else:
        POS5 = "  "

    if POS == 6:
        POS6 = "->"
    else:
        POS6 = "  "

    if POS == 7:
        POS7 = "->"
    else:
        POS7 = "  "

    if POS == 8:
        POS8 = "->"
    else:
        POS8 = "  "

    if POS == 9:
        POS9 = "->"
    else:
        POS9 = "  "
        
    if POS == 1:
        POS1 = "->"
    else:
        POS1 = "  "

The reason why I can't figure it out is mainly because the sequence I would use a for loop with is in a variable. Any suggestions would be appreciated.

Recommended Answers

All 7 Replies

locals_dict = locals()
for i in range(1, 10):
    var_name = "POS" + str(i)
    if i == POS:
        locals_dict[var_name] = "->"
    else:
        locals_dict[var_name] = " "

discalimer: That code uses hacks and the purists may have your head for it.

Yes, I see how that would be considered a hack. Will it be fairly reliable? Or will it crash most of the time.

Why do you want to have vars named POSn.
I wouldn't do that...
Very complicated. It's far easier to have one list variable where you assign pos[n]

pos=['  ' for i in range(10)] # defines a list inited with ['  ', '  ',... ten times]
pos[POS-1]='->'

Similar to jice's code:

# simply ignore index zero
pos = ['  '] * 11
print( pos )

POS = 1

pos[POS] = '->'
print( pos )

"""my display -->
['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ']
['  ', '->', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ']
"""

If I knew how the 2nd line of Jiccess code I could make it work. But I forgot to mention that each POS variable is in a certain place. I won't work to only have 1 variable. I also forgot to mention that scru's code didn't work either, it said that POS1 wasn't defined.

If I knew how the 2nd line of Jiccess code I could make it work. But I forgot to mention that each POS variable is in a certain place. I won't work to only have 1 variable. I also forgot to mention that scru's code didn't work either, it said that POS1 wasn't defined.

Sorry but I don't understand what you mean.
What do you mean with "each POS variable is in a certain place" ?

If I use one variable, it contains the tenth values.
Instead of using POS1, you'll use pos[0], POS5 will become pos[4]...

OH, now I get it, sorry, yes it does work. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.