python基础(06控制语句)

python系列文章目录

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


文章目录

  • python系列文章目录
  • 前言
  • 一、语句块
  • 二、bool类型:Ture、False
  • 三、条件判断(if、else、elif)
  • 四、循环语句
  • 五、推导式
    • 1.列表推导式
    • 2.字典推导式
    • 2.集合推导式
  • 总结


前言

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


一、语句块

缩进

二、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})

总结

理解即可!

你可能感兴趣的:(python基础,python,开发语言,功能测试,自动化)