Python while循环从不结束(在numworks计算器上)

2024-10-02 22:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

刚刚抓到一个与python集成的计算器(numworks)。你知道吗

我正在编写一个python程序,其中包含一个函数来检查输入是否是一个数字(float)。你知道吗

当我键入一个正确的浮点数时,一切正常,但当捕捉到异常时,行为如下:

  • 块运行正常
  • 然后while循环重新启动,再次请求我的输入并输入infite循环并冻结。没时间再输入我的输入了。你知道吗

我不熟悉Python,我很确定这是一个简单的语法问题。。。但我没能解决。你知道吗

请帮忙!你知道吗

代码如下:

    # controle de saisie d'un nombre
    def inputFloat(text):
      ret = ''
      while ret is not float:
        try:
          ret = float(input(text + " (nombre)"))
        except ValueError:
          print("saisie incorrecte.")
      return ret

    # test
    def test():
      print(inputFloat("saisir nombre"))

    # affichage du menu
    while True:
      print("[1] test")
      print("[0] quitter")
      choix = input("Choisir une fonction:")
      if choix == "0":
        print("au revoir.")
        break
      elif choix == "1":
        test()

干杯

PS:关于环境的信息:计算器使用micropython1.9.4(源代码https://www.numworks.com/resources/manual/python/

编辑

这是干净的工作版本的代码与所有建议从你们。 把它推到计算器上:像个魔咒。你知道吗


    # controle de saisie d'un nombre
    def inputFloat(text):
      while True:
        try:
          return float(input(text + " (nombre)"))
        except ValueError:
          print("saisie incorrecte.")
          continue

    # test
    def test():
      print(inputFloat("saisir nombre"))

    # affichage du menu
    while True:
      print("[1] test")
      print("[0] quitter")
      choix = input("Choisir une fonction:")
      if choix == "0":
        print("au revoir.")
        break
      elif choix == "1":
        test()
        break


Tags: texttesttrueinputdeffloat计算器print
2条回答

您需要比较typetextfloat。要做到这一点,保持原有的逻辑,一种方法是:

# controle de saisie d'un nombre
def inputFloat(text):
    ret = ''
    while type(ret) != float:
        try:
            ret = float(input(text + " (nombre)"))
        except ValueError:
            print("saisie incorrecte.")
    return ret

或者,您可以使用:while not isinstance(ret, float)isinstance实际上是python中检查类型的首选方法)。你知道吗

正如@Iguananaut在注释中提到的,您可以通过同时删除ret变量来简化函数。你知道吗

def input_float():
    while True:
        try:
            return float(input("(nombre): "))
        except ValueError:
            print("saisie incorrecte.")

编辑

要使它与test函数和第二个while循环一起工作,需要在test()返回时包含break子句:

# affichage du menu
while True:
  print("[1] test")
  print("[0] quitter")
  choix = input("Choisir une fonction:")
  if choix == "0":
    print("au revoir.")
    break
  elif choix == "1":
    test()
    break

注意,如果您选择使用我建议的第二个函数(input_float),您将希望将测试函数更改为

# test
def test():
  print(input_float())

我认为最简单的方法是:

def input_float():
  while True:
    try:
      return float(input("Give us a number: "))
    except:
      print("This is not a number.")

也可以使用递归版本:

def input_float():
  try:
    return float(input("Give us a number: "))
  except:
    print("This is not a number.")
    return input_float()

相关问题 更多 >