user4956086
user4956086

Reputation:

How to print the variable user input in python 3?

So basically, I have a python program but there's a point in which I need help. When the user input the variable name, I want it to print the variable value, not the variable name, even if the variable doesn't exist. This is what I've currently got:

    CMD = input(">>>>  ")

    if CMD[0:17] == "console.printVar(" and CMD[-1:] == ")" and CMD[-2:]!="')":
    try:
        CMD[13:-1]
    except NameError:
        print("Variable "+CMD[13:1]+" Not defined")
        Main()
    else:
        print(CMD[17:-1])
        Main()

Oh, and just in case it's not clear, i'm sort of working on a coding language sort of thing.

Upvotes: 0

Views: 412

Answers (3)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

You can get the local (function's) scope as a dict with locals() and the global (module's) scope as a dict with globals(). Now you may want to read a bit more about parsing, AST etc...

Upvotes: 1

mkrieger1
mkrieger1

Reputation: 23139

To get the value of a global variable by name, use the globals() dictionary:

name = CMD[17:-1]
print(globals()[name])

Upvotes: 1

jsfan
jsfan

Reputation: 1373

You can just call eval(CMD[17:-1]).

However, this evaluates more than just variable names, so be careful that the user cannot do anything malicious with your code.

Upvotes: -1

Related Questions