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

如何在一行中打印python给定的代码段,python,python-3.x,Python,Python 3.x,我有一个内联的代码段,必须对其进行修改,以便它使用一个print语句 age=12 if age < 18: if age < 12: print('kid') else: print('teenager') else: print('adult') 年龄=12岁 如果年龄

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

    age=12
    if age < 18:
      if age < 12:
        print('kid')
      else:
        print('teenager')
    else:
      print('adult')
年龄=12岁
如果年龄<18岁:
如果年龄<12岁:
打印(‘孩子’)
其他:
打印(‘青少年’)
其他:
打印(‘成人’)
我试图通过在一条打印语句中加入if条件来解决这个问题,而不使用额外的变量

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

打印('kid')如果年龄那么你要的,这是我的两分钱:

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))

我认为您应该回顾一下python的主要理念。如果我们打开一个控制台并导入它,我们将看到:

"""
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!
"""
需要特别注意的是可读性计数。
扁平比嵌套好。
。如果只需要使用单个
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
年龄=12岁

如果你想解释为什么它必须在一行中?不。使用第一种方法。@Austin Which one?@DroidX86问题中提到使用一条打印语句,希望这有帮助。。是的,这是一个很好的方法,但我可以使用我上面提到的方法而不使用函数吗?在elif条件下,我将其改为范围(12,18)这是否符合python的理想?@tenoEschate我认为在这种情况下,您不希望创建range对象。这将为列出的数字返回一个生成器,即
12、13、14、15、16、17
(但不是作为列表!)。通常
range()
用于在
循环的每次迭代中为
定义一个变量,如
中为范围(12,18)
中的i定义的;
打印(i)
好了,我们可以使用我的策略道歉吗
=
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