Home > Enterprise >  How can I turn an empty input into a defined variable?
How can I turn an empty input into a defined variable?

Time:03-05

I am super new to python (code in general) I was working on some practice exercises for functions in python 3.

I know it is probably sloppy code and I will work on cleaning it up over my time learning.

def show_employee():
    name = input("Employee name:  ")
    salary = int(input("Employee salary:  "))
    default = 9000
    
    
    if salary <= 9000:
        return (f'{name}, {default}')
    elif len(salary) == 0:
        return (f'{name}, {default}')
    else:
        return (f'{name}, Salary: {salary}')

I continue to receive this error "invalid literal for int() with base 10: '' "

What I am trying to accomplish is simply if the user inputs a number 9000 or less, it returns their name and 9000. If they input anything over 9000, it returns their name and their input value. The part that is puzzling me is how can I get it so that if they do not input a salary value it will default itself to 9000?

Thanks for taking your time to help!

CodePudding user response:

The best time to do this is at the time you define salary. If you just want to handle the case of an empty string, you could do:

salary = int(input("Employee salary:  ") or 9000)

This works because x or y will evaluate to x if it's "truthy" and y if it's not -- hence thing = maybe_thing or default_thing is a handy way to assign a default_thing if maybe_thing is any "falsy" value (which includes an empty string).

If you wanted to replace any invalid input with 9000, a try/except would be more appropriate:

try:
    salary = int(input("Employee salary:  "))
except ValueError:
    salary = 9000

CodePudding user response:

Instead of transforming the input into an int right away:

salary = int(input("Employee salary:  "))

First check if the input is empty and transform into a string if you need:

salary = input("Employee salary:  ")
if not salary:  # Meaning, len(salary) == 0
    salary = default
else:
    salary = int(salary)
  • Related