刚刚抓到一个与python集成的计算器(numworks)。你知道吗
我正在编写一个python程序,其中包含一个函数来检查输入是否是一个数字(float)。你知道吗
当我键入一个正确的浮点数时,一切正常,但当捕捉到异常时,行为如下:
我不熟悉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
您需要比较
type
的text
和float
。要做到这一点,保持原有的逻辑,一种方法是:或者,您可以使用:
while not isinstance(ret, float)
(isinstance
实际上是python中检查类型的首选方法)。你知道吗正如@Iguananaut在注释中提到的,您可以通过同时删除
ret
变量来简化函数。你知道吗编辑
要使它与
test
函数和第二个while
循环一起工作,需要在test()
返回时包含break子句:注意,如果您选择使用我建议的第二个函数(
input_float
),您将希望将测试函数更改为我认为最简单的方法是:
也可以使用递归版本:
相关问题 更多 >
编程相关推荐