python知识点总结(二):for循环/ if语句

for 循环

1. 遍历整个列表

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中检查是否相等时区分大小写

例如,两个大小写不同的值会被视为不相等。
在这里插入图片描述

2. 要判断两个值是否不等,使用 !=

3. 条件语句中可包含各种数学比较

  如小于、小于等于、大于、大于等于

4. 检查多个条件(使用and和or)

age_0 >= 21 and age_1 >= 21
age_0 >= 21 or age_1 >= 21

5. 检查特定值是否包含在列表中(使用关键字in)

words = ['a','b','c','d']
'c' in words  #返回True
'x' in words  #返回False

6. 检查特定值是否不包含在列表中(使用关键字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') #列表是空的

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值