如何在不在控制台屏幕中显示打印功能的情况下将 return 键存储到变量?

How can i store return key to a variable without appearing print function in console screen?

def a():
    print("Hello World!")
    b = 1
    return b

c = a()

print(c)

我只想在控制台显示1window,但是字符串'Hello world'也出现了。我该如何解决这个问题?

def a(printing):
    if printing == True:
        print("Hello World!")
    b = 1
    return b

c = a(printing = False)

print(c)

非常感谢!我用参数解决了这个问题:)

你可以试试这个。

def a(printing=False):
    if printing:
        print("Hello World!")
    b = 1
    return b

c = a()

print(c)

# Print Hello World and 1
print_hello = a(printing=True)

print(print_hello)

或者您可以嵌套方法。

def a()
    return 1

def A():
    print("Hello World!")
    return a()

c = a()

print(c)

# To print hello world and 1
print_hello = A()

print(print_hello)

您也可以在方法的外部范围内使用变量,并在 运行 方法之前将其设置为 True/False。

如果没有某种额外的变量、参数或方法调用,我看不出有什么明显的方法可以做到这一点。所有这 3 种方法都允许您在没有任何参数的情况下调用 a() 并且不打印 Hello world!