Python控制流( 判断 循环 )

控制流元素

条件

条件总是求值为一个布尔值, True False
代码块

1.缩进增加时, 代码块开始。
2.代码块可以包含其他代码块。
3.缩进减少为零, 或减少为外面包围代码块的缩进, 代码块就结束了。

控制流语句

条件判断

循环语句

if 判断

格式: ( 注意冒号 )

#    if
if name == 'Alice':
  print('Hi, Alice.')

#    if 加 else
if name == 'Alice':
  print('Hi, Alice.')
else:
  print('Hello, stranger.')

#    if  elif  else
if name == 'Alice':
  print('Hi, Alice.')
elif age < 12:
  print('You are not Alice, kiddo.')
else:
  print('You are neither Alice nor a little kid.')

 例子:

#!/usr/bin/env python
score = int(input("输入你的分数: "))

if score > 100:
    print("满分才100...")
elif score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 60:
    print("C")
else:
    print("E...没及格")

if嵌套

在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中

#!/usr/bin/env python
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")

while循环

1. 基本循环

while 条件:

     # 循环体         # 如果条件为真,那么循环体则执行  如果条件为假,那么循环体不执行

 2. 循环中止

  ① break    用于退出当前循环体结构

#!/usr/bin/env python
while True:
    print ('123')
    break
    print ("456")


[root@VM_0_15_centos py]# python while-1.py
123 

  ② continue    用于退出本次循环,继续下一次循环

#!/usr/bin/env python
count = 0
while count <= 10:
    count += 1
    if count > 3 and count < 9: #只要count在4-8之间,就跳过下面的print语句,直接进入下次循环
        continue
    print("loop ", count)
print("-- out of while loop --")


[root@VM_0_15_centos py]# python while-1.py
loop  1
loop  2
loop  3
loop  9
loop  10
loop  11
-- out of while loop --

  ③ exit()

 退出程序 

#!/usr/bin/env python
a=0
while True:
    a = a+1
    if a == 4:
        continue
    elif a < 8:
        print(a)
    elif a >7:
        exit()

[root@VM_0_15_centos learn]# python whileint.py
1
2
3
5
6
7

3. while ... else ...

与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句

while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else语句  --> 等到条件语句为 false 时执行 else 的语句块

#!/usr/bin/env python
count = 0
while count <= 5 :
    count += 1
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("--out of while loop --")

[root@VM_0_15_centos py]
# python while-else.py Loop 1 Loop 2 Loop 3 Loop 4 Loop 5 Loop 6 循环正常执行完啦 --out of while loop --

 如果执行过程中被break啦,就不会执行else的语句

#!/usr/bin/env python
count = 0
while count <= 5 :
    count += 1
    if count==3:break
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("--out of while loop --")

[root@VM_0_15_centos py]
# python while-else.py Loop 1 Loop 2 --out of while loop --

 for循环

Python  for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 按照顺序去循环可迭代对象的内容

格式

for <variable> in <sequence>:
    <statements>
else:
    <statements>

 for 栗子

#!/usr/bin/env python
msg = '好吧 python是个二狗子'
for item in msg:
    print(item)

li = ['abc','呵呵','egon',123]
for i in li:
    print(i)

dic = {'name':'哥哥','age':18,'sex':'man'}
for k,v in dic.items():
    print(k,v)


[root@VM_0_15_centos py]# python for.py 
好
吧
 
p
y
t
h
o
n
是
个
二
狗
子
abc
呵呵
egon
123
name 哥哥
age 18
sex man

for + else 栗子

#!/usr/bin/env python
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
    if site == "Runoob":
        print("菜鸟!")
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("End")


[root@VM_0_15_centos py]# python for-else.py
循环数据 Baidu
循环数据 Google
菜鸟!
循环数据 Runoob
循环数据 Taobao
没有循环数据!
End

for + break 语句,break 语句用于跳出当前循环体:

#!/usr/bin/env python
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
    if site == "Runoob":
        print("菜鸟!")
        break
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("End")


[root@VM_0_15_centos py]# python for-break.py 
循环数据 Baidu
循环数据 Google
菜鸟!
End

 enumerate:枚举,对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值. 为可迭代的对象添加序号

#!/usr/bin/env python
li = ['alex','女神','egon','太白',123]
for i in enumerate(li):
    print(i)
for i in enumerate(li,20):
    print(i)
for index,name in enumerate(li,1):
    print(index,name)
for index, name in enumerate(li, 10):  # 起始位置默认是0,可更改
    print(index,name)


[root@VM_0_15_centos py]# python enumerate.py 
(0, 'alex')
(1, '女神')
(2, 'egon')
(3, '太白')
(4, 123)
(20, 'alex')
(21, '女神')
(22, 'egon')
(23, '太白')
(24, 123)
1 alex
2 女神
3 egon
4 太白
5 123
10 alex
11 女神
12 egon
13 太白
14 123

range生成数列. 指定范围,生成指定数字。

#   生成数列
>>> for i in range(3):
...     print(i)
... 
0
1
2
#   也可以指定区间
>>> for i in range(3,8):
...     print(i)
... 
3
4
5
6
7
#   也可以指定数字开始并指定不同的增量(甚至可以是负数) 也叫做'步长'
>>> for i in range(3,17,3):      #指定步长值
...     print(i)
... 
3
6
9
12
15
>>> for i in range(3,17,-3):
...     print(i)
... 
>>> for i in range(30,17,-3):    #反向步长
...     print(i)
... 
30
27
24
21
18
>>> for i in range(-10, -100, -30) :   #负数   都是加步长的值
...     print(i)
... 
-10
-40
-70
#   结合range()和len()函数以遍历一个序列的索引
>>> a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)) :
...     print(i)
... 
0
1
2
3
4
>>> for i in range(len(a)) :
...     print(i,a[i])
... 
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
#   还可以使用range()函数来创建一个列表
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(3,7))
[3, 4, 5, 6]
>>> list(range(3,10,2))
[3, 5, 7, 9]

break和continue语句及循环中的else子句

#!/usr/bin/env python
for letter in 'Rool':     # 第一个实例
   if letter == 'o':        # 字母为 o 时跳过输出
      continue
   else: print ('当前字母 :', letter)
for letter in 'Rool':     # 和第一个实例基本相同
   if letter == 'o':        # 字母为 o 时跳过输出
      continue
   print ('当前字母 :', letter)
else: print('END')
for letter in 'Rool':     # break栗子
   if letter == 'o':        # 字母为 o 时退出循环
      break
   print ('当前字母 :', letter)
else: print('End')


[root@VM_0_15_centos py]# python else.py
当前字母 : R
当前字母 : l
当前字母 : R
当前字母 : l
END
当前字母 : R

pass 语句

Python pass是空语句,是为了保持程序结构的完整性。   pass 不做任何事情,一般用做占位语句

 

 

posted @ 2018-10-29 11:16  mingetty  阅读(148)  评论(0编辑  收藏  举报