python - 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 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 字典将是处理此问题的好方法。
toppings = {
"h": "Ham",
"p": "Pepperoni",
"c": "Capsicum",
"o": "Onion",
"m": "Mushroom"}
然后使用字典的get
方法为无法识别的键提供“更多奶酪”默认值:
for letter in input('Order: '):
print toppings.get(letter, "MORE CHEESE!")
推荐阅读
- php - 超时后调用 PHP 函数
- python - 通过python运行网络搜索?
- javascript - Facebook Graph API - 来自 Post 的具有不同操作值的广告洞察
- c# - Unity3D:如何通过脚本修改网格布局组组件
- turbine - Spring Boot 涡轮机
- sql-server - 自交叉应用表数据
- python-3.x - DataFrame 删除无用的列
- java - 对 Java 中的响应式 Web 编程感到困惑
- mysql - 如何在 MYSQL 中的多个表之间使用总和/计数进行复杂连接
- java - 如果不用于 DDL 生成,Hibernate @JoinColumn(nullable = false) 是否是多余的?