Task02:条件循环结构

if判断语句介绍

if语句是用来进行判断的,其使用格式如下:

if 条件成立:
        执行

举例:

age = 30
if age>=18:
	print "我已经成年了"
if-else的使用格式
if 条件:
        满足条件时要做的事情
else:
        不满足条件时要做的事情

举例:

age = 17
if age <= 18:
    print("我是小可爱")  
else:
    print("永远18岁")
elif的功能
 if xxx1:
        事情1
elif xxx2:
		事情2
elif xxx3:
		事情3

举例:

score = 77
if score >= 90 and score <= 100:
    print('本次考试,等级为A')
elif score >= 80 and score < 90:
    print('本次考试,等级为B')
elif score >= 70 and score < 80:
    print('本次考试,等级为C')
elif score >= 60 and score < 70:
    print('本次考试,等级为D')
elif score >= 0 and score < 60:
    print('本次考试,等级为E')
elif的功能

这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

assert 3 > 7
# AssertionError
循环结构
  1. while 循环
    while 条件:
    执行

举例:

i = 1
while i <= 5:
    j = 1
    while j <= i:
        print("*", end='')
        j += 1
    print("")
    i += 1
k = 5
while k <= 5:
    a = 1
    while a <= k:
        print("*", end='')
        a += 1
    print("")
    if k == 0:
        break
    k -= 1
   # 执行结果
*
**
***
****
*****
*****
****
***
**
*
  1. while - else 循环
    其实是顺序执行结构,执行完while循环执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。
count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = count + 1
else:
    print("%d is not less than 5" % count)

# 0 is  less than 5
# 1 is  less than 5
# 2 is  less than 5
# 3 is  less than 5
# 4 is  less than 5
# 5 is not less than 5
  1. for 循环
    迭代循环,可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict。
for 迭代变量 in 可迭代对象:
    代码块

range() 函数

range([start,] stop[, step=1])  # 从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。
for i in range(10):
    print("---%d---" % i)
# 执行结果:
# ---0---
# ---1---
# ---2---
# ---3---
# ---4---
# ---5---
# ---6---
# ---7---
# ---8---
# ---9---

  1. break continue 语句
    continue终止本轮循环并开始下一轮循环。 break 终止循环。
for j in range(10):
    if j == 5:
        break
    print("***%d***" % j)
print("_____________________________")
for k in range(10):
    if k == 5:
        continue
    print("^^^%d^^^" % k)
# 执行结果:
# ***0***
# ***1***
# ***2***
# ***3***
# ***4***
# _____________________________
# ^^^0^^^
# ^^^1^^^
# ^^^2^^^
# ^^^3^^^
# ^^^4^^^
# ^^^6^^^
# ^^^7^^^
# ^^^8^^^
# ^^^9^^^
  1. pass 语句
    空语句
推导式
  1. 列表推导式
[ expr for value in collection [if condition] ]
  1. 元组推导式
( expr for value in collection [if condition] )
  1. 字典推导式
{ key_expr: value_expr for value in collection [if condition] }
  1. 集合推导式
{ expr for value in collection [if condition] }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值