Python编程中一定要注意的那些“坑”(一)

来源:互联网 发布:怎么让手机只用4g网络 编辑:程序博客网 时间:2024/04/30 20:06

1  逗号不是运算符,只是个普通的分隔符
>>> x = 3, 5
>>> x
(3, 5)
>>> x == 3, 5
(False, 5)
>>> 1, 2, 3
(1, 2, 3)
>>> 3 in [1, 2, 3], 5
(True, 5)


2  ++和--也不是运算符,虽然有时候这样用也行
>>> x = 3
>>> x+++5
8
>>> x++
SyntaxError: invalid syntax
>>> ++5
5
>>> ++++++++5
5
>>> --5
5

# 下面这个代码是上面那个代码的等价形式

>>> -(-5)
5
>>> ---------5
-5


3  lambda表达式中变量的作用域
>>> d = dict()
# 这里有个坑
>>> for i in range(5):
       d[i] = lambda :i**2
 
>>> d[2]()
16
>>> d[3]()
16
# 这样看的更清楚一些
# lambda表达式中i的值是调用时决定的

>>> i = 10
>>> d[0]()
100
# 写成下面这样子就没问题了
>>> d = dict()
>>> for i in range(5):
       d[i] = lambda x=i:x**2
 
>>> d[2]()
4
>>> d[3]()
9


4  某个作用域中只要有某变量的赋值语句,它就是个局部变量
>>> x = 10
>>> def demo():
       print(x)
# 这样是可以的,访问全局变量
>>> demo()
10
>>> def demo():
       print(x)
       x = 3
       print(x)
# 这样是错的,x是局部变量,在x=3之前不存在x,print()失败
>>> demo()
Traceback (most recent call last):
  File "<pyshell#156>", line 1, in <module>
    demo()
  File "<pyshell#155>", line 2, in demo
    print(x)
UnboundLocalError: local variable 'x' referenced before assignment


5  纠结的元组到底可变不可变
>>> x = (1, 2, 3)
# 元组中的元素不可修改
>>> x[0] = 4
Traceback (most recent call last):
  File "<pyshell#161>", line 1, in <module>
    x[0] = 4
TypeError: 'tuple' object does not support item assignment

>>> x = ([1, 2], 3)
# 不能修改元组中的元素值
>>> x[0] = [3]
Traceback (most recent call last):
  File "<pyshell#163>", line 1, in <module>
    x[0] = [3]
TypeError: 'tuple' object does not support item assignment

>>> x
([1, 2], 3)
>>> x[0] = x[0] + [3]
Traceback (most recent call last):
  File "<pyshell#165>", line 1, in <module>
    x[0] = x[0] + [3]
TypeError: 'tuple' object does not support item assignment

>>> x
([1, 2], 3)
# 这里有个坑,虽然显示操作失败了,但实际上成功了
>>> x[0] += [3]
Traceback (most recent call last):
  File "<pyshell#167>", line 1, in <module>
    x[0] += [3]
TypeError: 'tuple' object does not support item assignment

>>> x
([1, 2, 3], 3)
>>> x[0].append(4)
>>> x
([1, 2, 3, 4], 3)
# y和x[0]指向同一个列表,通过其中一个可以影响另一个
>>> y = x[0]
>>> y += [5]
>>> x
([1, 2, 3, 4, 5], 3)
# 执行完下面的语句,y和x[0]不再是同一个对象
>>> y = y + [6]
>>> x
([1, 2, 3, 4, 5], 3)
>>> y
[1, 2, 3, 4, 5, 6]


6  字符串转换成数字的几种方式

>>> eval('9.9')
9.9
>>> eval('09.9')
9.9
>>> float('9.9')
9.9
>>> float('09.9')
9.9
>>> int('9')
9
>>> int('09')
9

# 坑来了,使用eval()转换整数时前面不能有0

>>> eval('09')
Traceback (most recent call last):
  File "<pyshell#187>", line 1, in <module>
    eval('09')
  File "<string>", line 1
    09
     ^
SyntaxError: invalid token

0 0