刚刚获得了一个与python集成的计算器(numworks)。
我正在编写一个python程序,其中包含一个函数来检查输入是否是数字(float)。
当我键入一个正确的浮点数时,一切正常,但当捕捉到异常时,以下是行为:
-
except块运行正常
-
然后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:infos关于环境:计算器使用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