Python的基础知识学习路线3—条件控制、循环语句、推导式、迭代器与生成器(使用jupyter notebook进行操作:最全路线,每部分附有代码操作结果)

一、条件控制:if-elif-else

形如:
if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
如果 "condition_1" 为False,将判断 "condition_2"
如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
如果 "condition_2" 为False,将执行"statement_block_3"块语句
注意:
1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在 Python 中没有 switch...case 语句,但在 Python3.10 版本添加了 match...case,功能也类似,详见下文。
例如1:
sums = 5
if sums>0 and sums<2:
    sums += 1
elif sums>=2 and sums<=4:
    sums += 2
else:
    sums +=3
print(f"sums = {sums}")
# 结果:sums = 8

例如2:
value1 = True
sums = 10
if value1:
    sums /= 2
else:
    sums += 5
print(f"sums = {sums}")
# 结果:sums = 5.0

例如3:
sums = 100
if sums != 100:
    sums += 1
elif sums>=200 and sums<=300:
    sums += 2
elif sums not in [1,2,3,4,5]:
    sums -=3
else:
    sums *=100
print(f"sums = {sums}")
# 结果:sums = 97

例如4:输入8
num=int(input("输入一个数字:"))
if num%2==0:
    if num%3==0:
        print ("你输入的数字可以整除 2 和 3")
    else:
        print ("你输入的数字可以整除 2,但不能整除 3")
else:
    if num%3==0:
        print ("你输入的数字可以整除 3,但不能整除 2")
    else:
        print  ("你输入的数字不能整除 2 和 3")
# 结果:你输入的数字可以整除 2,但不能整除 3

二、循环语句: for 与 while

1、for

例如1:
L1 = [1,2,3,4,5,6,7]
sums = 0
for i in L1:
    sums += i
    print(f"sums = {sums}")
结果:
sums = 1
sums = 3
sums = 6
sums = 10
sums = 15
sums = 21
sums = 28

例如2:
L1 = [1,2,3,4,5,6,7]
sums = 0
for i in L1:
    if i < 3:
        sums *= i
    elif i>=3 and i<=6:
        sums -= i
    else:
        sums += 7
    print(f"sums = {sums}")
结果:
sums = 0
sums = 0
sums = -3
sums = -7
sums = -12
sums = -18
sums = -11

例如3:
L1 = [1,2,3,4,5,6,7,1,2,3,4,5,6,8,9,10]
L2 = []
for i in L1:
    if i not in L2:
        L2.append(i)
    elif i>=3 and i<=6:
        L2.append(i+1)
    else:
        L2.append(i-1)
print(f"L2 = {L2}")
print(f"L2 = {list(set(L2))}")
结果:
L2 = [1, 2, 3, 4, 5, 6, 7, 0, 1, 4, 5, 6, 7, 8, 9, 10]
L2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

例如4:
L1 = [1,2,3,4,5]
L2 = [6,7,8,9,10]
sums = 0
L3 = []
for i in range(len(L1)):
    sums += L1[i]
    sums += L2[i]
    L3.append(L1[i])
    L3.append(L2[i])
print("sums = {}".format(sums))
print("L3 = {}".format(L3))
结果:
sums = 55
L3 = [1, 6, 2, 7, 3, 8, 4, 9, 5, 10]

例如5:
sums = 1
L1 = [1,2,3,4,5,6]
for i in L1:
    sums += i
else:
    sums -= sum(L1)
print(f"sums = {sums}")
结果:
sums = 1

2、while

例如1:
n = 100
sums = 0
counter = 1
while counter <= n:
    sums = sums + counter
    counter += 1
print("1 到 %d 之和为: %d" % (n,sums))

例如2:
var = 1
while var == 1 :  # 表达式永远为 true
    num = int(input("输入一个数字  :"))
    print ("你输入的数字是: ", num)
print ("Good bye!")

例如3:
sums = 1
while sums<10:
    sums *= 2
