条件打印语句打印错误的消息

时间:2016-04-10 09:59:50

标签: python

以下是一个例子:

my_name_is_anna = True
my_name_is_david = not my_name_is_anna

self_introduction = "Hello, my name is " + ("Anna!" if my_name_is_anna else "David!")
print(self_introduction) # Prints "Hello, my name is Anna!"

my_name_is_anna = False
print(self_introduction) # Still prints "Hello, my name is Anna!"

my_name_is_anna设置为False后,我想要打印"Hello, my name is David!"。有没有简洁的方法没有创建一个单独的函数,如下所示?

def write_self_introduction(my_name_is_anna):
    return "Hello, my name is " + ("Anna!" if my_name_is_anna else "David!")

print(write_self_introduction(my_name_is_anna=True)) # Prints "Hello, my name is Anna!"
print(write_self_introduction(my_name_is_anna=False)) # Prints "Hello, my name is David!"

0 个答案:

没有答案