Started by Gibson DavidsonNov 3, 2021

Open
Incrementing integer using variable name string

0 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWES SHARE

I'm doing the following in the python interpreter and it works:

rhce=rhcsa=0
args=['rhce,'rhcsa']
for cert in args:
    exec(cert+'+=1')
    print(eval(cert))
>>> 1
>>> 1

As you may see the variable is incremented, whether you use print(rhce) or print(eval(cert)). But, when I put the precise same snippet of code inner a class characteristic, it now does not work. No exceptions are thrown, however, the variable never increments. It's like the exec isn't running:

def addCertUser(self,userid,args):
    rhcsa=rhce=0
    print(args)
    try:
        for cert in args:
            exec(cert+'+=1')
            print(eval(cert))
    except for Exception as e:
        print(e)
>>> ['rhce', 'rhcsa']
>>> 0
>>> 0

0 Replies

You must be Logged in to reply
Techiio

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

facebooklinkdeintwitter

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Copyright techiio.com @2020 Kolkata, India
made with by Abhishek & Priyanka Jalan
Copyright techiio.com @2020
made with by Abhishek & Priyanka Jalan