简体   繁体   中英

Python execution certain steps in a function based on input

Currently, I have a function which includes steps that are common irrespective of the user input. But some steps need to be executed only for certain inputs. In the example below, (see if apples: do something).

What are other alternate, more optimized ways of accomplishing this, as opposed to entering a boolean input for every choice?

Eg:

choice = input("Select option: ")
if choice == "1":
   apple = True
   test_operation(user, apple, pear="")
elif choice == "2":
   pear = True
   test_operation(user, apple="", pear=pear)
elif choice == "3":
   test_operation(user, apple="", pear="")


def test_operation(user, apple, pear):

    if apple:
       do something
    if pear:
        do something else
    else:
        do both

    #Print results , common for all
    for category in operations:
        print(f"\n{category}")
        for task in operations[category]:
             print(f"{task}: {operations[category][task]}")

Why are you adding more unnecessary variables like apples,pear just pass the variable choice to the test_operation function then process further according to the choice

choice = int(input("select option"))
def test_operation(choice):
  if choice == 1:
     do you stuff 
  elif choice == 2:
     some other stuff
  else:
     do both
  common stuff

If I understand you correctly, you can create functions for each action. Then create a dictionary where the keys are the user input and the values are lists of actions

def do_apple():
    # Something
def do_pear():
    # Something else

actions = {"1": [do_apple],
           "2": [do_pear],
           "3": [do_apple, do_pear] }

def test_operation(user, all_actions):
    # Call each function
    for action in all_actions:
        action()
    ...

choice = input("Select option: ")
if choice in actions:
    test_operation(user, actions[choice])

Just pass the input and check it directly:

def test_operation(user, choice):
    if choice == "1":
        # do apples
    if choice == "2":
        # do pear
    if choice == "3":
        # do both

You could use a switch construct. Since there is no switch-statement in Python, you'll need a helper function to simulate it:

def switch(v): yield lambda *c: v in c

And you could write your code like this:

choice = input("Select option: ")

for case in switch(choice):
    if case("1","3"):
       # perform apple test
    if case("2","3"):
       # perform pear test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM