If statement: a dictionary-based 'switch' : If « Language Basics « Python






If statement: a dictionary-based 'switch'

If statement: a dictionary-based 'switch'

choice = 'ham'
print {'spam':  1.25,         # a dictionary-based 'switch'
       'ham':   1.99,         # use has_key() or get() for default
       'eggs':  0.99,
        'bacon': 1.10}[choice]



if choice == 'spam':
     print 1.25
elif choice == 'ham':
     print 1.99
elif choice == 'eggs':
     print 0.99
elif choice == 'bacon':
     print 1.10
else:
     print 'Bad choice'

           
       








Related examples in the same category

1.Nested if statementNested if statement
2.if-else structureif-else structure
3.if-elif-else structureif-elif-else structure
4.if structureif structure
5.if Statements: if, elif and elseif Statements: if, elif and else
6.Boolean operation in ifBoolean operation in if
7.elif demoelif demo
8.if with elseif with else
9.Leap Year checkerLeap Year checker