如何在一行中打印python给定的代码段

时间:2019-04-08 17:03:21

标签: python python-3.x

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

    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条件末尾的变量。

2 个答案:

答案 0 :(得分:2)

我认为您应该回顾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

答案 1 :(得分:0)

好吧,这是我的两分钱

ages = [5, 12, 19]

def get_age_status(age):
    return 'Kid' if age < 12 else 'Teenager' if age < 18 else 'Adult'

for age in ages:
    print(get_age_status(age))

输出:

Kid
Teenager
Adult