Home > Net >  How to return default value in Python from no user input
How to return default value in Python from no user input

Time:01-14

I'm trying to have this return a default value of "stupid" if the user does not enter in their name, but I cannot get it to work. It just returns "Greetings " with no name.

def main(): name = input("What is your name? ") hello(name)

def hello(x ="stupid"): print("Greetings,", x)

main()

Expected output:

Greetings, Ryan

or

Greetings, stupid

CodePudding user response:

The function hello has a default value of "stupid" for the parameter x, which means that if no value is provided for x when the function is called, it will use "stupid" as the value for x. However, the way you have your code set up, the input for the name is being taken in the main function, not in the hello function. So, even if the user doesn't enter anything for their name, the input function will return an empty string, which is being passed as the argument for x when hello is called.

def main(): 
    name = input("What is your name? ")
    if not name:
        name = "stupid"
    hello(name)

def hello(x): 
    print("Greetings,", x)

main()

This way, if the user enters an empty string, the main function will pass "stupid" as the argument for hello, resulting in "Greetings, stupid" being printed. If the user enters a name, that name will be passed as the argument and "Greetings, [name]" will be printed.

CodePudding user response:

If by "does not enter in their name" you mean that the user simply presses Enter without typing anything else, then name would be an empty string, and you can check for that:

def hello(x):
    if not x:
        x = 'stupid'

    print('Greetings,', x)

or even shorter:

def hello(x):
    print('Greetings,', x or 'stupid')
  • Related