Python入门
Python与其他语言最大的区别就是,Python的代码块不使用大括号{}来控制类,函数以及其他逻辑判断,而是用缩进来写模块
数字和表达式
整除 //
求余 % (适用浮点数)
求幂 **
内建函数 pow/abs/round
math模块 floor/ceil/sqrt
cmath 复数模块 complex math
内建值 None
>>> import math
>>> math.floor(4.53)
4.0
>>> math.sqrt(9)
3.0
>>> foo = math.sqrt
>>> foo(9)
3.0
>>> math.ceil(4.53)
5.0
附加:
1.floor向下取整/ceil向上取整
2.Python支持变量引用函数 foo = math.sqrt
用户输入
input 保持原始输入类型
raw_input 原始输入转化为字符串
>>> x = input("x: ")
x: 12
>>> x
12
>>> x = raw_input("x: ")
x: 12
>>> x
'12'
模块导入
import somemodule
from somemodule import somefunction
from somemodule import somefunction, anothefunction, yetanotherfunction
from somemodule import *
from somemodule as selfname
tips:
查看模块内函数列表 dir(ModuleName)
查看全局/局部变量列表 globals()/locals()
重载模块 reload(ModuleName)
注释
单行注释(#)
多行注释('''/"""):
区别执行脚本首行
#/usr/bin/env python
字符串
单/双引号基本等同,特定场景可用
>>> "Hello 'world'"
"Hello 'world'"
>>> 'Hello "world"'
'Hello "world"'
或者转义
>>> "Hello \"world\""
'Hello "world"'
>>> 'Hello \'world\''
"Hello 'world'"
假如输出同时包含单/双引号,则必须转义
>>> 'Let\'s say "Hello world"'
'Let\'s say "Hello world"'
字符串拼接 +
>>> "Let's say" '"Hello world"'
'Let\'s say"Hello world"'
>>> "Hello, " + "world !"
'Hello, world !'
拼接包含数字
- str 转换合理的字符串
- repr 创建合理的字符串
>>> Temp = 100
>>> print "Hello world " + Temp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "Hello world " + repr(Temp)
Hello world 100
>>> print "Hello world " + str(Temp)
Hello world 100
字符串换行
- 行末添加转义字符 \
- 使用长字符串 三个单/双引号包含字符串,字符串中支持使用单/双引号(首尾需转义)
>>> "Hello, \
... world"
'Hello, world'
>>> """Let's say "Hello world""""
File "<stdin>", line 1
"""Let's say "Hello world""""
^
SyntaxError: EOL while scanning string literal
>>> """Let's say "Hello world\""""
'Let\'s say "Hello world"'
>>> '''Let's say "Hello world"'''
'Let\'s say "Hello world"'
原始字符串(添加r表示) 支持特殊字符
>>> print "Hello \nworld"
Hello
world
>>> print r"Hello \nworld"
Hello \nworld
Unicode(添加u表示)
- python字符串默认8位ASCII码存储,Unicode使用16位Unicode字符存储
>>> "北京"
'\xe5\x8c\x97\xe4\xba\xac'
>>> u"北京"
u'\u5317\u4eac'
格式化输出(%)
Type "help", "copyright", "credits" or "license" for more information.
>>> format = 'Hello %s, %s enough for ya ?'
>>> values = ('world', 'Hot')
>>> print format % values
Hello world, Hot enough for ya ?
附加:若使用元组作为参数 括号不可以省略
字符串常用函数
find/join/split/lower/title/replace/strip/translate
replace/translate功能相同,区别,translate只处理单个字符,但支持同时执行多个替换,效率更高
>>> 'I love Beijing'.replace('Beijing', 'Hunan')
'I love Hunan'
>>> import string
>>> table = string.maketrans('ac','ca')
>>> table[97:123]
'cbadefghijklmnopqrstuvwxyz'
>>> 'aaaaa'.translate(table)
'ccccc'
列表(’[]’)
>>> edward = ['Edward Gumby',42]
>>> john = ['Jhon Smith', 50]
>>> database = [edward, john]
>>> database
[['Edward Gumby', 42], ['Jhon Smith', 50]]
索引/相加/相乘
#!/usr/bin/env python
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
+ ['st', 'nd', 'rd'] + 7 * ['th'] \
+ ['st']
year = raw_input('Year: ')
month = raw_input('Month (1-12): ')
day = raw_input('Day (1-31): ')
month_number = int(month)
day_number = int(day)
month_name = months[month_number - 1]
ordinal = day + endings[day_number]
print month_name + ' ' + ordinal + '. ' + year
分片
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> numbers[0:3]
[1, 2, 3]
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> numbers[:3]
[1, 2, 3]
>>> numbers[-3:-1]
[4, 5]
>>> numbers[-3:]
[4, 5, 6]
支持步长
>>> numbers[0:6:2]
[1, 3, 5]
>>> numbers[::-2]
[6, 4, 2]
附加:指定开始/结束点,开始点元素包含在结果中,结束点元素不在结果中
成员资格
#!/usr/bin/env python
database = [
['albert', '1234'],
['dilbert', '4242'],
['smith', '8520']
]
username = raw_input('User name: ')
pin = raw_input('PIN code: ')
if [username, pin] in database: print 'Access granted'
else: print 'Access failed'
长度/最小值/最大值
len/min/max 省略
字符串/列表转换
>>> say = list('HelloWorld')
>>> say
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
>>> ''.join(say)
'HelloWorld'
>>> ' '.join(say)
'H e l l o W o r l d'
赋值/删除
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']
>>> del name[1]
>>> name
['P', 't', 'h', 'o', 'n']
>>> name[1:5] = []
>>> name
['P']
列表方法(append/count/extend/index/insert/pop/remove/reverse/sort)
>>> numbers = [1,2,3]
>>> numbers
[1, 2, 3]
>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4]
>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4, 4]
>>> numbers.count(4)
2
>>> numbers.pop(3)
4
>>> numbers
[1, 2, 3, 4]
>>> numbers.extend([5,6,7,8])
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers.index(4)
3
>>> numbers.insert(9,8)
>>> numbers
[1, 2, 3, 4, 5, 5, 6, 7, 8, 8]
>>> numbers.pop()
8
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers.remove(8)
>>> numbers
[1, 2, 3, 4, 5, 6, 7]
>>> numbers.reverse()
>>> numbers
[7, 6, 5, 4, 3, 2, 1]
>>> numbers.sort()
>>> numbers
[1, 2, 3, 4, 5, 6, 7]
简单赋值(x/y指向相同指针)
>>> x = [4,6,2,1,8]
>>> y = x
>>> y
[4, 6, 2, 1, 8]
>>> x.sort()
>>> x
[1, 2, 4, 6, 8]
>>> y
[1, 2, 4, 6, 8]
获取排序副本
>>> y = sorted(x)
>>> y
[1, 2, 4, 6, 8]
高级排序(支持参数key/reverse)
>>> x = ['Perl', 'Python', 'Erlang', 'C++']
>>> x.sort(key=len, reverse=True)
>>> x
['Python', 'Erlang', 'Perl', 'C++']
元组(’()’)
类似列表,但元组不支持二次赋值
元组用括号表示,逗号隔开
>>> (1,2,3)
(1, 2, 3)
>>> (1,)
(1,)
>>> ()
()
>>> 3 * (40 + 2)
126
>>> 3 * (40 + 2,)
(42, 42, 42)
>>> x = 1,2,3
>>> x
(1, 2, 3)
>>> x[1]
2
>>> x[0:2]
(1, 2)
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)
字典(’{}’)
Python中唯一内建的映射类型(查询效率高于列表,规模越大,两者效率差距越明显),此外字典是无序的,列表通过偏移存储,字典通过键值存储
>&g