首页 > 解决方案 > How to check if a string input has a certain letter and then list a variable that's attached to that letter?

问题描述

I'm doing a groklearning challenge and am currently stuck on this one question. Any help is appreciated!

This is the problem.

This is my current code:

order = input('Order: ')
for i in order:
  if 'h' in order:
    print('Ham')
    if 'p' in order:
      print('Pepperoni')
      if 'c' in order:
        print('Capsicum')
        if 'o' in order:
          print('Onion')
          if 'm' in order:
            print('Mushroom')
  else:
    print('MORE CHEESE!')

I have no idea where to begin or what to do. Thanks in advance! If the image link doesn't work please let me know.

标签: python

解决方案


Python 字典将是处理此问题的好方法。

toppings = {
    "h": "Ham",
    "p": "Pepperoni",
    "c": "Capsicum",
    "o": "Onion",
    "m": "Mushroom"}

然后使用字典的get方法为无法识别的键提供“更多奶酪”默认值:

for letter in input('Order: '):
    print toppings.get(letter, "MORE CHEESE!")

推荐阅读