python使用语句的常见陷阱

422次阅读
没有评论

python使用语句的常见陷阱

1、冗余input语句的冗余使用,这种方法有效,但通常被认为是糟糕的风格。

data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
    print("Sorry, your response was not loud enough.")
    data = input("Please enter a loud message (must be all caps): ")

它最初可能看起来很有吸引力,因为它比while True方法短,但它违反了软件开发的不要重复自己的原则。这会增加系统中出现错误的可能性。如果你想向移植到2.7通过改变input来raw_input,却意外地只改变第一input上面?这SyntaxError只是等待发生。

2、递归会摧毁堆栈,用户输入无效数据的次数足够多会出错。

如果您刚刚了解了递归,您可能会想使用它get_non_negative_int来处理 while 循环。

def get_non_negative_int(prompt):
    try:
        value = int(input(prompt))
    except ValueError:
        print("Sorry, I didn't understand that.")
        return get_non_negative_int(prompt)
 
    if value < 0:
        print("Sorry, your response must not be negative.")
        return get_non_negative_int(prompt)
    else:
        return value

这在大多数情况下似乎工作正常,但如果用户输入无效数据的次数足够多,脚本将以RuntimeError: maximum recursion depth exceeded. 你可能认为“没有傻瓜会连续犯1000次错误”,但你低估了傻瓜的聪明才智!

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-04-08发表,共计914字。
新手QQ群:570568346,欢迎进群讨论 Python51学习