>>> x = 10 # 直接引用 >>> print(id(x)) 140725056100288 >>> >>> y = x >>> z = x >>> >>> l = ['a',] >>> print(id(l[0])) 2245258076400 >>> print(id(l[1])) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range >>> print(x) 10 >>> l = ['a',x] >>> print(id(l[1])) 140725056100288 >>>
# 循环引用导致内存泄漏 >>> l1 = [111,] >>> l2 = [222,] >>> >>> l1.append(l2) >>> id(l1),id(l2) (2245287352384, 2245287683712) >>> >>> l1 [111, [222]] >>> >>> id(l1[1]) 2245287683712 >>> >>> l2.append(l1) >>> >>> l2 [222, [111, [...]]] >>> >>> id(l2[1]) 2245287352384 >>>
背景:
分代:
回收:
# 接收用户的输入 # 在python3中input会将用户输入的所有内容都存成字符串类型保存起来赋值给变量名 # username = input('请输入您的账号:') # print(username, type(username)) # age = input("请输入你的年龄:") # age = "18" # print(age, type(age)) # # age = int(age) # int只能将纯数字的字符串转成整型 # print(age > 16)
# 在python2中: # raw_input():用法与python3中的input一模一样 # input():要求用户必须输入一个明确的数据类型,输入的是什么类型,就存成什么类型 >>> age = input('>>>>>') >>>>>18 >>> age,type(age) (18, <type 'int'>) >>> x = input('>>>>>') >>>>>1.2 >>> x, type(x) (1.2, <type 'float'>) >>> x = input('>>>>>') >>>>>[1,2,3] >>> x, type(x) ([1, 2, 3], <type 'list'>) >>>
# 格式化输出 # 按照位置与%s一一对应,少一个不行,多一个也不行 # res = "my name is %s my age is %s" % ('egon', '18') # res = "my name is %s my age is %s" % ('18', 'egon') # res = "my name is %s" % 'egon' # print(res) # 以字典的方式传值 res = "我的名字是 %(name)s my age is %(age)s" % {'name':'egon', 'age':'18'} print(res) # print('my age is %s' % 18) # print('my age is %s' % [1, 23]) # print('my age is %s' % {'age': 18}) # print('my age is %d'%18) # print('my age is %d'%'18') # %d只能接受int
# str.formate(),兼容性好,推荐使用 # res = "my name is {} my age is {}".format('egon', '18') # print(res) # res = "my name is {0} {0} {0} my age is {1} {1}".format('egon', '18') # print(res) # 打破位置的限制,按照key = value传值 res = "我的名字是{name},我的年龄是{age}".format(age=18, name='egon') print(res)
# f'' x = input('请输入姓名:') y = input('请输入年龄:') res = f'我的姓名是{x},我的年龄是{y}' print(res)
print(20 + 3) print(10 / 3) # 结果带小数 print(10 // 3) # 结果只保留整数部分 print(10 % 3) # 取模、取余数 print(10 ** 3) # 次方
print(10 > 3) print(10 < 3) print(10 >= 10) print(10 <= 10) print(10 == 10) print(10 != 10)
age = 19 age += 1 print(age) age -= 1 age /= 1 age //= 1 age %= 1 age **= 1 age *= 1
x = 10 z = x y = x x = y = z = 10 print(x, y, z) print(id(x), id(y), id(z))
m = 10 n = 20 print(m, n) # 交叉赋值 temp = m # m = n # n = temp # print(m, n) # 一行搞定 m, n = n, m print(m, n)
num = [1, 2, 3, 4, 5] m = num[0] n = num[1] x = num[2] y = num[3] z = num[4] print(m, n, x, y, z) m, n, x, y, z = num print(m, n, x, y, z) m, n, x, y, z, p = num # 对应的变量名多一个不行 m, n, x, y = num # 对应的变量名少一个也不行 # 引入*,可以帮我们取两头的值,无法取中间的值 # 取前面三个值 m, n, x, *_ = num print(m, n, x) # 取后面三个值 *_, m, n, x = num print(m, n, x) m, *_, x, y = num print(m, x, y) # 解压字典默认解压出来的是字典的key x, y, z = {'a': 1, 'b': 2, 'c': 3} print(x, y, z)