else:
    sums /= sums
print("sums = {}".format(sums))

例如4:
sums = 1
while sums<20:
    sums *= 2
    if(sums > 16):
        sums  = 66
        break
print("sums = {}".format(sums))

三、推导式

Python 推导式是一种独特的数据处理方式,可以从一个数据序列构建另一个新的数据序列的结构体。
Python 支持各种数据结构的推导式:
列表(list)推导式
字典(dict)推导式
集合(set)推导式
元组(tuple)推导式

列表推导式格式为:
[表达式 for 变量 in 列表] 
[out_exp_res for out_exp in input_list]
或者 
[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]
out_exp_res:列表生成元素表达式,可以是有返回值的函数。
for out_exp in input_list:迭代 input_list 将 out_exp 传入到 out_exp_res 表达式中。
if condition:条件语句,可以过滤列表中不符合条件的值。

字典推导式字典推导基本格式:
{ key_expr: value_expr for value in collection }{ key_expr: value_expr for value in collection if condition }

集合推导式集合推导式基本格式:
{ expression for item in Sequence }{ expression for item in Sequence if conditional }

元组推导式(生成器表达式)
元组推导式可以利用 range 区间、元组、列表、字典和集合等数据类型,快速生成一个满足指定需求的元组。
元组推导式基本格式:
(expression for item in Sequence )(expression for item in Sequence if conditional )
元组推导式和列表推导式的用法也完全相同,只是元组推导式是用 () 圆括号将各部分括起来,而列表推导式用的是中括号 [],另外元组推导式返回的结果是一个生成器对象。
例如1:
names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
new_names = [name.upper()for name in names if len(name)>3]
print(new_names)  # ['ALICE', 'JERRY', 'WENDY', 'SMITH']

例如2:
multiples = [i for i in range(30) if i % 3 == 0]
print(multiples) #[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

例如3:
listdemo = ['Google','Runoob', 'Taobao']
newdict = {key:len(key) for key in listdemo}
print(newdict)  # {'Google': 6, 'Runoob': 6, 'Taobao': 6}

例如4:
setnew = {i**2 for i in (1,2,3)}
print(setnew) #{1, 4, 9}

例如5:
a = (x for x in range(1,10))
tuple(a)       # 使用 tuple() 函数,可以直接将生成器对象转换成元组
(1, 2, 3, 4, 5, 6, 7, 8, 9)

四、迭代器与生成器

迭代器
迭代是 Python 最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter()next()。
字符串,列表或元组对象都可用于创建迭代器:

例如1:
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
print (next(it))   # 输出迭代器的下一个元素  #结果:1
print (next(it))   #结果:2

例如2:
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
for x in it:
    print (x, end=" ")  # 1234
生成器
在 Python 中,使用了 yield 的函数被称为生成器(generator)。

yield 是一个关键字,用于定义生成器函数,生成器函数是一种特殊的函数,可以在迭代过程中逐步产生值,而不是一次性返回所有结果。

跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。

当在生成器函数中使用 yield 语句时,函数的执行将会暂停,并将 yield 后面的表达式作为当前迭代的值返回。

然后,每次调用生成器的 next() 方法或使用 for 循环进行迭代时,函数会从上次暂停的地方继续执行,直到再次遇到 yield 语句。这样,生成器函数可以逐步产生值,而不需要一次性计算并返回所有结果。

调用一个生成器函数,返回的是一个迭代器对象。

下面是一个简单的示例,展示了生成器函数的使用:
def countdown(n):
    while n > 0:
        yield n
        n -= 1

# 创建生成器对象
generator = countdown(5)
 
# 通过迭代生成器获取值
print(next(generator))  # 输出: 5
print(next(generator))  # 输出: 4
print(next(generator))  # 输出: 3
 
# # 使用 for 循环迭代生成器
# for value in generator:
#     print(value)  # 输出: 2 1
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值