PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How can I turn an empty input into a defined variable?

 July 20, 2022     function, input, integer, python     No comments   

Issue

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!


Solution

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


Answered By - Samwise
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing