bash中有一个方便的多项选择命令case
,简化了条件逻辑。
假设有这样一个小型脚本:
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
它可以重构为
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不包含内置的多个选项
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.")
如何使用python以类似案例的方式实现这样的逻辑?