Search code examples
pythoninputraw-input

Inputs and user input validation


I have researched this question on here I have found similar question but this is different. I need to validate user input in the piece of code I am working on needs to print an error if the user input is either under 0 (This I have working fine) and print an error if the input is non-numeric here is where my problems are. If i use input rather than raw_input i get an error:

NameError name 'Whatever I type in' is not defined

What I tried so far:

Casting the variable as an integer and tried using the isNaN function but that failed miserably and finally going around the problem using ifs and elses. this is the code that works so far.

def pints_to_litres():
    pints = 0
    pints = input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")
    litres = pints * float(0.568261)
    litres = "%.2f" % litres
    print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)")
    if (pints < 0):
        print("Invalid Input! Try Again")
        pints_to_litres()

Thank you guys in advance


Solution

  • here I improved your code:

    def pints_to_litres():
        over = False
        while not over:
            try:
                pints = int(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>"))
                litres = pints * float(0.568261)
                print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)")
                if (pints < 0):
                    print("Invalid Input! Try Again")
                else:
                    over = True
            except ValueError:
                print("Invalid Input! Try Again")
    
    • useless setting of pints before overwriting it with raw_input ;
    • changed use of input in favor of raw_input designed for that purpose ;
    • if the string is invalid, it throws a ValueError at the time of the int() conversion of pints and loops again ;
    • if the value is too low, it loops again ;
    • As you can see, I also changed your recursive call to the function, as if the user always fails, you'll end up smashing the function stack limit, and have a failure.