0

I'm coding a menu. Options 1,2 and 3 will populate project. Options 4, 5 and 6 depend on the value of project. I want to strikethrough options 4,5 and 6 if project == None.

project = None
menuOptions = {0 : 'Option4', 1 : 'Option5', 2 : 'Option6'}

print("""
Choose:

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
1 : Option1 
2 : Option2
3 : Option3

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
4 : {0}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
5 : {1}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
6 : {2}     

    
0 : Exit""".format('\u0336'.join(menuOptions[0]) + '\u0336' if project == None else menuOptions[0],
                   '\u0336'.join(menuOptions[1]) + '\u0336' if project == None else menuOptions[1],
                   '\u0336'.join(menuOptions[2]) + '\u0336' if project == None else menuOptions[2]))

The code above works fine, but I'm wondering if there is a way of reducing the necessary code following this idea:

format( 
    for opt in menuOptions: 
        '\u0336'.join(menuOptions[opt]) + '\u0336' if project == None else menuOptions[opt]
)

The objective is to be able to add new elements into menuOptions, show them in the menu and apply the same formatting without having to "hardcode" it.

2 Answers 2

1

You can use a starred comprehension here:

"""...""".format(*('\u0336'.join(opt) + '\u0336' if project is None else opt
                   for opt in menuOptions))
Sign up to request clarification or add additional context in comments.

1 Comment

Works just as intended, just had to change the .join(opt) with .join(menuOptions[opt]) . Thanks, I didn't know about argument unpacking.
1

So not sure if this is what you wanted, but you can reduce the "hardcording" a bit by doing this:

# list comprehension to get format options 
# (you can use a loop here instead for more readability if needed)
x = ['\u0336'.join(menuOptions[opt]) + '\u0336' if project == None else menuOptions[opt] for opt in menuOptions]

print("""
Choose:

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
1 : Option1 
2 : Option2
3 : Option3

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
4 : {0}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
5 : {1}

━━━━━━━━━━━━ Text ━━━━━━━━━━━━
6 : {2} 

    
0 : Exit""".format(*x))

The * operator unpacks the list for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.