-3

Defining a FUNCTION through which we pass a variable name and in return we get a new variable assigned with a user_inp value.

I Tried this :

def Uinp(variable):
    variable = eval(input(f'Enter {variable} value : '))
    return variable

#trying the function.
x.Uinp

#trying to call the function.
Uinp(x)

print(x)

But coudn't get the desired results..

iLuvLogix
  • 5,920
  • 3
  • 26
  • 43
  • please add more information. I believe 'x' is a class so move this function to its class and then you can access it. Pass the returned value to class variable – Aliasgher Nooruddin Nov 07 '20 at 06:48
  • 1
    Does this answer your question? [Using a string variable as a variable name](https://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name) – John Gordon Nov 07 '20 at 07:06

2 Answers2

0

I think you need this:

def Uinp(variable):
    variable = eval(input(f'Enter {variable} value : '))
    return variable

print(Uinp(x))

Divyessh
  • 2,540
  • 1
  • 7
  • 24
0

So it's worth knowing that you really should not do this. It is very unexpected and modification of the globals dict is going to lead to some very hard to debug errors for you or someone else.

HOWEVER, it's definitely possible. Modification of the globals dict is legal Python.

def my_function(var_name):
    """Please don't use this function it's actually Pandora's Box of bugs."""
    user_inp = input("Enter some value: ")
    globals()[var_name] = user_inp

Use it with:

>>> my_function("this_is_a_new_variable")
Enter some value: this is my value that I've entered

>>> print(this_is_a_new_variable)
this is my value that I've entered
Adam Smith
  • 52,157
  • 12
  • 73
  • 112