在 Python 中,变量就是变量,它没有类型,我们所说的“类型”是变量所指的内存中对象的类型。
Python 中的变量不需要声明,在第一次赋值后被创建
=
用来给变量赋值
Python 允许你为多个变量赋值,例如
>>> a = b = c = 1
>>> d, e, f = 1, 2, 3
del
关键字用于删除对象
del a, b
type()
函数>>> a, b, c, d = 20, 5.5, True, 4 + 3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
isinstance()
函数>>> a = 111
>>> isinstance(a, int)
True
type()
和 isinstance()
的区别type()
和 isinstance()
的区别在于,type()
不会认为子类是一种父类型,而 isinstance()
会认为子类是一种父类型
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False
Python中有四种数字类型
其中复数的虚数单位用 j
来表示
>>> 5 + 4 # 加法
9
>>> 4.3 -2 # 减法
2.3
>>> 3 * 7 # 乘法
21
>>> 2 / 4 # 除法
0.5
>>> 2 //4 # 整除
0
>>> 17 % 3 # 取余
2
>> 2 ** 5 # 乘方
32
'
和 "
的使用完全相同'''
和 """
可以指定一个多行字符串\
r
可以让 \
不转义,如 r"this is a line with \n"
+
用于链接两个字符串,*
用于重复字符串string[begin : end : step]
表示一个字符串截取step
默认为 1
step
为复数s1 = 'Hello'
print(s1)
print(s1 + 'World')
print(s1 * 3)
print(s1[0])
print(s1[0 : -1])
print('Hello\n')
print(r'Hello\n')
输出为
Hello
HelloWorld
HelloHelloHello
Hello
Hell
Hello
Hello\n
[]
内,元素之间用 ,
分割+
是链接运算符, *
是重复操作>>> list1 = ['abcd', 123, 2.23]
>>> list2 = ['eee', 2+3j]
>>> print(list1)
['abcd', 123, 2.23]
>>> print(list1[0])
abcd
>>> print(list * 2)