1 问题
在python中我们常常使用到条件判断,if语句时常见的条件判断语句之一。那么如何使用if语句实现根据情况自动选择商品进行售卖呢?
2 方法
根据if语句执行时从上往下执行的特点,使用if语句、dict和list来实现整个流程**。**
代码清单 1
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| drinks = {'greentea':'please pay 4','weaktea':'please pay 5','blackcffee':'please pay 7','coffeewithmilk':'please pay 9','cocoa':'please pay 6'} drink = input('please input you wanted drink:') L=['greentea','weaktea','blackcffee','coffeewithmilk','cocoa'] if drink == l[0]: print( drinks['greentea']) elif drink == l[1]: print( drinks['weaktea']) elif drink == l[2]: print( drinks['blackcffee']) elif drink == l[3]: print( drinks['coffeewithmilk']) elif drink == l[4]: print( drinks['cocoa']) else: print('There is no drink you want') |
3 结语
针对用python实现自主售卖机问题,提出if语句的方法,通过运用if语句、dict和list实验,证明该方法是有效的,但本文的方法单一,可实现的成果简单单一,未来可以在此基础上扩展自主售卖机的功能。