4.python的基础语法元素_控制流程

本文深入探讨了Python中的条件测试,包括比较运算符、非空判断、逻辑运算以及存在运算的使用。同时,详细讲解了if语句的单分支、双分支及多分支结构,以及for循环和while循环的应用,包括循环控制和嵌套循环的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#-*- coding: utf-8 -*-

print ("===========条件测试==========")
#比较运算
a = 10
b = 8
print (a>b) #大于
print (a<b) #小于
print (a >= b)#大于等于
print (a <= b)#小于等于
print (a==b)
print (a != b)
#非空判断
ls = [1]
if ls:   #数据结构不为空、变量不为0、None、False 则条件成立
    print("非空")
else:
    print("空的")

#逻辑运算 与 或 非
a = 10
b = 8
c = 12
print ((a > b)and(b > c)) #与
print ((a > b)or(b > c)) #或
print (not(a > b)) #非
#复合逻辑运算的优先级 非 >  与 > 或
print (True or True and False)
print ((True or True) and False)
#存在运算
#元素in 列表/字符串
cars = ["BYD","BMW","AUDI","TOYOTA"]
print ("BMW" in cars)
print ("BENZ" in cars)
#元素 not in 列表/字符串
print ("BMW" not in cars)
print ("BENZ" not in cars)



print ("===========分支结构 if语句===========")
#单分支
age = 8
if age > 7:
    print ("孩子,你该上学了")

#双分支
age = 18
if age > 22:
    print ("可以结婚啦")
else:
    print ("再等等")

#多分支
age = 38
if age < 7:
    print ("再玩两年泥巴")
elif age < 13:
    print ("孩子,你该上初中了")
elif age < 60:
    print ("大家都要工作")
else:
    print ("退休了")
#嵌套循环


print("=========for 循环=========")
# 循环流程 从可迭代对象中,每次取出一个元素,并进行相应对操作
#直接迭代 -- 列表[],元组(),集合{},字符串" "
graduates = ("李雷","韩梅梅","Jim")
for graduate in graduates:
    print ("Congratulation,"+graduate)
#变换迭代 -- 字典
students = {201901:'xiaoming',201902:'xiaohong',201903:'xiaoqiang'}
for k,v in students.items():
    print (k,v)
for student in students.keys():
    print (student)
#range()对象
res = []
for i in range(1000):
    res.append(i**2)
print (res[:5])

res = []
for i in range(1,10,2):
    res.append(i**2)
print (res)

#循环控制  break结束整个循环
product_scores = [89,90,99,70,67]
i = 0
for score in product_scores:
    if score < 75:
        i += 1
    if i == 2:
        print ("产品抽检不合格")
#continue 结束本次循环
product_scores = [89,90,99,70,67]
for i in range(len(product_scores)):
    if product_scores[i] >= 75:
        continue
    print ("第{0}个产品,分数为{1},不合格".format(i,product_scores[i]))
#for与else的配合
#如果for循环全部执行完毕,没有被break中止,则运行else块
product_scores = [89,90,99,70,67]
#如果低于75分的超过2个,则该组产品不合格
i = 0
for score in product_scores:
    if score < 75:
        i += 1
    if i == 2:
        print ("产品抽检不合格")
        break
else:
    print("产品抽检不合格")

print("===========无限循环  while循环=========")
i = 1
res = 0
while i < 5:
    res += i
    i += 1
print (res)




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值