'How to conditionally print the input by user in Python?

def ask_question(question, option1, option2, option3, option4):
    print(question)
    print('1', option1)
    print('2', option2)
    print('3', option3)
    print('4', option4)
    print('Your answer:', input())

ask_question('Which color is your favorite?', 'red',
'lime', 'blue', 'gray')

What should I add more to fulfill "if a choice is equal to the empty string, then do not print that choice nor the adjacent number to the screen" this condition?



Solution 1:[1]

You should better try something like this:

var = input()
print(f"Your answer: {var}") if var else print('')

This is an inline if statement, that prints a newline if the input's returned value is False: ''.


If you want to avoid all the options which are empty strings:

def ask(question, *options):
    print(question)
    for index, option in enumerate(options):
        if option:
            print(f"{index} {option}")

Solution 2:[2]

As I understand you want to skip print that option if it is an empty string. then one of the solutions is this, (can be improvised based on the more specific requirements).

def ask_question(question, option1, option2, option3, option4):
    print(question)
    print('1', option1) if option1 != '' else None #or do what you want
    print('2', option2) if option2 != '' else None 
    print('3', option3) if option3 != '' else None 
    print('4', option4) if option4 != '' else None 
    print('Your answer:', input())
    

ask_question('Which color is your favorite?', 'red',
'lime', 'blue', 'gray')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MisterMiyagi