当我输入错误的输入但当我输入正确的输入时,我得到 None 。它没有出现。请帮我解决这个概念。
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!!")
Run Code Online (Sandbox Code Playgroud)
输出:
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!!
Run Code Online (Sandbox Code Playgroud)
Python 中的函数总是返回一些东西。如果您没有使用 明确指定返回值return ...,则默认情况下,您的函数将返回None。
如果你没有输入有效的输入,return你的函数的语句将不会被执行,所以order()返回None,它被打印为之后的字符串'None'。
您可以测试返回值:
choice = order()
if choice is not None:
print(choice, " will be ordered soon!!")
Run Code Online (Sandbox Code Playgroud)
以便在您没有做出有效选择的情况下不会打印。
但是您可能希望用户再试一次,直到他提交一个有效的选择:
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!!")
Run Code Online (Sandbox Code Playgroud)
示例输出:
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!!
Run Code Online (Sandbox Code Playgroud)