Python Forum

Full Version: Problem with variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
My program :

variable = chocolate
number = 'variable'

print(number... ?)
And I want the answer of the program to be: "chocolate"

How can I do this ?

Thanks !
you should use the quotes the other way round
variable = 'chocolate'
print(variable)
if you need to pass value from one variable to another
new_variable = variable
Right now variable "thinks" chocolate is another variable. But you didn't define it anywhere, so it will get confused and you get an error.
If you want to store the string/text "chocolate" to variable you need to put it in quotes (double or single), like you did with variable. Text in quotes is a string, text without quotes is a variable name.

variable = "chocolate"
number = variable
 
print(number)
My entire code is :

variable = 'chocolate'
variable2 = 'chocolate2'
#variable3 = '.....
And if you want to read a variable :

enter = int(input())  #Answer variable2
Answer : chocolate2

How can I do this ?

Thanks
Try answer = globals()[input()]
(Aug-25-2018, 02:55 PM)Gribouillis Wrote: [ -> ]Try answer = globals()[input()]
I don't think it's good idea to show this to a newbie

@O_Pas_Sage: Please, read Why you don't want to dynamically create variables

use some sort of container, e.g.

dict

myvars = {'variable':'chocolate', 'variable2':'chocolate2'}
print(myvars['variable2'])
myvars = {'1':'chocolate', '2':'chocolate2'}
print(myvars['2'])
or list, tuple

myvars = ['chocolate', 'chocolate2']
print(myvars[0])
Now that @Grib has shown globals()(Python's internal dictionary),okay to show but can also mention better ways.
A ordinarily visible dictionary.
λ ptpython
>>> choco_store = dict(variable='chocolate', variable2='chocolate2')
>>> choco_store
{'variable': 'chocolate', 'variable2': 'chocolate2'}

>>> enter = choco_store.get(input('What chocolate: '), 'No chocolate for you')
What chocolate: variable2
>>> enter
'chocolate2'

>>> enter = choco_store.get(input('What chocolate: '), 'No chocolate for you')
What chocolate: Mars
>>> enter
'No chocolate for you'
Similar to @buran post,did something else for a while so did not see the post.
(Aug-25-2018, 04:05 PM)snippsat Wrote: [ -> ]Similar to @buran post,did something else for a while so did not see the post.
Yeah, it happens often to me too :-)