[python学习]基本知识之运算符

来源:互联网 发布:巴黎 地图 知乎 编辑:程序博客网 时间:2024/06/07 18:43

运算符

算术
  • x+y 相加 8+8=16 ‘a’+’b’=’ab’
  • x-y 相减 8-8=0
  • x*y 相乘 8*8=64
  • x**y 幂运算 8**8=(8*8*8*8*8*8*8*8)=pow(8,8)=16777216
  • x/y 相除 9/8=1.125 注意上下取舍问题,有时会有截断
  import math  >>> math.floor(1.2)  1  >>> math.ceil(1.2)  2
  • x//y 取整除 8//8=1 9//8=1 8//9=0 总是向下取整
  • x%y 取余 8%8=0 8%9=8 9%8=1
比较
  • < 小于
  • <= 小于或等于
  • > 大于
  • >= 大于或等于
  • == 等于
  • != 不等于
  • is
  • is not
  • in
  • not in
逻辑
  • x or y 只有在第一个运算数为False时才会计算第二个运算数的值
  • x and y 它只有在第一个运算数为True时才会计算第二个运算数的值
if bmi>12 and bmi<13:    print()
  • not x 优先级比其他类型的运算符低,所以not a == b相当于not (a == b),而 a == not b是错误的
  • x | y 按位或运算符
  • x ^ y 按位异或运算符
  • x & y 按位与运算符
  • x << n 左移运算符
  • x >> n 右移运算符
  • ~x 按位取反运算符
赋值
  • =
  • +=
  • -=
  • *=
  • /=
  • //=
  • %=
  • **=

函数

  • abs(x) abs(-8.0)=8.0
  • int(x) int(8.0)=8
  • float(x) float(8)=8.0
  • str(x) str(8)=’8’
  • pow(x,y) x的y次幂
  • divmod(x,y) (x//y,x%y) divmod(8,8)=(1,0)
  • complex(x,y) x为实数 y为虚数 complex(8,8)=(8+8j)
  • c.conjugate 返回c的共扼复数

练习中的小例子

# -*- coding: utf-8 -*-height = 1.75weight = 80.5bmi =weight/pow(height,2)print(bmi)if bmi<18.5:    print('过轻')elif bmi>18.5 and bmi<25:    print('正常')elif bmi>25 and bmi<28:    print('过重')elif bmi>28 and bmi<32:    print('肥胖')elif bmi>32:    print('严重肥胖')else:    print('no')
原创粉丝点击