1

There's a handy multiple-choice command case in bash which simplify the condition logic.

Suppose such a minial script:

    read -p "Enter selection [0-2]: " num
    if [[ $num =~ ^[0-2]$ ]]; then
        if [[ $num == 0 ]]; then 
            echo "num eq 0"
        fi
        if [[ $num == 1 ]]; then 
            echo "num eq 1"
        fi 
        if [[ $num == 2 ]]; then 
            echo "num eq 1" 
        fi 
    else
        echo "Invalid Entry." >&2
        exit 1
    fi

It could be refactored as

    read -p "Enter selection [0-2]: " num
    case $num in 
        0)  echo "num eq 0" ;;
        1)  echo "num eq 1" ;;
        2)  echo "num eq 2" ;;
        *)  echo "Invalid Entry." >&2
            exit 1 ;; 
    esac      

Python does not include multiple options builtins as case

    num=int(input( "Enter selection [0-2]: "))
    if num == 0:
        print( "num eq 0")
    elif num == 1:
        print( "num eq 1")
    elif num == 2:
        print( "num eq 2")
    else:
        print( "Invalid Entry.")

How to achieve such a logic in a case-like way with python?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 2
    What's wrong with `elif` here? Is there any actual problem you're trying to solve? – abarnert Apr 10 '18 at 05:35
  • 2
    For more complicated cases, the Pythonic solution is normally to use a dict mapping keys to objects or functions, like `d = {0: "num eq 0", 1: "num eq 1", 2: "num eq 2"}` and then `print(d.get(num, "Invalid Entry"))`. But for a simple case like this, `elif` is generally more readable. – abarnert Apr 10 '18 at 05:37

0 Answers0