如何将 isdigit 用于 python 中的浮点数

how to use isdigite for floats in python

如何修复我可以输入浮点数的代码

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")

当我输入浮点数时出现“输入必须是数字”

您可以使用异常处理来简化代码,如下所示:

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")