你需要比较
type
属于
text
到
float
. 要做到这一点,保持你原来的逻辑,一种方法是:
# 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
循环需要在以下情况下包含break子句
test()
返回:
# 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())