变量、运算符与数据类型

变量、运算符与数据类型

1. 注释

###在python中,‘#‘表示注释,作用于整行。
【例子】单行注释
#这是一个注释
print(“hello datawhale”)

##’’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释
‘’’
这是多行注释,
用三个单引号
‘’’

“”"
这是多行注释,
用三个双引号
“”"

2. 运算符

###算术运算符

操作符 名称 示例
+ 1 + 1
- 2 - 1
* 3 * 4
/ 3 / 4
// 整除(地板除) 3 // 4
% 取余 3 % 4
** 2 ** 3

【例子】

print(1 + 1)  # 2
print(2 - 1)  # 1
print(3 * 4)  # 12
print(3 / 4)  # 0.75
print(3 // 4)  # 0

比较运算符

操作符 名称 示例
> 大于 2 > 1
>= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5

【例子】

print(2 > 1)  # True
print(2 >= 4)  # False
print(1 < 2)  # True
print(5 <= 2)  # False
print(3 == 4)  # False
print(3 != 5)  # True

###位运算符

操作符 名称 示例
~ 按位取反 ~4
& 按位与 4 & 5
| 按位或 4 | 5
^ 按位异或 4 ^ 5
<< 左移 4 << 2
>> 右移 4 >> 2

【例子】

print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

###三元运算符
【例子】

x,y=4,5
if x<y:
     small=x
 else:
      small=y
 print(small)

有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

x, y = 4, 5
small = x if x < y else y
print(small)  # 4

###其他运算符

操作符 名称 示例
in 存在 'A' in ['A', 'B', 'C']
not in 不存在 'h' not in ['A', 'B', 'C']
is "hello" is "hello"
is not 不是 "hello" is not "hello"

【例子】

letters = ['A', 'B', 'C']
if 'A' in letters:
    print('A' + ' exists')
if 'h' not in letters:
    print('h' + ' not exists')

# A exists
# h not exists

3. 变量和赋值

  • 在使用变量之前,需要对其先赋值。
  • 变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
  • Python 变量名是大小写敏感的,foo != Foo。

【例子】

teacher=“java是最棒的语言”
print(teacher)'''

【例子】
```python
myTeacher = "老马的程序人生"
yourTeacher = "小马的程序人生"
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher)  # 老马的程序人生,小马的程序人生

4. 数据类型与转换

类型 名称 示例
int 整型 <class 'int'> -876, 10
float 浮点型<class 'float'> 3.149, 11.11
bool 布尔型<class 'bool'> True, False

整型

【例子】 通过‘print()‘可看出’a‘的值 以及类(class) 是’int’

a = 1031
print(a, type(a))
# 1031 <class 'int'>

【例子】

b = dir(int)
print(b)

【例子】找到一个整数的二进制表示,再返回其长度。

a = 1031
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11

浮点型

【例子】

print(1, type(1))
#   1 <class 'int'>
a = 0.00000023
b = 2.3e-7
print(a)  # 2.3e-07
print(b)  # 2.3e-07

有时候我们想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现。

import decimal是 28
from decimal import Decimal

Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值 位 (prec=28)。

a = decimal.getcontext()
print(a)

# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
# capitals=1, clamp=0, flags=[], 
# traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)
print(b)


# 0.3333333333333333333333333333

【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)

# 0.3333

###布尔型
布尔 (boolean) 型变量只能取两个值,TrueFalse。当把布尔型变量用在数字运算中,用 10 代表 TrueFalse

【例子】

print(True + True)  # 2
print(True + False)  # 1
print(True * False)  # 0

除了直接给变量赋值 TrueFalse,还可以用 bool(X) 来创建变量,其中 X 可以是

  • 基本类型:整型、浮点型、布尔型
  • 容器类型:字符串、元组、列表、字典和集合
    【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0bool(X) 就是 True,其余就是 False
print(type(0), bool(0), bool(1))
# <class 'int'> False True

print(type(10.31), bool(0.00), bool(10.31))
# <class 'float'> False True
  • 对于数值变量,0, 0.0 都可认为是空的。
  • 对于容器变量,里面没元素就是空的。

###获取类型信息
获取类型信息 ‘type(object)’
【例子】

print(type(1))  # <class 'int'>
print(type(5.2))  # <class 'float'>
print(type(True))  # <class 'bool'>
print(type('5.2'))  # <class 'str'>
  • 获取类型信息 isinstance(object, classinfo)
    【例子】
print(isinstance(1, int))  # True
print(isinstance(5.2, float))  # True
print(isinstance(True, bool))  # True
print(isinstance('5.2', str))  # True

注:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。
  • isinstance() 会认为子类是一种父类类型,考虑继承关系。
  • 如果要判断两个类型是否相同推荐使用 isinstance()

类型转换

  • 转换为整型 int(x, base=10)
  • 转换为字符串 str(object='')
  • 转换为浮点型 float(x)

【例子】

print(int('520'))  # 520
print(int(520.52))  # 520
print(float('520.52'))  # 520.52
print(float(520))  # 520.0
print(str(10 + 10))  # 20
print(str(10.1 + 5.2))  # 15.3

5. print() 函数

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
  • 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
  • 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
  • 关键字参数end是输出结束时的字符,默认是换行符\n
  • 关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
  • 关键字参数flush是立即把内容输出到流文件,不作缓存。

【例子】没有参数时,每次输出后都会换行。

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)


# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana

【例子】item值与'another string'两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
    print(item, 'another string', sep='&')
# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string

练习题

  1. 怎样对python中的代码进行注释?
    一般使用 ’#‘ 进行单行的注释
    " ‘’’ "进行多行注释

  2. python有哪些运算符,这些运算符的优先级是怎样的?
    python有算术运算符/比较运算符/逻辑运算符/位运算符
    一元运算符优于二元运算符。
    先算术运算,后移位运算,最后位运算
    逻辑运算最后结合

  3. python 中 is, is not==, != 的区别是什么
    is,is not是地址比较
    ==,!= 是值比较

  4. python 中包含哪些数据类型?这些数据类型之间如何转换?
    python中包含 int float bool str

类型转换

转换为整型 int(x, base=10)

转换为字符串 str(object=’’)

转换为浮点型 float(x)

猜你喜欢

转载自blog.csdn.net/chestnut_ou/article/details/107523339