Python3基础语法——变量与运算符

变量

  • Python中变量命名规则

1. 可使用字母、数字、下划线任意组合,但首字母不能是数字

2. 保留关键字不能用在变量名中

3. 区分大小写

4. 变量没有类型限制,在赋值时不规定变量类型 

5.python中建议使用小写字母+下划线区分,例如:user_account

>>> # int str tuple为值类型 list set dict为引用类型 值类型不可变 引用类型可变
>>> a=1
>>> b=a
>>> a=3
>>> print(b)
1
>>> a=[1,2,3,4,5]
>>> b=a
>>> a[0]=7
>>> print(b)
[7, 2, 3, 4, 5]

运算符

  • 算数运算符:加、减、乘、除、整除、取余、n次方

>>> 'hello'+'world'
'helloworld'
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> 3-1
2
>>> 3/2
1.5
>>> 3//2
1
>>> 5%2
1
>>> 2**2 #2的平方
4
>>> 2**5 #2的5次方
32
  • 赋值运算符:=、+=、*=、/=、//=、%=、 **=

>>> c=1
>>> c+=1
>>> print(c)
2
>>> d=1
>>> c-=d
>>> print(c)
1
  • 比较(关系)运算符:==、!=、>、<、>=、<=    

操作结果返回bool值

>>> 1==1
True
>>> 1>1
False
>>> 1>=1 #大于或者等于
True
>>> b=1
>>> b+=b>=1
>>> #执行过程 b>=1为True b=b+True b结果为2
>>> print(b)
2
  • 逻辑运算符: and(且)、or(或)、not(非)

操作对象为bool类型,返回结果也为bool类型

注:对于int、float类型,0被认为是False,非0被认为是True;对于字符串类型,空字符串被认为是False,其他被认为是True;

对于list、tuple、set、dict 类型,空被认为是False,其他被认为是True

>>> True and True
True
>>> True and False
False
>>> True or False
True
>>> False or False
False
>>> not False
True
>>> not True
False
>>> not not True
True
>>> 1 and 1
1
>>> 'a' and 'b'
'b'
>>> 'a' or 'b'
'a'
>>> not 'a'
False
>>> not 0.1
False
>>> not ''
True
>>> 1 and 2 #计算机读到2 才能判断返回结果
2
>>> 1 or 2 #计算机读到1 即可判断返回结果
1
  • 成员运算符:in、not in

返回值为bool类型

>>> #字符串
>>> a='h'
>>> a in 'hello'
True
>>> b=6
>>> #列表
>>> b in [1,2,3,4,5]
False
>>> #元组
>>> b not in (1,2,3,4,5)
True
>>> #集合
>>> b not in {1,2,3,4,5}
True
>>> #字典 判断的为key
>>> b='c'
>>> b in {'c':1}
True
  • 身份运算符:is 、is not

身份运算符,比较的是两个变量的身份(内存地址)。

>>> a=1
>>> b=2
>>> a is b
False
>>> a is not b
True
>>> a=1
>>> b=1.0
>>> a==b #比较的是两个变量的取值
True
>>> a is b #比较的是两个变量的地址
False
  • 位运算符:&(按位与)、|(按位或)、^(按位异或)、~(按位取反)、<<(左移动)、>>(右移动)

把数字当做二进制数进行运算

>>> a=2
>>> b=3
>>> a&b
2
>>> a|b
3

猜你喜欢

转载自blog.csdn.net/xushunag/article/details/81455154