Posts: 2
Threads: 1
Joined: Aug 2018
Aug-25-2018, 02:33 PM
(This post was last modified: Aug-25-2018, 02:44 PM by buran.)
Hello,
My program :
1 2 3 4 |
variable = chocolate
number = 'variable'
print (number... ?)
|
And I want the answer of the program to be: "chocolate"
How can I do this ?
Thanks !
Posts: 8,169
Threads: 160
Joined: Sep 2016
you should use the quotes the other way round
1 2 |
variable = 'chocolate'
print (variable)
|
if you need to pass value from one variable to another
Posts: 1,150
Threads: 42
Joined: Sep 2016
Aug-25-2018, 02:48 PM
(This post was last modified: Aug-25-2018, 02:50 PM by j.crater.)
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.
1 2 3 4 |
variable = "chocolate"
number = variable
print (number)
|
Posts: 2
Threads: 1
Joined: Aug 2018
My entire code is :
1 2 3 |
variable = 'chocolate'
variable2 = 'chocolate2'
|
And if you want to read a variable :
Answer : chocolate2
How can I do this ?
Thanks
Posts: 4,804
Threads: 77
Joined: Jan 2018
Try answer = globals()[input()]
Posts: 8,169
Threads: 160
Joined: Sep 2016
Aug-25-2018, 03:53 PM
(This post was last modified: Aug-25-2018, 04:08 PM by buran.)
(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
1 2 |
myvars = { 'variable' : 'chocolate' , 'variable2' : 'chocolate2' }
print (myvars[ 'variable2' ])
|
1 2 |
myvars = { '1' : 'chocolate' , '2' : 'chocolate2' }
print (myvars[ '2' ])
|
or list, tuple
1 2 |
myvars = [ 'chocolate' , 'chocolate2' ]
print (myvars[ 0 ])
|
Posts: 7,324
Threads: 123
Joined: Sep 2016
Aug-25-2018, 04:05 PM
(This post was last modified: Aug-25-2018, 04:05 PM by snippsat.)
Now that @Grib has shown globals() (Python's internal dictionary),okay to show but can also mention better ways.
A ordinarily visible dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
λ 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.
Posts: 8,169
Threads: 160
Joined: Sep 2016
(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 :-)
|