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)
Related
This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 1 year ago.
How to pass a variable for an f-string '=' debugging operator?
from datetime import datetime
def print_var(var):
print(str(datetime.now())[:19], end=' ')
print(f'{var = }')
test = 5
print_var(test)
I expect print_var(test) to print the variable name from outside the function, ie.
test = 5
Please refer to Python: Print a variable's name and value? for the context of the question.
In f-strings you need to put the variable that needs to be printed between accolades. Like this:
from datetime import datetime
def print_var(var):
print(str(datetime.now())[:19], end=' ')
print(f'var = {var}')
Running the test yields the following:
test = 5
print_var(test)
>>>2021-10-06 11:32:05 var = 5
This question already has answers here:
Call a function from a stored string in Python [duplicate]
(4 answers)
Closed 1 year ago.
I have scraped some strings from emails into a list. The strings correspond to the names of functions which I want to be able to call later. I cannot call them in their current form so is there a way of converting the list of strings into a list of functions that I can call?
For example:
a = ['SU', 'BT', 'PL']
str = 'sdf sghf sdfgdf SU agffg BL asu'
matches = [x for x in a if x in str]
print(matches)
returns:
['SU', 'BL']
But I cannot call functions SU and BL from this list given the format.
With this example:
def my_func1():
print("ONE")
def my_func2():
print("TWO")
You can try eval, but it's not a good practise: (explanation)
eval("my_func1")()
Or you can assign this function to a string equivalent (inside a dictionary), and run that:
my_func_dict = {
"my_func1": my_func1,
"my_func2": my_func2
}
my_func_dict["my_func1"]()
Both of these examples will print ONE.
Or closer to your example:
a = [my_func1, my_func2]
matches = [x for x in a if x.__name__ in str]
# matches now has two funcions inside, so you can run either:
matches[0]()
matches[1]()
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:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 2 years ago.
I have the following code:
var1='aaa'
var2='bbb'
debug(var1, var2)
I would like the debug function to print:
"var1=aaa var2=bbb"
My function currently looks like
def debug(thing1, thing2):
print(f"{thing1=} {thing2=}")
and outputs:
"thing1=aaa thing2=bbb"
I tried using locals() in the function as well but got the same output. I would like to have "var1" and "var2" in the output without hardcoding them in the print statement.
You need to come at this problem in a slightly different way.
As stated, there is no way for debug to know the variable names.
You need to supply that information:
>>> import pprint
>>> var1 = 'aaa'
>>> var2 = 'bbb'
>>> def debug(**kwargs):
... pprint.pprint(kwargs, width=20)
...
>>> debug(var1=var1, var2=var2)
{'var1': 'aaa',
'var2': 'bbb'}
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"