栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录
    • for 循环
      • 1. 遍历整个列表
    • if 语句
      • 1. 在Python中检查是否相等时区分大小写
      • 2. 要判断两个值是否不等,使用 !=
      • 3. 条件语句中可包含各种数学比较
      • 4. 检查多个条件(使用and和or)
      • 5. 检查特定值是否包含在列表中(使用关键字in)
      • 6. 检查特定值是否不包含在列表中(使用关键字not in)
      • 7. if-elif-else 结构(需要考虑的情形超过两个)
      • 8. 使用多个 elif 代码块
      • 9. 使用 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') #列表是空的

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1033001.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号