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
===========================================================
时间: 2024-10-03 17:50:23