当我输入错误的输入,但当我输入正确的输入时,我得不到任何提示。它不会出现。请帮助我解决这个概念。
def order():
try:
count = int(input("How many order ? "))
return count
except Exception as e:
print("Kindly enter in numbers")
print("Example :- 1, 2, 3, 4, 5 etc..")
finally:
print("Thanks to choose our service.")
choice = order()
print(choice, " will be ordered soon!!")输出:
How many order ? asdd
Kindly enter in numbers
Example :- 1, 2, 3, 4, 5 etc..
Thanks to choose our service.
None will be ordered soon!!发布于 2020-04-05 18:51:51
Python中的函数总是返回一些东西。如果你没有用return ...显式地指定返回值,你的函数将默认返回None。
如果您没有输入有效的输入,您的函数的return语句将不会被执行,因此order()返回None,然后将其输出为字符串'None'。
你可以测试返回值:
choice = order()
if choice is not None:
print(choice, " will be ordered soon!!")以便在您没有做出有效选择的情况下不会打印出来。
但您可能希望用户在提交有效选择之前重试:
def order():
while True:
try:
count = int(input("How many order ? "))
return count
except Exception as e:
print("Kindly enter in numbers")
print("Example :- 1, 2, 3, 4, 5 etc..")
choice = order()
print(choice, " will be ordered soon!!")示例输出:
How many order ? e
Kindly enter in numbers
Example :- 1, 2, 3, 4, 5 etc..
How many order ? r
Kindly enter in numbers
Example :- 1, 2, 3, 4, 5 etc..
How many order ? 4
4 will be ordered soon!!发布于 2020-04-05 18:51:03
在异常时,调用相同的函数以重试:
def order():
try:
count = int(input("How many order ? "))
return count
except Exception as e:
print("Kindly enter in numbers")
print("Example :- 1, 2, 3, 4, 5 etc..")
return order()
finally:
print("Thanks to choose our service.")发布于 2020-04-05 18:54:37
如果出现错误(例如,如果提供string作为输入),您的代码将转到没有返回值(None是默认返回值)的except块,这就是为什么您的choice变量将为None。
https://stackoverflow.com/questions/61041369
复制相似问题