-1

Doing a very basic grade calculator, and I can't figure out how to code a specific input validity test. I want to test the input to make sure it is only numerical values, and not characters. I already have a single test to verify that the inputed value is within the specified numerical range, but it doesn't account for the possibility of letters.

# prompt user for input
x = float(input("Enter your score between 0.0 - 1.0"))
# test if input is within range
if x < 0.0 or x > 1:
    print("Not a valid score")
Nakura
  • 1
  • 1
  • 5
    Possible duplicate of [How do I check if a string is a number (float)?](https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float) – Idos Feb 17 '19 at 19:31

1 Answers1

2

The default data type for anything you pass into input() is a 'string'. Since you have explicitly converted the input value to 'float', what you can do here is wrap your float conversion in a try-except like so:

try:
  x = float(input("Enter your score between 0.0 - 1.0"))
  if x < 0.0 or x > 1:
    print("Not a valid score")
except ValueError as e:
  print("{}. Cannot convert to float".format(e.message))

This will print the error message if your input cannot be converted to type 'float'

user11075263
  • 41
  • 1
  • 4