首页 > 解决方案 > 如何在一行中打印给定的python代码片段

问题描述

我有一个内联代码片段,必须对其进行修改,以便它使用一个打印语句。

    age=12
    if age < 18:
      if age < 12:
        print('kid')
      else:
        print('teenager')
    else:
      print('adult')

我试图通过将 if 条件放在单个打印语句中而不使用额外变量来解决这个问题。

    age=12
    print('kid' if age<18 and age<12 else 'teenager' if age<18 and age>=12 else 'adult')

修改后的代码片段的结果与原始代码片段的结果相同,但想根据问题确认它是否正确,或者我应该使用额外的变量并存储每个 if 语句的结果并将变量打印在if 条件结束。

标签: pythonpython-3.x

解决方案


我认为你应该回顾一下 python 的主要理念。如果我们打开一个控制台,import this我们将看到:

"""
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""

特别注意的地方是Readability counts.Flat is better than nested.。如果您只需要使用一个,print()那么您应该使用一个变量来保留结果,然后只打印该变量。这将保持代码的可读性。就像是:

age=12
if age <= 12:
    stage_of_life = 'kid'
elif 12 < age < 18:
    stage_of_life = 'teenager'
else:
    stage_of_life = 'adult'

print(stage_of_life) # only one print statement in code

推荐阅读