Ali
Ali

Reputation: 23

Can we make python take variables than strings from raw_input() builtin function?

I want to know if there is anyway I can have python raw_input() to procure a variable call for me.

what I understand is that, raw_input() takes whatever comments written in it and convert it to string, much like %r, it just prints everything in what I understand as a debugging mode string formatted.

but if we attempt to convert something like this:

test1 = int(raw_input("Please write some number:>  "))
print test1 * 100

and if we input 100, the next line will perform a calculation function on it, something I am very interested to implement but in this way:

This isn't a false attempt but to give a general idea of what I want

a = "I will like some candies"
b = "I will like some chocolates"
c = "I will rather die but have fried chicken" 
test2 = raw_input("Please write the variable name you want to print"

If this was the way python would take the inputs like, we will have a printed for example when the input was given as a and so on with b and c etc.

Is there a way in python to get the program to get an input from us in form of a variable than string. Any conversions?

Thank you all for your help in advance...

Upvotes: 2

Views: 48

Answers (2)

Apoorva Srivastava
Apoorva Srivastava

Reputation: 388

If it's a global variable, then you can do:

test1 = int(raw_input("Please write some number:>  "))
print test1 * 100

a = "I will like some candies"
b = "I will like some chocolates"
c = "I will rather die but have fried chicken"
test2 = raw_input("Please write the variable name you want to print ")
print globals()[test2]

If not, you'll have to specify the namespace of your variable.

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

No, As you said raw_input returns a string. If you you want to return a relevant result based on user input, the best way is using a dictionary for mapping your variable names to their values:

my_dict = {'a': "I will like some candies"
           'b': "I will like some chocolates"
           'c': "I will rather die but have fried chicken" }

test2 = raw_input("Please write the variable name you want to print"
warning = "Please choose one of the aforementioned choices (a, b, c)"
print my_dict.get(test2,warning)

Upvotes: 1

Related Questions