---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-48-17aa7cb5f29d> in <module>()
1 # 访问一个没有赋值过的变量名,会抛出异常
2 # 直接看console中的输出来了解异常原因
----> 3 some_unknown_var
NameError: name 'some_unknown_var' is not defined
1 2 3 4
# if 可以用来作为一种表达式 # a if b else c 意为 b为True取a,b为False取c hoo = "yahoo!"if3 > 2else2# => "yahoo!" hoo
# list有append函数,可以在末尾添加item li.append(1) # li is now [1] li.append(2) # li is now [1, 2] li.append(4) # li is now [1, 2, 4] li.append(3) # li is now [1, 2, 4, 3] # pop函数可以删除list中的最后一个元素 li.pop() # => 3 and li is now [1, 2, 4] # 还是把3放回去吧 li.append(3) # li is now [1, 2, 4, 3] again.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-53-9bf3eba2f737> in <module>()
1 # 如果index访问的item超出list长度,会抛出异常
----> 2 li[4] # Raises an IndexError
IndexError: list index out of range
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-58-0f5f01941ba3> in <module>()
1 # remove方法调用时,如果没有对应value的item,则会报错
----> 2 li.remove(100)
ValueError: list.remove(x): x not in list
1 2 3
# insert(index, value)可以在list中的index处插入值为value的item li.insert(1, 2) # li is now [1, 2, 3] again li
[1, 2, 3]
1 2 3 4
# index(value)方法可以在list中进行查询,返回值为value的item的index li.index(2) # => 1 # 没有的话就报错 li.index(4) # Raises a ValueError as 4 is not in the list
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-60-4520a794cb71> in <module>()
2 li.index(2) # => 1
3 # 没有的话就报错
----> 4 li.index(4) # Raises a ValueError as 4 is not in the list
ValueError: 4 is not in list
# 可以对tuple进行解压,分别赋值给变量 a, b, c = (1, 2, 3) # a = 1, b = 2 and c = 3 # 还可以进行扩展拆包 a, *b, c = (1, 2, 3, 4) # a = 1, b = [2, 3] and c = 4 # 如果你不写括号,tuple也会自动生成 d, e, f = 4, 5, 6 # 交换两个变量的值 e, d = d, e # d is now 5 and e is now 4
# setdefault方法可以给不存在的key赋值 # 如果该键值对(key:value)已存在,则不生效 filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
5
1 2 3 4
# 在dictionary中增加键值对,可以使用update方法 filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} # 直接对不存在的key 进行赋值,也可以实现键值对的增加 filled_dict["four"] = 4# another way to add to dict
1 2
# 通过del方法可以删除对应key的键值对 del filled_dict["one"] # Removes the key "one" from filled dict