简体   繁体   中英

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 Peter Romaniuk

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.
pints = raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")
try:
     pints = float(pints)
except ValueError:
     print("Invalid Input! Try Again")
     pints_to_litres()

then continue with the code

try this:

try:
    pints = float(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>\n"))
    # Calculation ...
except ValueError:
    print "Error"

you can check if the input is a digit bu using .isdigit() try this

entry =raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")
        if (not( entry.isdigit())):
                print "not a number"
                pints_to_litres()
        else:
                 pints=(int)(entry)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM