Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python “无”背后的概念是什么?_Python - Fatal编程技术网

Python “无”背后的概念是什么?

Python “无”背后的概念是什么?,python,Python,当我输入错误的输入,但当我输入正确的输入时,我没有得到任何结果。它没有出现。请帮我解决这个问题 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

当我输入错误的输入,但当我输入正确的输入时,我没有得到任何结果。它没有出现。请帮我解决这个问题

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!!

出现异常时,调用同一函数重试:

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.")

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!!

如果出现错误(例如,如果字符串作为输入提供),代码将转到
块,但
块没有返回值(
None
是默认返回值),因此如果输入不能转换为整数,则
选项
变量将为
None
,异常将被触发,并且没有返回值,因为它只显示一些消息。如果值不是有效的数字,您可以返回0。

不是向下投票者,我想原因是
“感谢选择我们的服务”
将被打印100次,如果用户在第100次输入正确的输入<代码>最后总是被执行。是的,是真的,没有考虑。我看到蒂埃里已经提供了一个更好的方法。