Python - Modify an input variable inside a function [duplicate] - python

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 3 years ago.
The following code:
def function(X):
X.upper()
if X == 'YES':
print ('success')
else:
print ('fail')
function('yes')
Produces:
fail
But this code:
def function2(X):
Y = X.upper()
if Y == 'YES':
print ('success')
else:
print ('fail')
function2('yes')
Gives me:
success
Why is this? I want to be able to edit my input variables within my functions. Is there a more efficient way to do this than copying variable values to new variables? I'm running Python 3.7.1.
Thanks!

Because "".upper() returns new string, it doesn't change the original. Strings are immutable in Python.

Related

Can you directly alter the value of a non-list argument passed to a function? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 13 days ago.
This snippet of python code
def changeValue(x):
x = 2*x
a = [1]
changeValue(a[0])
print(a[0])
Will print the result "1" when I would like it to print the result "2". Can this be done by only altering the function and no other part of the code? I know there are solutions like
def changeValue(x):
x[0] = 2*x[0]
a = [1]
changeValue(a)
or
def changeValue(x):
return 2*x
a = [1]
a[0] = changeValue(a[0])
I am wondering if the argument passed as-is can be treated as a pointer in some sense.
[edit] - Just found a relevant question here so this is likely a duplicate that can be closed.
No it's not possible. If you pass a[0], it's an int and it can't be mutated in any way.
If the int was directly in the global namespace, you could use global keyword. But it's not. So again no.

I want print paramater's name in a python function [duplicate]

This question already has answers here:
How to print actual name of variable class type in function?
(4 answers)
Getting the name of a variable as a string
(32 answers)
Closed 3 years ago.
I want print paramater's name in a python function
First, a variable is assigned a value.Then, pass the variable to a function.
Last,I want to print str(variable) inner the function.
varibale = 1234
def f(x):
print(....)
return
f(varibale)
Expected output is print out the 'varibale' whatever variable is.
if a = 1 ==> f(x), expected output is 'a';if b = 2 ==> f(x), expected output is 'b'.....
Why do you want to print out the value using a function?
If you know the name of the variable, you can simply write your requested function output yourself by just putting 'variable'
So in your example: instead of using f(x), just use print('x')

Regarding replace in string using .replace [duplicate]

This question already has answers here:
replace characters not working in python [duplicate]
(3 answers)
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 4 years ago.
I have tried to use .replace in python to replace an empty list in a string but it is not working. Could anyone please tell me how?
x = ['check-[]|man', 'check-[]|king']
for y in x:
if "[]" in y:
y.replace("[]", "o")
print(y)
The results gave me this despite using .replace:
check-[]|man
check-[]|king
y.replace returns a value.
You have to assign it back
y = y.replace("[]", "o")
You need to assign i back to variable y:
x = ['check-[]|man', 'check-[]|king']
for y in x:
if "[]" in y:
y=y.replace("[]", "o")
print(y)
Output:
check-o|man
check-o|king

Python function can modify list or dict outside but not string [duplicate]

This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
How do I pass a variable by reference?
(39 answers)
Closed 4 years ago.
Why Python function can modify list or dict but not a string outside:
this makes sense, because function create scope, so the setit function create new variable:
ttt = 'ttt'
def setit(it):
ttt = it
print(ttt)
def showit():
print(ttt)
if __name__ == "__main__":
setit("lsdfjlsjdf")
showit()
But how to explain this, the setit function can modify the list outside:
aaa = []
def setit(it):
ttt = it
aaa.append(it)
def showit():
print(aaa)
if __name__ == '__main__':
setit(123)
showit()
setit(234)
showit()
Because strings are immutable. You cannot edit strings, you can just create new strings.
Source: Python Docs
See also: Function calls in Python

Python calling function by string name from code [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
Here is what I would like to be able to do:
I have a file called functions, with lots of functions. The functions are all essentially the same, functionally speaking (i.e., they are all of the form: pandas.Dataframe -> pandas.Dataframe). Obviously, they do different things to the Dataframe, so in that sense they are different.
I'd like to be able to pass my main function a list of strings, which would be the actual function names in the module, and have my program translate the strings into function calls.
So, basically, instead of:
functions = [module.functionA, module.functionB, module.functionC]
x = g(functions)
print(x)
> 'magical happiness'
I would have:
function_strings = ['functionA','functionB','functionC']
functions = interpret_strings_as_function_calls(module,function_strings)
x = g(functions)
print(x)
> 'magical happiness'
Is there a way to do this? Or do I need to write a function in the module that matches each string with it's corresponding function? i.e.:
def interpret_strings(function_string):
if function_string == 'functionA':
return module.functionA
elif function_string == 'functionB':
return module.functionB
etc.
(or in a switch statement, or whatever)
You can use getattr(module, function_string).

Categories