1 request_foods=["tomato","beaf","milk"] 2 for elements in request_foods: 3 if elements=="beaf": 4 print("sorry for that beaf is out of") 5 else: 6 print("add "+elements+".") 7 print(" finished making your food.") 8 #-----------------------------------------------------
1 这段代码主要说明了 if 和for的结合使用,同时注意: for elements in request_foods:这种用法遍历列表中的元素,同样的可以用这种方法检查列表中的元素。在C语言中,如果进行遍历列表,实际上需要做一个查找的算法操作。充分体会Python在这一方面的优点
2 注意每一个逻辑块从属之前的 “:”,写程序不要忘了
1 foods=["beaf","tomato","patato"] 2 if foods: 3 for food in foods: 4 print("adding"+food+".") 5 print("this is your dinner") 6 else: 7 print("sorry for you!")
3 这段代码主要用来表明,遍历列表,如果列表为空,则会返回逻辑0,因此 if foods: 若foods为空,则不会执行,这其中则反映了Python这里面的便捷的思想