Search code examples
pythoninputreturnuser-input

How return a value with the input function?


Hi guys I'm new to python. I've been trying to return a value with an input function to the return can anyone help me out?

def bike_wash(amount):
    print("Welcome to your bike wash")
    print("Please enter your desired wash")
    
    if (amount == 100):
        print("Thanks for choosing basic wash")
        print("Enjoy water wash with spray")

    if (amount == 200):
        print("Thanks for choosing Premium wash")
        print("Enjoy foam wash to the entire body")


amount = input()
bike_wash(amount)

Solution

  • The answer depends on which version of Python you're using.

    Python 3

    You can simply pass the result of input (a string) to int (a function which turns a string into an integer).

       amount = int(input("Enter a number"))
    

    Python 2

    The python2 equivalent (to the input function from python3) is raw_input

       amount = int(raw_input("Enter a number"))
    

    Additionally it might be helpful to make your own parse_input function:

    def parse_input(parser, prompt='', defaultValue=None):
        try:
            return parser(input(prompt))
        except ValueError:
            return defaultValue
    
    

    replace input with raw_input for python2

    Typical usage:

       amount = parse_input(int, "Enter a number", 0)