Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Bit of help with Python


ghost's Avatar
0 0

Basically, I want to be able for a user to input a string that includes the variables in my script (which they will know) and for them to be able to affect the script: For example:

i = 1
raw_input("Enter what you want to do to the variable 'i': ")
# some code that allows them to change the i variable 
print i #the 'new' i

So if someone typed in i=i+5 or i= i*3 It would output 6 and 3..

Thanks in advance.


techb's Avatar
Member
0 0

You will want to use the exec() function.

i = 0

x = raw_input("type in i and its assignment:\n example: i += 5\n>")

exec(x)

print(i)

starofale's Avatar
Member
0 0

EDIT: Well techb's method is definitley a lot easier :P

The easiest way I can think of doing this is to use a regular expression to check if the string is of the correct form and then parse that string if the regex matches.

i = 1
str = raw_input("Enter what you want to do to the variable 'i': ")

# regular expression to match strings valid strings, e.g. "i=i+3" and "  i   =  4   / i   "
regex = re.match("[ ]*i[ ]*=[ ]*(i[ ]*[\+\-\*\/][ ]*[0-9]+|[0-9]+[ ]*[\+\-\*\/][ ]*i)[ ]*", str)
if regex:
    # get the individual parts of the string - operator, number, what order they were entered  (i-2 or 2-i)

    # could use regex:
    operator = re.search("[\+\-\*\/]", str).group(0)

    # or just iterate through string:
    for i in str:
        if i == "+" or i == "-" or i == "*" or i == "/":
            operator = i
    ...

ghost's Avatar
0 0

Thanks for your replies, I'm going to use eval() :)


techb's Avatar
Member
0 0

Note that eval only handles expressions, and exec only handles statements.

Check out this for better clarification.


ghost's Avatar
0 0

Thanks, I'll have a look and decide later. Thanks again :)