1

i have and old script in python, where in

if __name__ == '__main__': <br>

We call arguments of functions. And if it argument equals some string we should call function. Old code.

if sys.argv[1] == 'add':
    sys.exit(add(db, usr))
if sys.argv[1] == 'rem':
    sys.exit(rem(db, usr))
if sys.argv[1] == 'rmusr':
    sys.exit(rmusr(db, usr))

At the first time, i thought about "switch case", but how i find out, python does not have it. And i tried to loop and array. Can i use it on this ? Sorry, i started learn python, 2 hours ago. But it is very interesting, and i hope, that you can help me.

 actions = ['add','rem','rmusr']
    for a in actions:
    if sys.argv[1] == 'a':
        sys.exit(a(db, usr))

Is it correct ? How i find out, we should not call variables with "$". Please help.

1
  • The line if sys.argv[1] == 'a': compares the user input to the character a. I don't think this is what you want. Try removing the single quotes so that you compare argv[1] to the value of the variable a, not the character 'a'. Commented Apr 19, 2017 at 21:19

3 Answers 3

1

Use a dictionary:

actions = {'add': add, 'rem': rem, 'rmusr': rmusr}

try:
    sys.exit(actions[sys.argv[1]](db, usr))
except KeyError:
   pass
   # or whatever you need to do for an invalid action
Sign up to request clarification or add additional context in comments.

Comments

0

You can add the functions to the dictionary and then use the user-input string to retrieve the function:

actions = {
    'add': add,
    'rem': rem,
    'rmusr': rmusr,
}

action = sys.argv[1]

if action in actions:
    sys.exit(actions[action](db, usr))

2 Comments

but what about my way ? it should not work ? if i want to use loop ?
Your example mixes up the function variable (a) with a similar string ('a'): they're not the same. There's no need to add a loop, since the in operator in my example does all the checking you need.
0

your code could be right but there is a typo on it.

actions = ['add','rem','rmusr']
for a in actions:
    if sys.argv[1] == 'a':
        sys.exit(a(db, usr))

I think It's better using in:

actions = ['add','rem','rmusr']
if sys.argv[1] in actions:
    sys.exit(sys.argv[1](db, usr))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.