首页 编程 软件学院 查看内容

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

2017-6-13 22:22 |来自: 互联网 2320 0

摘要: Python学习交流裙5952660891 逗号不是运算符,只是个普通的分隔符 x = 3, 5 x(3, 5) x == 3, 5(False, 5) 1, 2, 3(1, 2, 3) 3 in , 5(True, 5)2 ++和--也不是运算符,虽然有时候这样用也行 x = 3 x+++58 x++SyntaxEr ...

Python学习交流裙595266089

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 "", line 1, in

demo()

File "", 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 "", line 1, in

x[0] = 4

TypeError: 'tuple' object does not support item assignment

>>> x = ([1, 2], 3)

# 不能修改元组中的元素值

>>> x[0] = [3]

Traceback (most recent call last):

File "", line 1, in

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 "", line 1, in

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 "", line 1, in

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 "", line 1, in

eval('09')

File "", line 1

09

^

SyntaxError: invalid token

本文出处: http://www.toutiao.com/a6431010283296686337/
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花

鸡蛋

最新评论

返回顶部