Python-if

Python中的switch

>>> choice = 'ham'

>>> print({'spam': 1.25,

...     'ham': 1.99,          # A dictionary-based 'switch'

...     'eggs': 0.99,          # Use has_key or get for default

...     'bacon': 1.10}[choice])

1.99

>>> branch = {'spam': 1.25,

...       'ham': 1.99,

...       'eggs': 0.99}

>>> print(branch.get('spam', 'Bad choice'))

1.25

>>> print(branch.get('bacon', 'Bad choice'))

Bad choice

>>> choice = 'bacon'

>>> if choice in branch

...    print(branch[choice])

...  else:

...    print('Bad choice')

...

Bad choice

===========================================================

原文地址:https://www.cnblogs.com/yy-is-ing/p/3951784.html