python使用语句的常见陷阱

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

data=input("Pleaseenteraloudmessage(mustbeallcaps):")
whilenotdata.isupper():
print("Sorry,yourresponsewasnotloudenough.")
data=input("Pleaseenteraloudmessage(mustbeallcaps):")

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

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

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

defget_non_negative_int(prompt):
try:
value=int(input(prompt))
exceptValueError:
print("Sorry,Ididn'tunderstandthat.")
returnget_non_negative_int(prompt)

ifvalue<0:
print("Sorry,yourresponsemustnotbenegative.")
returnget_non_negative_int(prompt)
else:
returnvalue

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

以上就是python使用语句的常见陷阱,希望对大家有所帮助。更多Python学习指路:Python基础教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。