This question already has answers here:
Global Variable in Python
(2 answers)
Closed 5 years ago.
I have a little python application, and declared at the top of the application a string called lastMsg, in a function, this string should be changed, but instead of changing the existing string, it creates a new string, how can I change the old string?
If I guessed correctly what you are trying to do (do share some code to further explain your answer):
You need to use the global keyword to specify you want to change the global variable.
myVar = "1"
def myFun():
global myVar
myVar = "2"
print(myVar)
myFun()
print(myVar)
Should print:
1
2
It's not quite clear what you're asking.
I think you mean this:
lastMsg = "some string"
def a_function():
lastMsg = "new value"
If so, you can change it using the global keyword:
lastMsg = "some string"
def a_function():
global lastMsg
lastMsg = "new value"
Related
This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
Closed 1 year ago.
another dynamic variable question, but different from other seen imho.
class MyClass:
myvarA="alfa"
myvarB="beta"
myvarC="gamma"
myobj=MyClass()
for var in ["A", "B", "C"]:
print("{}\n".format("myobj.myvar{}".format(var)))
My goal: print all attributes values in oneline using format myvar+variable as var name.
print in last line, prints "myobj.myvarA..B..C" instead of values
many thanks
You generally don't want to do that, you'll want to use a dict if you need "dynamic variable names".
Anyway, you can do this with getattr():
class MyClass:
myvarA = "alfa"
myvarB = "beta"
myvarC = "gamma"
myobj = MyClass()
for var in ["A", "B", "C"]:
var_name = f"myvar{var}"
print(getattr(myobj, var_name))
This question already has answers here:
Why isn't the 'global' keyword needed to access a global variable?
(11 answers)
Closed 2 years ago.
In Python, I was wondering something about defining a variable in a module which can be used by all functions in that module.
I know that if I define a variable outside function, I can access that variable in a function by introducing global
e.g : inside a module name gas.py
R = 8.314 # univsersal gas constant
def pressure(T, V, n):
global R
P = n*R*T/V
return P
def temperature(P,V,n):
global R
T = P*V/(R*n)
return T
But as you can see, I have to write global R inside each function.
Is there a way that I can access R without writing global R inside each function ?
For example :
R = 8.314 # univsersal gas constant
def pressure(T, V, n):
P = n*R*T/V
return P
def temperature(P,V,n):
T = P*V/(R*n)
return T
Thank you
In python, you can read the value of a global variable without declaring it global.
You only need the global declaration when you want to change the value of a global variable. So in your case, you can just delete the all global declarations.
No, in Python a global variables works in a different way compared to other programming languages.
If you want to access a variable contained outside a function, you can just call it like a regular variable, for example:
word = "hello"
def function():
print(word)
function()
Output: hello
If you want to edit a variable locally, but not globally, you have to reassign the variable inside the function, for example:
word = "hello"
def function():
word = "world"
print(word)
print(word)
Output: hello, because we reassigned the variable only inside the function, so the global value of the variable word is still hello
But, if we want to edit a global variable (such as in case 1) in a non-global scope (local scope) and we want to manipulate the value of that variable inside a function, we have to use the global declaration, for example:
word = "hello"
def function():
global word
word = "world"
function()
print(word)
Now the Output will be world.
This question already has answers here:
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Using global variables in a function
(25 answers)
Closed 2 years ago.
Hi Team is there a way to append string in python, I mean i need to declare the variable globally and append the strings together and write in my file without changing the variable name.
For Example
example_string = ''
def method1():
example_string = 'Value1'
def method2():
example_string = 'value2'
def method3():
example_string = 'value3'
print(example_string )
Now I want my the result to be printed as 'Value1 value2 value3', This is what im looking for can anyone help me on this.
Use global keyword to make changes to global variables in functions. Use += to append to a string.
example_string = ''
def method1():
global example_string
example_string += 'value1'
def method2():
global example_string
example_string += 'value2'
def method3():
global example_string
example_string += 'value3'
Note that in order to get this last string you need to call all three functions
method1()
method2()
method3()
print(example_string)
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
I'm trying to store the result of random.random into a variable like so:
import random
def randombb():
a = random.random()
print(a)
randombb()
How can I properly get a?
Generally, you return the value. Once you've done that, you can assign a name to the return value just like anything else:
def randombb():
return random.random()
a = randombb()
As a side note -- The python tutorial is really great for anyone looking to learn a thing or two about the basics of python. I'd highly recommend you check it out. Here is the section on functions: https://docs.python.org/2/tutorial/controlflow.html#defining-functions ...
You can make it a global variable if you don't want to return it. Try something like this
a = 0 #any value of your choice
def setavalue():
global a # need to declare when you want to change the value
a = random.random()
def printavalue():
print a # when reading no need to declare
setavalue()
printavalue()
print a
You can simply store the value of random.random() as you are doing to store in a, and after that you may return the value
import random
def randombb():
a = random.random()
print(a)
return a
x= randombb()
print(x)
This question already has answers here:
How can I access global variable inside class in Python
(6 answers)
Closed 8 years ago.
Right, so I'm making a program...
def aFunction():
aVariable = 5
aVariable = 9
aFunction()
...and of course this won't work. What I am trying to do is to make aVariable changeable in other functions, namely, aFunction. How do I do that? Can I use the global statement, I have heard some bad things about it, although I don't really remember why?
You should use global:
def aFunction():
global aVariable
aVariable = 5
aVariable = 9
aFunction()
print aVariable #print 5
So this is a comprehensive explanation why global variables are bad in every programming language: global variables are bad
For your problem, you can use return values, for example:
def a_function(a_variable):
return a_variable - 5
a_variable = 9
a_variable = a_function(a_variable)