-1

how to fix this code that i can input float number

x = 0
y = x
count = 0
while True:
    x = input("please enter student's grade: ")
    if x == "quit" or x == "exit":
        break
    if x.isdigit():
        x = float(x)
        if (x >= 0) and (x <= 20):
            y += x
            count += 1
            z = y / count
            print(f"your students average grade is {z}")
        else:
            print("please enter a number between 0 and 20")
    else:
        print("input must be number")

i got "input must be number" when i input a float number

Pasha
  • 1
  • 1
  • That is because the float input i.e: `3.0` is not considered fully numeric since it contains a `.` – Adam Jan 23 '21 at 11:07
  • 1
    Does this answer your question? [Using isdigit for floats?](https://stackoverflow.com/questions/4138202/using-isdigit-for-floats) – rfkortekaas Jan 23 '21 at 12:40

1 Answers1

1

You can simplify the code by using exception handling as following:

x = 0
y = x
count = 0
while True:
    x = input("please enter student's grade: ")
    if x == "quit" or x == "exit":
        break
    try:
      x = float(x)
      if (x >= 0) and (x <= 20):
         y += x
         count += 1
         z = y / count
         print(f"your students average grade is {z}")
      else:
         print("please enter a number between 0 and 20")
    except:    
      print("Enter a valid marks") 
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35