第四章 Python运算符和流程控制

简介: 在第一章的时候讲解了运算操作符和赋值操作符,这章来学习下其他常用Python操作符。
在第一章的时候讲解了运算操作符和赋值操作符,这章来学习下其他常用操作符。
4.1 基本运算符
4.1.1 比较操作符
操作符
描述
示例
==
相等
>>> 1 == 1  True
!=
不相等
>>> 1 != 1 False
>
大于
>>> 2 > 1   True
<
小于
>>> 2 < 1  False
>=
大于等于
>>> 1 >= 1  True
<=
小于等于
>>> 1 <= 1  True
4.1.2 逻辑运算符
逻辑运算符常用于表达式判断。
操作符
描述
and
or
not
示例:
>>> a = "a"
>>> b = "b"
>>> a and b
'b'
>>> a or b
'a'
>>> a = ""
>>> b = "b"
>>> a and b
''
>>> a or b
'b'
and操作符判断表达式,如果a和b都为真,返回b的值,否则返回a的值。
or操作符也是判断表达式,如果a和b都为真,返回a的值,否则返回b的值。
类似于shell里的&&和||:[ 'a' == 'b' ] && echo no || echo yes
>>> a = ""
>>> if not a:   
...   print "yes"
... else:       
...   print "no"
...
yes
>>> a = "a"
>>> if not a:   
...   print "yes"
... else:
...   print "no"
...
no
not操作符用于布尔值(true和false)判断不为真,与if语句连用。上面是不为真用not,那为真时怎么弄呢?
>>> a = "a"
>>> if a:
...   print "yes"
... else:
...   print "no"
...
yes
>>> a = ""
>>> if a:
...   print "yes"
... else:
...   print "no"
...
no
4.1.3 成员运算符
操作符
描述
in
在对象里
not in 
不在对象里
示例:
>>> 'a' in 'abc'
True
>>> 'd' in 'abc'
False
>>> lst = ['a','b','c']
>>> 'a' in lst
True
>>> 'd' in lst
False

>>> 'a' not in 'abc'
False
>>> 'd' not in 'abc'   
True
>>> 'd' not in lst
True
4.1.4 标识运算符
操作符
描述
is
内存地址相等
is not 
内存地址不相等
示例:
>>> a = []
>>> b = []
>>> id(a)
139741563903296
>>> id(b)
139741563902144
>>> a is b
False
>>> a is not b
True
这里用到了id()函数,用于获取对象在内存的地址。
4.2 条件判断
   4.2.1 单分支
>>> a = 20
>>> if a < 18: 
...   print "no"
... else:
...   print "yes"
...
yes
   有时候一个简单的判断语句,感觉这样写麻烦,有没有一条命令搞定的。
   有的,简写if语句:
>>> a = 20
>>> result = ("yes" if a == 20 else "no")
>>> result
'yes'
>>> type(result)
<type 'str'>

# 有时会看到别人代码用中括号,意思把结果存储为一个列表
>>> result = ["yes" if a == 20 else "no"]
>>> result
['yes']
>>> type(result)
<type 'list'>
   4.2.2 多分支
>>> a = 20
>>> if a < 18:
...   print "no"
... elif a == 20:
...   print "yes"
... else:
...   print "other"
...
yes
   4.2.3 pass语句
     >>> a = 20
>>> if a < 18:
...   print "no"
... elif a == 20:
...   pass
... else:
...   print "other"
...
   pass语句作用是不执行当前代码块,与shell中的冒号做作用一样。

博客地址:http://lizhenliang.blog.51cto.com and https://yq.aliyun.com/u/lizhenliang
QQ群:323779636(Shell/Python运维开发群)

4.3 循环语句
   4.3.1 for
     1)迭代对象
       遍历字符串,每个字符当做单个遍历:
>>> for i in "abc":
...   print i
...
a
b
c
       使用range()函数生成一个数字序列列表,并遍历:
>>> for i in range(1,5):
...   print i
...
1
2
3
4
       回顾下第三章讲的遍历字典:
>>> d = {'a':1, 'b':2, 'c':3}
>>> for i in d.iteritems():
...   print "%s:%s" %(i[0],i[1])
...
a:1
c:3
b:2
      2)嵌套循环
        逐个循环判断外层列表里元素是否存在内层列表:
>>> for i in range(1,6):
...   for x in range(3,8):
...     if i == x:
...       print i
...
3
4
5
      3)简写语句
        简写for语句:
>>> result = (x for x in range(5))
>>> result
<generator object <genexpr> at 0x030A4FD0>
>>> type(result)
<type 'generator'>
说明:在这里用小括号,会生成一个生成器,在这里知道下就可以了,不过多讲解,后面会专门生成器用途。

# 同样用中括号会以列表存储
>>> result = [ x for x in range(5)]
>>> type(result)
<type 'list'>
>>> result
[0, 1, 2, 3, 4]
       for和if语句写一行:
