您的位置:首页 > 编程语言 > Python开发

Python流程控制

2016-05-22 20:59 417 查看
本节所讲内容:
Python 流程控制语句的使用
 
python中比较运算符的使用
x == y                     x 等于 y
x < y                     x 小于 y
x > y                     x 大于 y
x >= y
                     x 大于等于 y

x <= y
                     x 小于等于 y

x != y                     x 不等于 y
x is y                     x 和 y 是同一个对象
x is not y
              x 和 y 是不同的对象

x in y                     x 是 y 容器(例如,序列)的成员
x not in y              x 不是 y 容器(例如,序列)的成员
 
注:如果偶然遇见 x <> y 这样的表达式,它的意思其实就是 x!= y ,不建议使用 <> 运算符,应该尽量避免使用它。
 
在Python 中比较运算和赋值运算一样是可以是可以连接的——几个运算符可以连接在一起使用,比如:0<num<100,判断变量num的范围为0到100
 
1)相等运算符
>>> 'rm' == 'RM'
False
>>> 'rm' == 'rm'
True
>>> 'rm' != 'rm'
False
 
2)大小运算符
>>> 2 > 3
False
>>> 2 <= 3
True
>>> 3 >= 3
True
 
3)同一性运算
>>> x = y = [1,2,3]
>>> a = [1,2,3]
>>> x is a
False
 
主要用来判断序列,字符串是不适用的。is 运算符是判断同一性而不是相等性。变量x和y都被绑定到同一个列表上,而变量z被绑定在另一个具有相同数值和顺序的列表上。它们的值可能相等,但是却不是同一个对象。
 
>>> 'P' in 'Python'
True
 
[root@localhost ~]# vim in.py
#!/usr/bin/env python
name = raw_input("What is your name? ")
 
if 's' in name:
  print "Your name contain the letter 's'."
else:
  print "Your name does not contain the letter 's'."
 
[root@localhost ~]# ./in.py
What is your name? suwukong
Your name contain the letter 's'.
[root@localhost ~]# ./in.py
What is your name? Zhubajie
Your name does not contain the letter 's'.
 
多条件运算
and              连接两个运算符都为真时返回为真,否者为假

or              连接两个运算符任一为真是返回为真,否者为假
not              取反
 
增量赋值
Python中没有使用shell的x=x+1,而是将表达式运算符放置在赋值运算符=的左边,写成x+=1。这种写法叫做增量赋值,对于*,/ , % ,等标准运算符都适用
>>> x = 2
>>> x += 1
>>> x *= 2
>>> x
6
 
>>> name = 'rm'
>>> name += 'mk'
>>> name *= 2
>>> name
 
if语句的使用
语法格式
if 条件测试语句:
       条件测试操作
 
>>> if name == 'rm':
... print "Hello,rm!!!"
...
Hello,rm!!!
 
2)双分支if语句
语法格式
if       条件测试语句1:
       条件测试操作1
else:
       条件测试操作2
 
#!/usr/bin/env python
name = raw_input("What is your name? ")
if name.endswith('rm'):
  print 'Hello,Mr.rm'
else:
  print 'Hello,stranger'
 
注:endswith 是字符串的一种方法,用来判断字符串是否以某个字符串结尾
执行结果:
[root@localhost ~]# ./if.sh
What is your name? rm
Hello,Mr.rm
[root@localhost ~]# ./if.sh
What is your name? mk
Hello,stranger
 
3)多分支if语句
语法格式
if       条件测试语句1:
       条件测试操作1
elif 条件测试语句2:
       条件测试操作2
……
else:
       默认执行的操作
 
例:判断数字的正负
#!/usr/bin/python
 
num = input("Enter a number: ")
 
if num > 0:
  print "The number is positive"
elif num < 0:
  print "The number is negative"
else:
  print "The number is zero"
 
4)if语句的嵌套
语法格式
if 条件测试1:
       if       条件测试语句:
              print       条件测试操作
       ……
else:
 
