天池Python练习03-条件语句 循环语句

目录

1 条件语句

1.1  if语句

1.2 if-else 语句

1.3 if-elif-else 语句

1.4 assert 关键词

2 循环语句

2.1 while循环

2.2 while-else 循环

2.3 for循环

2.4 for-else 循环

2.5 range()函数

2.6 enumerate()函数

2.7 break语言

2.9 pass语句

2.10 推导式


1 条件语句

1.1  if语句

if A :
    B

        只有当代码块A为真时B才执行 条件表达式A可以通过布尔操作符and or not 实现多重条件判断。

if 2>1 and not 2>3 :
    print('Yes')
>>>Yes

1.2 if-else 语句

if A :
    B
else :
    C

        如果条件标识结果布尔值为假 那么执行else后的语句。

if 3>4 :
    print('yes')
else:
    print('no')
>>>no

        if语句支持嵌套 在一个if中可以嵌入另一个if语句。

h=6
if h>0 :
    if h>9 :
        print('big')
else:
    print('small')
>>>

1.3 if-elif-else 语句

if A :
    B
elif C :
    D
else :
    D

        elif 既为else if 用来检查多个表达式是否为真。

1.4 assert 关键词

        assert 被称为“断言” 当这个关键词后条件为false时程序自动崩溃并抛出assertionerror异常。

my_list = ['gogogo']
my_list.pop(0)

assert len(my_list) >0 
>>>AssertionError

        在进行单元测试时, 可以用来在程序中放置检查点,只有条件为true才能让程序正常工作。

assert 3 > 7
>>>AssertionError

2 循环语句

2.1 while循环

while A :
    B

        while循环会一直循环直到表达式A为的值为布尔假。当输入一个非零整数时 视为真值;写入0时 视为假值 。

string = 'abcd'
while string :
    print(string)
    string = string[1:]
>>>
abcd
bcd
cd
d

2.2 while-else 循环

while A :
    B
else :
    D
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

2.3 for循环

        for循环是迭代循环 在python中相当于一个通用迭代器 可以遍历任何有序序列。如 str list tuple等 也可以遍历任何可迭代对象 如dict。

for i in 'ILoveYou' :
    print(i,end=" ")
    
dic ={'a':1,'b':2,'c':3,'d':4}
for key,value in dic.items() :
    print(key,value,sep=":",end=" ")
>>>I L o v e Y o u 
dic ={'a':1,'b':2,'c':3,'d':4}
for key,value in dic.items() :
    print(key,value,sep=":",end=" ")
>>>a:1 b:2 c:3 d:4 

2.4 for-else 循环

for 迭代对象 in 可迭代对象 :
    代码块
else :
    代码块

        当for循环正常执行完成的情况下,执行else输出,如果for循环中执行跳出循环语句。比如break 将不再执行else代码块中内容 与while-else一样。

for num in range(10,20) :
    for i in range(2,num) :
        if num%i == 0:
            j = num / i
            print('%d 等于 %d * %d' %(num,i,j))
            break
    else :
        print(num,'是一个质数')
>>>
10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数

2.5 range()函数

        range([start,]stop[,step=1])。
        函数有三个参数,方括号里为可选参数。
        step=1 表示步长默认是1。
        range的作用是生成一个从start开始到stop结束的数字序列,包含start 但是不包含stop。

for i in range(2,9) :
    print(i)
>>>
2
3
4
5
6
7
8

2.6 enumerate()函数

        enumerate(sequence,[start=0])。
        sequence 是一个序列、迭代器或者其他支持迭代的对象。
        start 是下标起始位置。
        返回 enumerate(枚举) 对象。

seasons =['Spring','Summer','Fall','Winter']
lis = list(enumerate(seasons))
print(lis)
lis = list(enumerate(seasons,start=1))
print(lis)
>>>[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

enumerate()与for循环结合使用

for i,a in enumerate(A) :
    do somethings with a

        用enumerate(A)不仅返回了A中元素,还顺表给该元素一个索引值。(默认从0开始) 此外,用enumerate(A,j)还可以确定索引起始值为j。

language=['Python','R','C++']
for i,language in enumerate(language,2) :
    print(i,'I Love',language)
print('Done!')
>>>
2 I Love Python
3 I Love R
4 I Love C++
Done!

2.7 break语言

        break语句可以跳出当前所在层的循环。

for i in range(10) :
    #print('%d :' %i)
    if i % 2 != 0 :
        print(i)
        continue
    i += 2
    print(i)
>>>2
1
4
3
6
5
8
7
10
9

2.9 pass语句

        pass语句意思是不做任何事,如果有需要写语句的地方不写任何语句,那么解释器会提示出错,可以用pass占位。如果暂时不确定写什么代码 可以先放置一个pass 让代码正常运行。

def afunc() :
    pass

2.10 推导式

列表推导式 [expr for value in collection[if condition]]

x=[-4,2,1,4]
y=[a * 2 for a in x]
print(y)
>>>[-8, 4, 2, 8]

x=[i ** 2 for i in range(1,10)]
print(x)
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81]
元组推导式 (expr for value in collection [if condition])

a=(x for x in range(10))
print(a)
>>><generator object <genexpr> at 0x0000021B4F06B890>

print(tuple(a))
>>>(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
字典推导式 {key_expr:value_expr for value in collection [if condition]}
b = {i:i % 2 ==0 for i in range(10) if i % 3 ==0}
print(b)
>>>{0: True, 3: False, 6: True, 9: False}
#集合推导式 {expr for value in collection [if condition]}
c = {i for i in [1,2,3,4,5,6,7,8,9]}
print(c)
>>>{1, 2, 3, 4, 5, 6, 7, 8, 9}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值