>>> result = [ x for x in range(5) if x % 2 == 0]
>>> result
[0, 2, 4]
   4.3.2 while
    语法:
    while 表达式:
        执行语句...
       1)输出序列
         当条件满足时,停止循环:
>>> while count < 5:
...   print count   
...   count += 1   
...
0
1
2
3
4
       2)死循环
>>> import time
>>> i = 1
>>> while True:     
...   print i       
...   i += 1         
...   time.sleep(0.5)
...
1
2
3
......   # 会一直循环,直到海枯石烂,天荒地老...
       注意:当表达式值为true或者非零时,都会一直循环。
   4.3.3 continue和break语句
   continue当满足条件时,跳出本次循环。
   break当满足条件时,跳出所有循环。
   for和while用法一样。
      1)基本使用
       满足条件跳出当前循环:
#!/usr/bin/env python
for i in range(1,6):
    if i == 3:
        continue
    else:
        print i
# python test.py
1
2
4
5

#!/usr/bin/env python
count = 0
while count < 5:
    count += 1
    if count == 3:
        continue
    else:
        print count
# python test.py
1
2
4
5
       满足条件终止循环:
#!/usr/bin/env python
for i in range(1,6):
    if i == 3:
        break
    else:
        print i
# python test.py
1
2

#!/usr/bin/env python
count = 0
while count < 5:
    count += 1
    if count == 3:
        break
    else:
        print count
# python test.py
1
2
      2)输入错误次数超过三次退出
       例如:提示用户输入名字,如果名字是xiaoming输入正确退出,否则一直提示重新输入,直到三次退出。
#!/usr/bin/env python
count = 0
while 1:
    if count < 3:
        name = raw_input("Please input your name: ").strip()    # .strip()去除首尾空格
        if len(name) == 0:
            print "Input can not be empty!"
            count += 1
            continue
        elif name == "xiaoming":
            print "OK."
            break
        else:
            print "Name input error, please input again!"
            count += 1
    else:
        print "Error three times, Exit!"
        break
   4.3.4 else语句
      else语句会在循环正常执行完才执行。 在for循环用法也一样。
>>> count = 0   
>>> while count < 5:
...   print count
...   count += 1
... else:
...   print "end"
...
0
1
2
3
4
end

>>> count = 0       
>>> while count < 5:
...   print count   
...   break
... else:
...   print "end"
...
0
目录
相关文章
|
7天前
|
Python
python一元运算符的应用
【4月更文挑战第12天】Python的一元运算符包括正号(+), 负号(-), 按位取反(~), 取绝对值(abs())和类型转换(int(), float(), str())。例如:`+a`使数值变正,`-a`变为负数,`~a`为按位取反,`abs(a)`获取绝对值,而`int(a)`, `float(a)`, `str(a)`则用于类型转换。示例代码展示了这些运算符的使用效果。
15 0
|
1月前
|
存储 Python
Python系列(13)—— 三元运算符
Python系列(13)—— 三元运算符
|
1月前
|
存储 Python
Python系列(11)—— 赋值运算符
Python系列(11)—— 赋值运算符
|
1月前
|
Python
Python系列(7)—— 运算符的优先级
Python系列(7)—— 运算符的优先级
|
1月前
|
算法 数据处理 Python
Python系列(6)—— Python运算符
Python系列(6)—— Python运算符
|
1月前
|
索引 Python
Python系列(14)—— 字符串运算符
Python系列(14)—— 字符串运算符
|
1天前
|
开发者 索引 Python
Python中的海象运算符:简洁而强大的赋值表达式
【4月更文挑战第17天】Python 3.8 引入了海象运算符 `:=`,也称赋值表达式运算符,用于在表达式内部赋值,简化代码并提升可读性。它能用于条件判断、循环控制和函数参数等场景,优化逻辑流程。然而,使用时需注意可读性、运算符优先级及赋值限制,以确保代码清晰易懂。海象运算符是Python编程的一个有用工具,但应根据情况谨慎使用。
|
6天前
|
数据采集 机器学习/深度学习 人工智能
「Python系列」Python运算符
Python 支持多种运算符,包括算术运算符、比较运算符、逻辑运算符、位运算符等等。
16 3
|
12天前
|
存储 Python
python基础篇: python中的流程控制,你都了解吗?
python基础篇: python中的流程控制,你都了解吗?
20 3
|
26天前
|
安全 程序员 数据处理
Python运算符详解
Python编程中的运算符包括算术、比较、逻辑、赋值和位运算符。算术运算符如加法(+), 减法(-), 乘法(*), 除法(/), 整除(//)和取模(%)用于数学运算。比较运算符如==, !=, &gt;, &lt;, &gt;=和&lt;=用于比较两个值。逻辑运算符and, or和not用于组合布尔表达式。赋值运算符如=, +=等用于赋值和复合赋值。位运算符如&(按位与)、|(按位或)、^(按位异或)、~(按位取反)、&lt;&lt;(左移)和&gt;&gt;(右移)对整数的二进制位进行操作,常用于底层数据处理和性能优化。

热门文章

最新文章