a=1
def choice():
if a==1 :
return 'more work to do '
b='cool'
else :
return 'more work to do '
b='not cool'
print (b)
all I want is to call it outside the function in another much longer code . this is the simple version. thanks a lot.
CodePudding user response:
You could make b
a global variable and use the global
keyword to modify it within choice
. But please don't.
>>> a = 1
>>> b = None
>>> def choice():
... global b
... if a == 1: b = "cool"
... else: b = "not cool"
...
>>> choice()
>>> b
'cool'
>>>
CodePudding user response:
As you've seen, b
is a local variable inside choice
and can't be referenced outside it. One option is to return the value from choice
:
def choice():
if a == 1:
return 'cool'
else:
return 'not cool'
b = choice()
print(b)
CodePudding user response:
There are 2 ways of achieving this. First of all you can just simply return b along with 'more work to do' like this:
a=1
def choice():
if a==1 :
b = 'cool'
return 'more work to do', b
else :
b = 'not cool'
return 'more work to do', b
moreWorkToDo, b = choice()
print (b)
Another way is to set b as a global variable however it is usually not advised. Global variables can be accessed and modified from anywhere in the code, which can make it difficult to trace the source of a bug. Anyways here is the code:
a=1
def choice():
global b
if a==1 :
b = 'cool'
return 'more work to do'
else :
b = 'not cool'
return 'more work to do'
moreWorkToDo = choice()
print (b)
CodePudding user response:
You can make b as a global variable to get it done for more info visit below thread Correct Use Of Global Variables In Python 3
a=1
def choice():
if a==1:
global b
b='cool'
return 'more work to do '
else :
b='not cool'
return 'more work to do '
print(choice())
print(b)