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

标签 python

<分区>

刚拿了一个集成了 python (numworks) 的计算器。

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

当我输入一个正确的 float 时,一切正常,但是当异常被捕获时,行为是:

  • except block 运行正常
  • 然后 while 循环重新开始,再次询问我的输入并进入无限循环并卡住。没有时间再次输入我的输入。

我不熟悉 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:关于环境的信息:计算器使用 MicroPython 1.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



最佳答案

我认为最简单的方法如下:

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

关于Python while 循环永不结束(在 numworks 计算器上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100837/

相关文章:

javascript - javascript中的 "has_key"相当于什么?

python - 如何在 Python/Matplotlib 中根据特征值和特征向量绘制椭圆?

python - Scrapy shell 在终端中不断返回无效语法

python 正则表达式匹配一个组或不匹配它

python - Pandas 可以推断 DataFrame 名称吗?

python - python-ldap 初始化时 httpd 上的段错误 (11)

python - OpenCV gving 错误 "ASSERT: "false“在文件 qasciikey.cpp,第 495 行”在多个窗口上

python - Pytorch中位数 - 这是错误还是我使用错误

python - Pandas 中的 Groupby、map 和 sum 导致 NaN

python - 如何使用 pandas groupby.filter 保留至少一个值小于 24 的组