- for 循环
- 1. 遍历整个列表
- if 语句
- 1. 在Python中检查是否相等时区分大小写
- 2. 要判断两个值是否不等,使用 !=
- 3. 条件语句中可包含各种数学比较
- 4. 检查多个条件(使用and和or)
- 5. 检查特定值是否包含在列表中(使用关键字in)
- 6. 检查特定值是否不包含在列表中(使用关键字not in)
- 7. if-elif-else 结构(需要考虑的情形超过两个)
- 8. 使用多个 elif 代码块
- 9. 使用 if 语句处理列表
words = ['a', 'b', 'c'] for i in words: #for循环内部语句需要缩进,for语句末尾的冒号表示下一行是循环的第一行 print(i) print(i.title() + ", that was a great trick!n") print("Thank you!") #此print属于for循环外
if 语句 1. 在Python中检查是否相等时区分大小写
例如,两个大小写不同的值会被视为不相等。
如小于、小于等于、大于、大于等于
4. 检查多个条件(使用and和or)age_0 >= 21 and age_1 >= 21 age_0 >= 21 or age_1 >= 215. 检查特定值是否包含在列表中(使用关键字in)
words = ['a','b','c','d'] 'c' in words #返回True 'x' in words #返回False6. 检查特定值是否不包含在列表中(使用关键字not in)
words = ['a','b','c','d'] user = 'y' if user not in words: print(user + ", error!") if-else 语句 age = 17 if age >= 18: print("You are old enough to vote!") else: print("Sorry, you are too young to vote.")7. if-elif-else 结构(需要考虑的情形超过两个)
例如一个根据年龄段收费的游乐场:4岁以下免费,4~18岁收费5美元,18岁(含)以上收费10美元。
age = 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.") #让代码更简洁 age = 12 if age < 4: price = 0 #设置门票价格 elif age < 18: price = 5 else: price = 10 print("Your admission cost is $" + str(price) + ".") #添加一条简单的print 语句8. 使用多个 elif 代码块
假设对于65岁(含)以上的老 人,可以半价(即5美元)购买门票
age = 68 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5 print("Your admission cost is $" + str(price) + ".")9. 使用 if 语句处理列表
foods = ['bread', 'milk', 'cheese','coffee'] foods_avaliable = ['bread', 'milk', 'cheese'] if foods: #确定列表不是空的 for food in foods: if food in foods_avaliable: #检查元素是否有效 if food == 'milk': #检查特殊元素 print("Sorry, we are out of milk right now.") else: print("Adding " + food + ".") else: print("Sorry, we don't have " + food + ".") #元素无效 print("Thank you!") else: print('ERROR') #列表是空的