Python基本运算
1、复数运算
变量在使用前必须“定义”(赋值),否则会出错
带有后缀 j 或 J 就被视为虚数,带有非零实部的复数写为(real + imag * j),或者可以用complex(real, imag)函数创建。
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0, 1)
(-1+0j)
复数的实部和虚部总是记为两个浮点数;要从复数z中提取实部和虚部,使用z.real和z.imag。
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
2、字符串
不同于C字符串,Python字符串不可变。
>>> word[0] = ’x’
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: ’str’ object does not support item assignmen
3、列表List
可以写作中括号之间的一列逗号分隔的值。列表的元素不必是同一类型,且允许修改。
>>> a = [’spam’, ’eggs’, 100, 1234]
>>> a
[’spam’, ’eggs’, 100, 1234]
就像字符串索引,列表从0开始检索,可以被切片和连接:
>>> a[0]
’spam’
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
[’eggs’, 100]
>>> a[:2] + [’bacon’, 2*2]
[’spam’, ’eggs’, ’bacon’, 4]
>>> 3*a[:3] + [’Boo!’]
[’spam’, ’eggs’, 100, ’spam’, ’eggs’, 100, ’spam’, ’eggs’, 100, ’Boo!’]
所有切片操作都会返回新的列表,包含求得的元素。
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert
允许嵌套列表(创建一个包含其他列表的列表)
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
在列表末尾添加元素内容:
>>> p[1].append(’xtra’)
>>> p
[1, [2, 3, ’xtra’], 4]
>>> q
[2, 3, ’xtra’]
注意:最后一个例子中, p[1] 和q 实际上指向同一个对象!
4、while循环
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print(b)
... a, b = b, a+b
...
1
1
2
3
5
8