python-5 运算符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/L1558198727/article/details/82733571

逻辑运算符

and
or
nor


>>> a = 10
>>> b = 20
>>> a and b
20
>>> a or b
10
>>> not(a or b)
False

成员运算符

判断元素是否在另外的成员里面

in
not in

>>> x = 'abcd'
>>> y = 'a'
>>> y in x
True

身份运算符

用于比较两个对象的存储单元(地址)
is 
is not

>>> x = 'abc'
>>> y = x
>>> z = 'acde'
>>> x is y
True
>>> x is z
False
>>> x is not z
True
---------
>>> x = 'abc'
>>> y = 'abc'
>>> x is y
True

都在常量区?

is 与 == 的区别?

is:
比较地址

==:
比较的是内容

3种错误类型

语法错误

文法和标点的错误
Eg:
>>> x = 5
>>> y = 6
>>> print(x,y)
5 6
>>> print(x+y)
11
>>> print(x+" "+y)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    print(x+" "+y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

运行时异常:
>>> num += 1
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    num += 1
NameError: name 'num' is not defined

逻辑错误:(最难找的bug)
average = num1 + num2 /2

流程控制语句

三种:
顺序 判断(选择) 循环

选择语句:
1.单分支
if(条件表达式):
    语句

条件表达式:关系 逻辑 算术表达式三种
语句:可以是单个语句,也可以是多个语句 但是要注意缩进
通过缩进来组织代码,没有{}

2.双分支 加上else
if(判断语句):
    语句
else3.多分支
if(条件表达式):
    语句
elif(条件表达式):
    语句
else:
    语句

if语句可以嵌套 可以放在上面的三个语句的任意位置 注意缩进即可

python没有三元运算符

循环语句

循环分为两种 for while

1.可迭代对象:系列、字典、文件对象、迭代器、生成器对象

for 变量 in 对象集合:
    语句
Eg:

>>> for i in (1,2,3,4,5,6):
    print(i)

1
2
3
4
5
6

迭代器对象 (range)

在python3中用来产生指定范围内的数字序列,是一个迭代器对象

在python2中,range是一个函数,是生成器

range(start,stop,[step])结束不包含,开始包含
步长为1的时候可以省略


>>> for i in range(1,11,1):
    print(i)


1
2
3
4
5
6
7
8
9
10
----
Eg:
>>> for i in range(1,11,3):
    print(i)


1
4
7
10

-----
start也可以省略

>>> for i in range(5):
    print(i)

0
1
2
3
4

print函数的结尾可以改变

>>> for i in range(5):
    print(i,end=" ")

if语句的括号不要省略

while循环

缩进和for相同

循环的嵌套

循环的嵌套不能超过三层,如果超过三成就是垃圾代码

循环的其他语句

break:
结束当前循环

continue:
进行下一轮循环

死循环

ctrl + c 结束当前程序

猜你喜欢

转载自blog.csdn.net/L1558198727/article/details/82733571