#!/usr/bin/env python
name = raw_input("What is your name? ")
if name.endswith('rm'):
  if name.startswith('Mr.'):
  print "Hello,Mr.rm"
  elif name.startswith('Mrs.'):
  print "Hello,Mrs.rm"
  else:
  print "Hello,rm"
else:
  print "Hello,stranger"
 
注:startswith是字符串的一种方法,用来判断字符串是否以某个字符串开头
 
while循环语句的使用
例:打印100以内的数字
>>> x = 1
>>> while x <= 100:
... print x
... x += 1
 
编写登录信息验证程序
#!/usr/bin/python
width = 80
title = "Welcome to Hero alliance"
len_width = len(title)
margin_width = (width - len_width - 2 ) // 2
 
print '*' * width
print '*' * margin_width + ' ' + title + ' ' + '*' * margin_width
print '*' * width
 
while True:
  input = raw_input("Please input your username: ")
  if input == 'RM':
  password = raw_input("Please input your password: ")
  p = '123'
  while password != p:
  print "Wrong password"
  password = raw_input("Please input your password again:")
  else:
  print title
  break
  else:
  print "Sorry, user %s not found" % input
 
 
注:在Python中while循环也可以使用else语句进行流程控制
 
for循环的使用
语法格式
for 变量名 in 列表:
       循环操作
 
>>> message = ['Good','morning','Sir']
>>> for word in message:
... print word
...
Good
morning
Sir
 
range 函数
用来定义一组数字,包含下限,不包含上限,例:range(1,5)代表从1到5(不包含5)
>>> range(1,5)
[1, 2, 3, 4]
 
range函数可以手动指定数字间的间隔
>>> range(1,10,2)                                          #代表从1到10,间隔2(不包含10)
[1, 3, 5, 7, 9]
其中上限可以省略
>>> range(5)
[0, 1, 2, 3, 4]
 
通常,for循环可以和range函数结合进行使用
#!/usr/bin/env python
round = [
  'first',
  'second',
  'third',
  'fourth',
  'fifth'
]
for i in range(5):
  print i
  i += 2
  print i
  num = i - 2
  print "The " + round[num] + " round end."
注:round[num] 这是序列的一种表示方式,后期会讲到
 
执行的结果:
[root@localhost ~]# python for_range.py
0
2
The first round end.
1
3
The second round end.
2
4
The third round end.
3
5
The fourth round end.
4
6
The fifth round end.
 
扩展:
shell 中创建一组数字的方法
[root@localhost ~]# seq 1 5
1
2
3
4
5
或者
[root@localhost ~]# echo {1..5}
1 2 3 4 5
 
跳出循环
break :跳出循环
continue :结束当前循环
 
>>> for i in range(1,10):
... if i == 3:
... print "Great,you get your lucky number,which is " + str(i)
... continue
... print "The number is : %d " % i
...
The number is : 1
The number is : 2
Great,you get your lucky number,which is 3
The number is : 4
The number is : 5
The number is : 6
The number is : 7
The number is : 8
The number is : 9
 
实战:通过字典创建一个查询公司内部员工信息的程序
 
#!/usr/bin/env python
people = {
  'MK':{
  'phone': '110120',
  'addr': 'HeBei'
  },
  'RM':{
  'phone': '119999',
  'addr': 'HeNan'
  },
  'Find':{
  'phone': '111111',
  'addr': 'SanDong'
  }
}
 
labels = {
  'phone':'phone number',
  'addr': 'address'
}
 
while True:
  name = raw_input('Name: ')
  while name in people:
  request = raw_input('Phone number (p) or address (a)?')
 
  if request == 'p' : key = 'phone'
  if request == 'a' : key = 'addr'
 
  print "%s's %s is %s." % (name,labels[key],people[name][key])

break
  else:
  YN = raw_input("The user does not exist,enter user name again?(Y/N)")
  if YN == 'N':
  print "Program is stopping!!!"
  break
  if YN == 'Y':
  continue
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: