条件与循环

一、条件语句

if id == 0:

    print('red')

elif id == 1:

    print('yellow')

else:

    print('green') 

注意:if语句是可以单独使用的,但elif、else都必须和if成对使用;

  if条件语句的判断,除了boolean类型外,其他的最好显性显示出来;

二、循环语句

1、本质上就是遍历集合中的元素,python中的循环一般是通过for和while循环实现。

 

d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}

for k in d: # 遍历字典的键

    print(k)

name

dob

gender

 

for v in d.values(): # 遍历字典的值

    print(v)

jason

2000-01-01

male   

 

for k, v in d.items(): # 遍历字典的键值对

    print('key: {}, value: {}'.format(k, v))

key: name, value: jason

key: dob, value: 2000-01-01

key: gender, value: male

2、通常也使用range()函数,通过索引来遍历集合中的元素。

l = [1, 2, 3, 4, 5, 6, 7]

for index in range(0, len(l)):

    if index < 5:

        print(l[index])       

       

1

2

3

4

5

3、当同时需要访问索引和元素时,也可使用python的内置函数enumerate()。用它来遍历集合,不仅返回每个元素,并且还返回其对应的索引。

 

l = [1, 2, 3, 4, 5, 6, 7]

for index, item in enumerate(l):

    if index < 5:

        print(item) 

             

1

2

3

4

5

循环语句中通常使用continue和break一起使用。continue就是让程序跳过当前这层循环,继续执行下面的循环;而break则是指完全跳出所在的整个循环体;

4、while循环,当条件满足时会一直重复循环内部的操作,直到continue不再满足,就跳出处循环体。

三、条件和循环的复用

expression1 if condition else expression2 for item in iterable

将这个表达式拆解开来,其实就等同于下面这样的嵌套结构:

for item in iterable:

    if condition:

        expression1

    else:

        expression2

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值