以下是一个例子:
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!"