Inputs and user input validation
Question:
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
Answers:
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
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.
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)
import java.util.Scanner;
import java.util.InputMismatchException;
import java.lang.Throwable;
public class Paint1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Throwable();
}
} catch(InputMismatchException e) {
scnr.next(); // cleared the bad value from the scanner
System.out.println("Please enter a valid input of a number. No alphabet characters.");
} catch(Throwable t) {
System.out.println("Please enter a positive number greater than 0.");
}
} while (wallHeight <= 0);
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's width
do {
try {
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
if (wallWidth <= 0) {
throw new Throwable();
}
} catch(InputMismatchException e) {
scnr.next(); // clear the bad value from the scanner
System.out.println("Please enter a valid input of a number. No alphabet characters.");
} catch(Throwable t) {
System.out.println("Please enter a positive number greater than 0.");
}
} while (wallWidth <= 0);
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println("Wall area: " + wallArea + " square feet");
// Calculate and output the amount of paint (in gallons) needed to paint the wall
gallonsPaintNeeded = wallArea/squareFeetPerGallons;
System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
//This was an interesting assignment, was able to get direction and assistance with this.
}
}
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
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
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 withraw_input
; - changed use of
input
in favor ofraw_input
designed for that purpose ; - if the string is invalid, it throws a
ValueError
at the time of theint()
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.
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)
import java.util.Scanner;
import java.util.InputMismatchException;
import java.lang.Throwable;
public class Paint1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
try {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
throw new Throwable();
}
} catch(InputMismatchException e) {
scnr.next(); // cleared the bad value from the scanner
System.out.println("Please enter a valid input of a number. No alphabet characters.");
} catch(Throwable t) {
System.out.println("Please enter a positive number greater than 0.");
}
} while (wallHeight <= 0);
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's width
do {
try {
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
if (wallWidth <= 0) {
throw new Throwable();
}
} catch(InputMismatchException e) {
scnr.next(); // clear the bad value from the scanner
System.out.println("Please enter a valid input of a number. No alphabet characters.");
} catch(Throwable t) {
System.out.println("Please enter a positive number greater than 0.");
}
} while (wallWidth <= 0);
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println("Wall area: " + wallArea + " square feet");
// Calculate and output the amount of paint (in gallons) needed to paint the wall
gallonsPaintNeeded = wallArea/squareFeetPerGallons;
System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
//This was an interesting assignment, was able to get direction and assistance with this.
}
}