我编写了一个函数,可以在 python 中将输出打印到屏幕上。我希望在调用函数时将打印语句作为返回值。
def printer:
print("Statement 1")
print("Statement 2")
....
代替上面的
def printer:
return x
print(printer())
答案 0 :(得分:1)
您需要通过变量打印语句并将其存储在列表中,有点像这样:
def printer():
printed_lines = []
line = "Statement 1"
print(line)
printed_lines.append(line)
line = "Statement 2, etc"
print(line)
printed_lines.append(line)
return printed_lines