I don't know how I can describe it on the title, but basically here is what I would like to describe in detail. This is an example of what I'm trying to do:
def test():
text = 'Hello World'
print(str(text))
test(),
print ("Function text is " text)
which I would like the last line to print out Function text is Hello World
, but it won't print out any way but showing NameError: name 'text' is not defined
. Any ideas?
CodePudding user response:
You should normally return
from a function. This is captured in b
.
def test():
text = 'Hello World'
return text
b = test()
print ("Function text is " b)
Shorter one:
def test():
return 'Hello World'
print ("Function text is " test())
CodePudding user response:
The variable text
is visible only within the test()
function. This means that if you refer to that variable outside of the test()
function an error is shown. In addition, the variable text
is already a string, so there is no need to write str(text)
. If you want to print Function text is Hello World
you have to do something like this:
def test():
text = 'Hello World'
return text
print("Function text is " test())
The function test()
returns the value of text
. Then, the print()
function prints Function text is
plus the value returned by test()
, i.e., Hello World
.