python培训之使用语句的常见陷阱

发布时间:2023-01-09 09:30:07 人气:105 作者:多测师

  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只是等待发生。

python培训之使用语句的常见陷阱

  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次错误”,但你低估了傻瓜的聪明才智!

  以上就是python使用语句的常见陷阱,希望对大家有所帮助。 更多Python学习指路:请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线