Python编程入门

https://docs.python.org/3/tutorial/index.html

Hello World!

1. REPL

这个模式下可以简单测试代码片段

2. 调用解释器

code.py:
print("Hello World!")

$ python3 code.py

3. 直接调用

code.py:
#!/usr/bin/env python3
print("Hello World!")

$ ./code.py

常用数据类型和Literal

数字

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5
1.6

>>> 8 // 5
1
>>> 8 % 5
3
>>> 5 ** 3
125
>>> 0x20
32

字符串

>>> "Hello World!"
'Hello World!'

>>> 'Hello World!'
'Hello World!'

>>> 'Hello\nWorld!'
'Hello World!'

>>> print('Hello\nWorld!')
Hello
World!

>>> print('Hello\tWorld!')
Hello   World!

>>> print('Hello\\World!')
Hello\World!

>>> 'py' * 3
'pypypy'

>>> 'py' + 3
TypeError: Can't convert 'int' object to str implicitly

>>> 'py' + '3'
'py3'

列表

>>> bases = ['A', 'T', 'C', 'G']
>>> bases
['A', 'T', 'C', 'G']

>>> bases[0]
'A'
>>> bases[-1]
'G'
>>> bases[1:3]
['T', 'C']

 +---+---+---+---+
 | A | T | C | G |
 +---+---+---+---+
 0   1   2   3   4
-5  -4  -3  -2  -1

>>> bases[2:]
['C', 'G']
>>> bases[:2]
['A', 'T']

>>> bases = bases + ['N']
>>> bases
['A', 'T', 'C', 'G', 'N']

>>> bases[1] = 'U'
>>> bases
['A', 'U', 'C', 'G', 'N']

>>> len(bases)
5

字典

>>> counts = {'A': 100, 'T': 55, 'C': 33, 'G': 0}
>>> counts
{'C': 33, 'A': 100, 'T': 55, 'G': 0}

>>> counts['A']
100

>>> counts['A'] = 105
>>> counts
{'C': 33, 'A': 105, 'T': 55, 'G': 0}

简单流程控制

if

freq = alt_depth / depth

if freq > 0.9:
    print("hom-alt")
elif 0.4 < freq < 0.6:
    print("het")
elif freq < 0.1:
    print("hom-ref")
else:
    print("cannot decide")

for

seq = "TCCAGCTNTCNGCGTGCTAGC"

num_N = 0
for base in seq:
    if base == 'N':
        num_N = num_N + 1

print(num_N)

break and else

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        print(n, 'is a prime number')

The outputs are

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

continue

for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    print("Found a number", num)

The outputs are

Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

while, try-except-else-finnaly

Iterable

for i in "CCTAACCCTAACCCTAACCCTAACCCTAACCCATA":
    print(i)

>>> x = range(2,5)
>>> x
range(2,5)

>>> list(x)
[2, 3, 4]

>>> [x*x for x in range(2,5)]
[4, 9, 16]

>>> iter = (x*x for x in range(2,5))
>>> iter
generator object genexpr at 0x0000024F47C9B2B0

>>> for i in iter:
...     print(i)
4
9
16

>>> iter = (x*x for x in range(2,5) if x % 2 == 0)
>>> list(iter)
[4, 16]

>>> iter = enumerate(['A', 'C', 'C'])
>>> for i, base in iter:
...   print(i)
...   print(base)
0
A
1
C
2
C

>>> seq = "AACTCG"
>>> if 'N' in seq:
...   print('has N')
... else:
...   print('clean')
clean

方法

>>> x = []
>>> x.append('A')
>>> x
['A']

>>> x.extend(['T', 'G'])
>>> x
['A', 'T', 'G']

>>> x.pop()
'G'
>>> x
['A', 'T']

>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']

>>> help(x.sort)
Help on built-in function sort:

sort(...) method of builtins.list instance
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

函数定义和调用

def qual_to_num(x):
    return ord(x) - 33

>>> qual = "KF<,7A"
>>> for q in qual:
...   print(q, qual_to_num(q))

>>> f = lambda x: ord(x) - 33
>>> iter = (f(q) for q in qual)
>>> list(iter)
[42, 37, 27, 11, 22, 32]

实例

统计一个TXT(SNP)文件中不同突变类型的个数

file = open("example.txt")

counts = {}

for n, line in enumerate(file):
    if n == 0:
        continue

    line = line.split()
    mut = line[3] + line[4]

    if mut in counts:
        counts[mut] = counts[mut] + 1
    else:
        counts[mut] = 1

print(counts)