python基础(06控制语句)

python系列文章目录

python基础(01变量&数据类型&运算符)
python基础(02序列共性)
python基础(03列表和元组)
python基础(04字符串&字典)
python基础(05集合set)



前言

持续学习,争取早日退休!


一、语句块

缩进

二、bool类型:Ture、False

1、False:none、0、“”、()、[]、{}

>>> bool('')
False

2、true:1、其他

>>> bool('hello')
True

3、可以相加

>>> True + False + 42
43//false代表0  true 代表1

三、条件判断(if、else、elif)

1.if

a = int(input('pls enter the number:'))
if a > 2:
 print 'bigger than 2'

2.else

a = int(input('pls enter the number:'))
if a > 2:
 print 'bigger than 2'
else:
 print 'not bigger than 2'

3.elif

a = int(input('pls enter the number:'))
if a > 2:
 print 'bigger than 2'
elif a < 2:
 print 'not bigger than 2'
else:
 print 'a ==2'

4.嵌套语句块

name = input("pls enter the name:")
if name.endswith('z'):
 if name.startswith('m'):
 print 'hello m'
 elif name.startswith('l'):
 print 'hello l'
 else:
 print'z'
else:
 print 'hello stranger'

5.if-else新用法(类似三元运算符)

>>> a,b = 1,2
>>> c = 'more' if a>b else 'less'
>>> print(c)
less

------------------------------------------>>

>>> c = {True:'more',False:'less'}[a>b]
>>> c
'less'

6.运算符

x==y
x<y
x>y
x<=y
x>=y
x !=y
x is y
x is not y
x in y
x not in y
and
or
not:取反

四、循环语句

1.while循环

x = 0
while x <=100:
 print(x)
 x += 1

2.for循环(可以为一个可迭代对象的每一个元素执行一个语句块)

nums = [0,1,2,3,4,5,6,7,8,9]
for num in nums:
 print(num)

3.循环遍历字典元素

1、遍历键(默认)
d = {'x':1,'y':2,'z':3}
for key in d:
 print(key,'is',d[key])

    
2、遍历值
d = {'x':1,'y':2,'z':3,'a':11}
for value in d.values():
 print(value)

3、遍历键值
d = {'x':1,'y':2,'z':3,'a':11}
for key,value in d.items():
 print(key,value)

4.跳出循环

1break
2continue

5.for中的else语句

注意:for 能正常结束,或者 continue 也没事,都会执⾏ else 语句块,只有当for 循环 触发 break 了, else 不会执⾏

num='a','b','c'for i in num:
    print(1)
else:
    print("ccc")
----------------------------------->>
1
1
1
ccc
------------------------------------>>
num=['a','b','c']
for i in num:
    print(1)
    continue
else:
    print("ccc")
----------------------------------->>
1
1
1
ccc
-------------------------------------->>
num=['a','b','c']
for i in num:
    print(1)
    break
else:
    print("ccc")
---------------------------------------->>
1

五、推导式

1.列表推导式

代码如下(示例):

>>> c = [i+1 for i in a]
>>> c
[2, 3, 4]
--------------------------------
>>> d = [i+1 for i in a if i % 2 > 0]
>>> d
[2, 4]
------------------------------------
>>> def fun(i):
 return i*2
>>> e = [fun(i) for i in a if i % 2 > 0]
>>> e
[2, 6]

2.字典推导式

代码如下(示例):

a='anbxncbhdwgwjavcbdhjd'
b={i:a.count(i) for i in a}
print(b)

2.集合推导式

代码如下(示例):

print({x for x in range(1,100) if x%9==0})

总结

理解即可!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

佳佳不爱上班

送你一朵小红花,生活不必太焦虑

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值