Home > Mobile >  Need to set a default value for multiple input for list in Python
Need to set a default value for multiple input for list in Python

Time:08-29

I'm trying to get the default value if input is blank, how can I do that?

Output what I'm getting is for variable is blank if there is no user input.

Brand_default = 'ABC','XYZ'
cate_default = 'GKK','KKL','MKK','UKK'

Brand = list(input('Please enter Brand? (ABC/XYZ)= ').split(',') or Brand_default)
Cate = list(input('Please enter Category?GKK,KKL,MKK,UKK = ').split(',') or cate_default) 

CodePudding user response:

Your logic needs to decide whether the value is empty, and then split if not. Unfortunately, this means your otherwise rather elegant or formulation won't work.

def split_or_default(prompt, default):
    response = input(prompt   " ("   "/".join(default)   ") ")
    if response == "":
        return default
    return response.split(",")

Brand = split_or_default(
    'Please enter Brand?',
    ['ABC','XYZ'])
Cate = split_or_default(
    'Please enter Category?',
    ['GKK','KKL','MKK','UKK'])

Notice also how the defaults are also lists now. I suppose your code could work with lists or tuples, but that seems like an unwelcome complication.

Tangentially, you should probably remove the "Please enter" part from the prompt. It's nice to be polite, but in user interfaces, it's actually more friendly to be concise.

Requiring commas between the values is also somewhat cumbersome. If some values could contain spaces, you need for the input to be unambiguous; but if these examples are representative, you could just as well split on whitespace.

In keeping with the DRY Principle I refactored the repeated code into a function.

  • Related