【问题标题】:how to use isdigite for floats in python如何在python中使用isdigit进行浮点数
【发布时间】:2021-01-23 10:59:59
【问题描述】:

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

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

当我输入浮点数时,我得到“输入必须是数字”

【问题讨论】:

  • 这是因为浮点输入,即:3.0 不被视为完全数字,因为它包含 .
  • 这能回答你的问题吗? Using isdigit for floats?

标签: python python-3.x python-2.7 python-requests


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2016-10-10
    相关资源
    最近更新 更多