#1. python是一种高级的编程语言
- c, c++, java, php, javascript, vb, c#...
- 任何的编程语言都是为了让计算机干活,
eg:下载音乐,电影,编辑一文档... 而cpu只认识机器指令
- 不同的编程语言,实现同一功能,编写代码量,差距很大
C >> python
- 代码少的代价是运行速度慢
真正软件开发时,除了编写代码之外,需要很多基本的已经写好的现成的东西,加快开发速度。因此高级语言通常会提供一个比较完善的基础代码库,可直接调用。eg:编写电子邮件客户端,有针对电子邮件协议的smtp库;针对桌面环境的GUI库。
1989年圣诞节期间龟叔"Guido van
Rossum"编写的编程语言。TIOBE排行榜,了解编程语言的大致流行程度。
#2. python可以做什么?
- 日常任务,小工具,eg:备份mp3,系统管理员需要的脚本任务
- 做网站,eg:YouTube,国内的豆瓣,Google,Yahoo
- 网络游戏的后台
- 爬虫
python不可以做什么?
- 操作系统只能用C语言编写
- 手机应用,IOS用Object-C, Android用Java
- 3D游戏,最好用C,C++
#3. 工欲善其事,必先利其器
- 命令行交互环境
- 简单的集成开发环境
Windows: http://www.python.org/ftp/python/2.7.9/python-2.7.9.msi
Linux: yum install python -y
Mac:自带python2.7(OS>10.8)
#4. python解释器
cpython
ipython:基于cpython,交互方式有所增强
pypy: 对代码进行动态编译,JIT技术(just-in-time compiler,即时编译器),显著提高代码执行速度。
Jpython: java平台上的python解释器,将python代码编译成java字节码执行。
IronPython: 直接将python代码编译成.net的字节码
#5. 第一个python程序
- 交互方式
- 文本编辑器
sublime
Notepad++
切记:绝对不能使用word(不是纯文本文件)和windows自带的记事本(在文件开始的地方加特殊字符0xefbbbf<16进制>UTF-8 BOM,有了前缀,程序自动判断它为utf-8格式,并按utf-8格式解析文本或字符串,否则,需要按照字符编码格式一个个去验证)
- 直接运行py文件
文件第一行: #!/usr/bin/env python
文件添加执行权限: chmod +x xx.py
如果脚本中有中文字符的话编辑会报错 所以我们要改变编码格式
#coding:utf-8 ##在脚本中随便加入其中的一行就行
#coding=utf-8
#encoding:utf-8
#encoding=uft-8
#-*-coding:utf-8-*-
#6. 输入与输出
##6-1. 输出: 告诉用户程序执行的结果
print + 字符串... //字符串可为多个,逗号隔开
print + 数字|表达式
print 300
print '100 + 200 =',100 + 200
##6-2. 输入(raw_input): 告诉计算机程序所需的信息
name = raw_input()
print name
name = raw_input("嗨,哥们,输入你姓名呗:")
print "hello," name
#7. Python基础
- python是一种计算机编程语言,计算机需要根据编程语言保证程序不能有歧义,任何编程语言都有自己的一套语法,编译器或者解释器就负责把符合语法的程序代码转换成cpu能够识别的机器码,然后执行。
- python采用缩进方式
```
# print absolute value of an integer:
a = 100
if a >= 0:
print a
else:
print -a
```
#7-1. 变量
变量是内存中的一块区域。
变量的命名: 变量名由字母,数字,下划线组成。
>>> a=1
>>> print a
1
>>> a_1 = 111
>>> _a = 222
>>> print _a
222
>>> 1a = 111
File "<stdin>", line 1
1a = 111
^
SyntaxError: invalid syntax //范指语法错误,无效的语法
>>> a = 5
>>> b = 3
>>> print a + b
8
>>> print a + b +c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined //名称错误
变量的特性:
实际存储在内存上;
变量名最好见名知意;
变量可重新赋值;
>>> number1 = 1
>>> number2 = 2
>>> number1 + number2
3
python中地址变量与c语言刚好相反,一条数据包含包含多个标签;
>>> a = 1
>>> b = 1
>>> id(a)
10812520
>>> id(b)
10812520
**练习:
在交互模式中让python计算一月有多少分钟,使用变量DaysPerMonth(每月天数)、HoursPerDay(每天小时数)和MinutesPerHour(每小时分钟数),分别显示JanMintues(一月秒数)和AprMintues(四月秒数)。
#!/usr/bin/python
#coding=utf-8
a=int(raw_input("plase input one month days:"))
b=int(raw_input("plase input four month days:"))
hoursperday=24
minuteperhour=60
print "Janmintues=",a*hoursperday*minuteperhour
print "Aprmintues=",b*hoursperday*minuteperhour
~
##7-2. 运算符与表达式
赋值运算符:=, +=, -=, /=, *=, %=
算术运算符:+, -, *, /, //, %, **
>>> 1 + 1
2
>>> 1 - 1
0
>>> 1 * 3
3
>>> 1 / 2
0
>>> 1.0 / 2
0.5
>>> 1.0 // 2
0.0
>>> 1 % 2
1
>>> 2 ** 3
8
>>> a33 = 3 ** 3
>>> print a33
27
>>> print "a33=",a33
a33= 27
>>> print "a33 =",a33
a33 = 27
关系运算符: >, >=, <, <=, !=, ==
1 < 2,返回一个布尔类型的结果
>>> 1 < 2
True
>>> 1 > 2
False
逻辑运算符:逻辑与and, 逻辑或or, 逻辑非not
运算符的优先级:
eg: 8*4+2*3 a=2+5*3
**练习:
编写一四则表达式,(if语句实现) ###python里面不支持case语句
#!/bin/usr/env python
#coding=utf-8
a=int(raw_input("num1:"))
c=(raw_input("char1(+,-,*,/,%):"))
b=int(raw_input("num2:"))
if c=="+":
print "加法运算:",a+b
elif c=="-":
print "减法运算:",a-b
elif c=="*":
print "乘法运算:",a*b
elif c=="/":
print "除法运算:",a/b
elif c=="%":
print "取余运算:",a%b
else:
print "erron"
##7-3. 数据类型
案例: 123和“123”一样么?
从数字角度讲
从程序语言的识别来讲
>>> a = 123
>>> stra = "123"
>>> a == stra
False
>>> print a
123
>>> print stra
123
>>> a + stra
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
数字:
整型
>>> num1 = 123
>>> type(num1)
<type 'int'>
>>> type(123)
<type 'int'>
长整形
>>> num2 = 999999999999999
>>> type(num2)
<type 'int'>
强制定义为长整型: num3 = 123L
>>> num3 = 123L
>>> type(num3)
<type 'long'>
浮点型:表示小数
>>> f1 = 12
>>> type(f1)
<type 'int'>
>>> f2 = 12.0
>>> type(f2)
<type 'float'>
复数类型:python对复数提供内嵌支持,eg: 3.14j, 8.32e-36j
>>> c = 3.14
>>> type(c)
<type 'float'>
>>> c = 3.14j
>>> type(c)
<type 'complex'>
字符串: 常用三种定义方式
>>> str1 = 'our company is westos'
>>> str2 = "our company is westos"
>>> str3 = """our company is westos"""
>>> type(str1)
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
>>> say = 'let\'s go'
>>> say
"let's go"
>>> say = "let's go "
>>> say
"let's go "
**转义符号
>>> mail = "tom: hello i am westos "
>>> print mail
tom: hello i am westos
>>> mail = "tom:\n hello\n i am westos "
>>> print mail
tom:
hello
i am westos
**三重引号
其他用法:
注释
函数的doc文档
>>> mail = """tom:
... i am jack
... good luck
... """
>>> print mail
tom:
i am jack
good luck
>>> mail
'tom:\n\ti am jack\n\tgood luck\n'
**字符串索引取出相应的值
>>> a = 'abcde'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[3]
'd'
>>> a[0]+a[1]
'ab'
>>> a[0]+a[2]
'ac'
**切片
>>> a
'abcde'
>>> a[1:5:2]
'bd'
>>> a[1:5] //代表切片取出第2个到第4个
'bcde'
>>> a[:5]
'abcde'
>>> a[4:]
'e'
>>> a[4:1] //python中默认是从左向右取值
''
>>> a[4:1:-1] //当步长为-1时,从右向左取值
'edc'
>>> a[:]
'abcde'
>>> a[-1]
'e'
>>> a[-4:-1] //代表倒数第2个到倒数第4个切片
'bcd'
>>> a[-2:-4]
''
>>> a[-2:-4:1]
''
>>> a[-2:-4:-1]
'dc'
字符串判断是不是副串在主串之中:
in not in
#!/usr/bin/env python
#coding=utf-8
a=raw_input("input master str:")
b=raw_input("input slave str:")
if b in a:
print "this word belong to the str so that`s true"
else:
print "this word is not belong to the str so that`s false"
输出20组相同的字符串
print "@"*20
字符串的操作:
a="172848236487"
max(a)
min(a)
b="374673648"
cmp (str1,str2)
元组
元组的定义:
- 定义空元组 tuple = ()
- 定义单个值的元组 tuple = (fentiao,)
- 一般的元组 tuple = (fentiao, 8, male)
为什么需要元组?
>>> userinfo1 = "fentiao 4 male"
>>> userinfo2 = "westos 10 unknown"
>>> userinfo1[:7]
'fentiao'
>>> userinfo2[:6]
'westos'
字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组与列表这两个数据类型
>>> t1 = ("fentiao",4,"male")
>>> t2 = ("westos", 10, "unknown")
>>> type(t1)
<type 'tuple'>
>>> type(t2)
<type 'tuple'>
>>> t1[0]
'fentiao'
>>> t2[0]
'westos'
>>> t2[0:2]
('westos', 10)
不能对元组的值任意更改
>>> t1
('fentiao', 4, 'male')
>>> t1[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
t1.index(1) ##查找1在元组中出现第一次的位置
t1.index(1,4,9) ##从元组4到9中查找1第一次出现的位置
t1.conut(1) ##1在元组中出现的次数
对元组分别赋值,引申对多个变量也可通过元组方式分别赋值
>>> t1
('fentiao', 4, 'male')
>>> name,age,gender=t1
>>> print name,age,gender
fentiao 4 male
>>> a,b,c=(1,2,3)
>>> print a,b,c
1 2 3
注意:
- C语言中,定义一类型,必须先开辟一存储空间,当后期重新赋值时也一定是整型的;
- python中,先在内存上存储数据后,再通过标签去引用。不同的字符串占用不同的存储空间。
>>> str1
'12345'
>>> id(str1)
140205776037520
>>> str1 = "abcde"
>>> id(str1)
140205776037424
>>> str2 = "12345"
>>> id(str2)
140205776037520
列表
li.append ##添加
li.extend ##扩展
In [60]: li
Out[60]: ['yiyi', 21, 'ice', 2, 4, 9, 4, 9, 4, [1, 2, 3, 4]]
In [61]: li.extend([1,2,3,4])
In [62]: li
Out[62]: ['yiyi', 21, 'ice', 2, 4, 9, 4, 9, 4, [1, 2, 3, 4], 1, 2, 3, 4]
li.insert(index, object) ##在index前面插入object
li.remove(object) ##删除元素
li.sort ##排序
li.count(object) ##object在列表中总共出现的次数
li.index(object) ##object在列表中出现第一次的位置
li.pop ##将最后一个元素弹出,也可以加入索引
li.reverse ##将列表反转
列表的定义:
list = ["fentiao", 4, gender]
列表是可变类型的序列,而元组与字符串是不可变类型的序列
>>> list1 = ["fentiao", 4, "male"]
>>> type(list1)
<type 'list'>
>>> list1[1]
4
>>> list1[1] = 5
>>> list1
['fentiao', 5, 'male']
列表的操作:理解"对象=属性+方法"与类
>>> list1
['fendai', 5, 'male']
- 取值:索引和切片
>>> list1[0]
'fentiao'
- 添加:list.append()
>>> list1[3] = "cat"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> list1.append('cat')
>>> list1
['fentiao', 5, 'male', 'cat']
- 删除:del(list[]), list.remove(list[])
方法一:
>>> list1.remove("cat")
>>> list1
['fendai', 5, 'male']
方法二:
>>> list1.remove(list1[3])
>>> list1
['fendai', 5, 'male']
方法三:
>>> del(list1[3])
>>> list1
['fendai', 5, 'male']
- 修改:list[]=x
>>> list1
['fentiao', 5, 'male', 'cat']
>>> id(list1)
140205776057408
>>> list1[0] = "fendai"
>>> id(list1)
140205776057408
- 查找:var in list
t=(1,2,3[1,2,3])
t[3][0]=9
**练习
打印1-100中所有的偶数
打印1-100中所有的奇数
for i in range(1,101)
if i%2 ==0:
print i
for i in range(1,101)
if i%2!=0
print i
集合
s1={1,2,3,4}
s2={1,2,3}
s1 - s2 ##差集
s1.difference(s2) ##差集
s1.difference_update(s2) ##差集并更新结果给s1
s1 & s2 ##并集
si.intersection(s2)
s1|s2 ##交集
s1.union(s2) ##交集
In [169]: s1.issubset(s2) ##s1是不是s2的子集
Out[169]: True
In [174]: s2.issuperset(s1) ##s2是不是s1的真子集
Out[174]: True
In [170]: s1.isdisjoint(s2) ##是不是有交集 因为是dis 所以返回的布尔值是反的
Out[170]: False
In [171]: s1
Out[171]: {1, 2, 3}
In [172]: s2
Out[172]: {1, 2, 3, 4}
s1.discard(9) ##删除没有的元素的时候不会报错 remove删除的时候会报错
s1.pop() ##随机弹出
字典
为什么需要字典类型?
>>> list1 = ["name", "age", "gender"]
>>> list2 = ["fentiao", 5, "male"]
>>> zip(list1, list2) //通过zip内置函数将两个列表结合,help(zip)
[('name', 'fentiao'), ('age', 5), ('gender', 'male')]
>>> list2[0] //在直接编程时,并不能理解第一个索引表示姓名
'fentiao'
>>> list2[name]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
故字典是python中唯一的映射类型,key-value(哈希表),字典对象是可变的,但key必须用不可变对象。
字典的定义:
- 简单字典创建
>>> dic = {"name":"fentiao", "age":5, "gender":"male"}
>>> dic[0] //不能通过索引提取value值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> dic["name"] //根据key找出value值
'fentiao'
- 内建方法:fromkeys
>>> ddict = {}.fromkeys(('username','password'),'fentiao')
//字典中的key有相同的value值,默认为None
>>> ddict
{'username': 'fentiao', 'password': 'fentiao'}
>>> ddict = {}.fromkeys(('username','password'),)
>>> ddict
{'username': None, 'password': None}
访问字典的值:
- 直接通过key访问
- 循环遍历
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao'}
>>> for k in dic:
... print k
...
gender
age
name
>>> for k in dic:
... print dic[k]
...
male
8
fentiao
- 使用迭代器
字典的key-value值添加:
>>> dic["kind"] = "cat"
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
字典的删除:
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
>>> dic.pop("kind") //弹出字典中key值为"kind"的元素并返回该key的元素
'cat'
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao'}
>>> dic.clear() //删除字典的所有元素
>>> dic
{}
>>> del dic //删除整个字典
>>> dic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dic' is not defined
字典的常用方法:
- dict.get() //如果key存在于字典中,返回对应value值
>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
>>> dic.get(3)
>>> dic.get("name")
'fentiao'
- dic.keys()
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
>>> dic.keys()
['gender', 'age', 'name', 'kind']
自己试试:
len(), hash()
dict.clear()
dict.fromkeys(seq, value=None)
dict.get()
dict.has_keys(), in, not in
dict.items()
dict.keys()
dict.pop()
dict.setdefault()
dict.update()
dict.values()
总结:
序列:列表, 元组, 字符串
序列的两个主要特点:
- 索引操作符
- 切片操作符
序列的基本操作:
len()
>>> str1
'abcde'
>>> len(str1)
5
+
>>> str2 = "hello"
>>> str1 + str2
'abcdehello'
* //某一元素重复几次
>>> str1*5
'abcdeabcdeabcdeabcdeabcde'
>>> "#" * 40
'########################################'
in //判断元素是否在序列中
not in //与in相反
>>> str1
'abcde'
>>> 'c' in str1
True
>>> 'f' in str1
False
注意: a与'a'不同, ‘a’代表字符a, 而a代表变量a,实质存放的数值为100
>>> a = 100
>>> 'a' in str1
True
>>> a in str1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
max()
min()
>>> str3 = '12345'
>>> max(str3)
'5'
>>> min(str3)
'1'
cmp(tuple1:tuple2)
>>> str1 = "12345"
>>> str2 = "12345"
>>> cmp(str1,str2)
0
>>> str2 = "12"
>>> cmp(str1,str2)
1
>>> cmp(str2,str1)
-1
python流程控制:
if结构
- if-else结构:
- if-elif-else结构:
- if条件表达式:
逻辑值(bool)用来表示诸如对与错,真与假,空与非空等概念,True与False.
逻辑运算符:and,or,not
for循环:让循环执行一定的次数,eg:遍历列表,字符串,元组
for iterating_var in sequence:
statements(s)
序列遍历的两种方式:
- 直接从序列中取值
- 通过序列的索引取值
字典遍历的两种方式:
- dic[key]
- 元组的拆分 key,value = dic,items()
while循环:
while expression:
statement(s)
跳出while循环的两种方式:
- 表达式
- 代码块跳出
while中的else语句块:当条件失败正常跳出循环时,执行的代码块
函数
- 目标:
实现一个小的工具集
排序
极值
- 使用函数的优点
降低编程难度
代码重用
- 函数的定义
def 函数名(参数列表):
函数体
- 参数
形参:定义函数时的变量名称
实参:调用函数时的变量名称
缺省参数/默认参数:def(x,y=1)
多类型传值:
向函数传元组和字典,
传值冗余:接收多个值,元组和字典
- 变量的作用域
局部变量:只能在函数内部使用的变量
全局变量:在整个程序中使用的变量
global:强制将局部变量转换为全局变量
- 函数返回值
return在一个函数中只执行一次,并结束函数的执行
- 匿名函数(lambda表达式): lambda 参数... : 返回值
省去定义函数的过程,让代码更加精简;
对于抽象的不再复用的函数,不需要考虑命名的问题
有些时候让代码更容易理解
>>> def f(x,y):
... return x*y
...
>>> f(2,3)
6
>>> g = lambda x,y : x*y
>>> g(2,3)
6
- lambda应用实例
reduce为逐次操作list里的每项,接收的参数为2个,最后返回值为1个结果。
递归调用
>>> reduce(lambda x,y : x*y, range(1,6))
120
- switch函数的实现(python本身不提供switch语句)
通过字典,dict.get("key")
- 常用内建函数
abs(), max(), min(), len(), divmod(), round()
callable() //函数是否可以被调用
isinstance() //某一对象是否为什么类型
cmp()
range() //快速生成一序列,返回序列
xrange() //快速生成一序列,返回一对象/生成器
类型转换:int(), float(), long(), complex(),
str(), list(), tuple(), hex(), oct(), chr(), ord()
string内置函数:
str.capitalize() //字符串首字母大写
str.replace("a", "b") //将字符串中的a替换为b
str.spilt(".",3) //以.为分隔符切割3次,类似于import string, string.spilt(str,".",3 )
序列处理函数:
len(), max(), min()
filter(fun or None, seq) //对序列做f函数的操作,将返回值为Ture的值保留
zip(seq1,seq2...) //遍历多个序列,返回最短的序列
map(fun or None, seq1, se2) //遍历多个序列并做运算,不够的序列用None填充
reduce()
**练习:
print filter(lambda x:x%3==0, range(1,101))
print map(lambda x:x*2+10, range(1,11))
print reduce(lambda x,y:x+y, range(1,101))
break,continue与pass:
练习:
1. 实现1+2+3+...+100
2. 实现阶乘
- c, c++, java, php, javascript, vb, c#...
- 任何的编程语言都是为了让计算机干活,
eg:下载音乐,电影,编辑一文档... 而cpu只认识机器指令
- 不同的编程语言,实现同一功能,编写代码量,差距很大
C >> python
- 代码少的代价是运行速度慢
真正软件开发时,除了编写代码之外,需要很多基本的已经写好的现成的东西,加快开发速度。因此高级语言通常会提供一个比较完善的基础代码库,可直接调用。eg:编写电子邮件客户端,有针对电子邮件协议的smtp库;针对桌面环境的GUI库。
1989年圣诞节期间龟叔"Guido van
Rossum"编写的编程语言。TIOBE排行榜,了解编程语言的大致流行程度。
#2. python可以做什么?
- 日常任务,小工具,eg:备份mp3,系统管理员需要的脚本任务
- 做网站,eg:YouTube,国内的豆瓣,Google,Yahoo
- 网络游戏的后台
- 爬虫
python不可以做什么?
- 操作系统只能用C语言编写
- 手机应用,IOS用Object-C, Android用Java
- 3D游戏,最好用C,C++
#3. 工欲善其事,必先利其器
- 命令行交互环境
- 简单的集成开发环境
Windows: http://www.python.org/ftp/python/2.7.9/python-2.7.9.msi
Linux: yum install python -y
Mac:自带python2.7(OS>10.8)
#4. python解释器
cpython
ipython:基于cpython,交互方式有所增强
pypy: 对代码进行动态编译,JIT技术(just-in-time compiler,即时编译器),显著提高代码执行速度。
Jpython: java平台上的python解释器,将python代码编译成java字节码执行。
IronPython: 直接将python代码编译成.net的字节码
#5. 第一个python程序
- 交互方式
- 文本编辑器
sublime
Notepad++
切记:绝对不能使用word(不是纯文本文件)和windows自带的记事本(在文件开始的地方加特殊字符0xefbbbf<16进制>UTF-8 BOM,有了前缀,程序自动判断它为utf-8格式,并按utf-8格式解析文本或字符串,否则,需要按照字符编码格式一个个去验证)
- 直接运行py文件
文件第一行: #!/usr/bin/env python
文件添加执行权限: chmod +x xx.py
如果脚本中有中文字符的话编辑会报错 所以我们要改变编码格式
#coding:utf-8 ##在脚本中随便加入其中的一行就行
#coding=utf-8
#encoding:utf-8
#encoding=uft-8
#-*-coding:utf-8-*-
#6. 输入与输出
##6-1. 输出: 告诉用户程序执行的结果
print + 字符串... //字符串可为多个,逗号隔开
print + 数字|表达式
print 300
print '100 + 200 =',100 + 200
##6-2. 输入(raw_input): 告诉计算机程序所需的信息
name = raw_input()
print name
name = raw_input("嗨,哥们,输入你姓名呗:")
print "hello," name
#7. Python基础
- python是一种计算机编程语言,计算机需要根据编程语言保证程序不能有歧义,任何编程语言都有自己的一套语法,编译器或者解释器就负责把符合语法的程序代码转换成cpu能够识别的机器码,然后执行。
- python采用缩进方式
```
# print absolute value of an integer:
a = 100
if a >= 0:
print a
else:
print -a
```
#7-1. 变量
变量是内存中的一块区域。
变量的命名: 变量名由字母,数字,下划线组成。
>>> a=1
>>> print a
1
>>> a_1 = 111
>>> _a = 222
>>> print _a
222
>>> 1a = 111
File "<stdin>", line 1
1a = 111
^
SyntaxError: invalid syntax //范指语法错误,无效的语法
>>> a = 5
>>> b = 3
>>> print a + b
8
>>> print a + b +c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined //名称错误
变量的特性:
实际存储在内存上;
变量名最好见名知意;
变量可重新赋值;
>>> number1 = 1
>>> number2 = 2
>>> number1 + number2
3
python中地址变量与c语言刚好相反,一条数据包含包含多个标签;
>>> a = 1
>>> b = 1
>>> id(a)
10812520
>>> id(b)
10812520
**练习:
在交互模式中让python计算一月有多少分钟,使用变量DaysPerMonth(每月天数)、HoursPerDay(每天小时数)和MinutesPerHour(每小时分钟数),分别显示JanMintues(一月秒数)和AprMintues(四月秒数)。
#!/usr/bin/python
#coding=utf-8
a=int(raw_input("plase input one month days:"))
b=int(raw_input("plase input four month days:"))
hoursperday=24
minuteperhour=60
print "Janmintues=",a*hoursperday*minuteperhour
print "Aprmintues=",b*hoursperday*minuteperhour
~
##7-2. 运算符与表达式
赋值运算符:=, +=, -=, /=, *=, %=
算术运算符:+, -, *, /, //, %, **
>>> 1 + 1
2
>>> 1 - 1
0
>>> 1 * 3
3
>>> 1 / 2
0
>>> 1.0 / 2
0.5
>>> 1.0 // 2
0.0
>>> 1 % 2
1
>>> 2 ** 3
8
>>> a33 = 3 ** 3
>>> print a33
27
>>> print "a33=",a33
a33= 27
>>> print "a33 =",a33
a33 = 27
关系运算符: >, >=, <, <=, !=, ==
1 < 2,返回一个布尔类型的结果
>>> 1 < 2
True
>>> 1 > 2
False
逻辑运算符:逻辑与and, 逻辑或or, 逻辑非not
运算符的优先级:
eg: 8*4+2*3 a=2+5*3
**练习:
编写一四则表达式,(if语句实现) ###python里面不支持case语句
#!/bin/usr/env python
#coding=utf-8
a=int(raw_input("num1:"))
c=(raw_input("char1(+,-,*,/,%):"))
b=int(raw_input("num2:"))
if c=="+":
print "加法运算:",a+b
elif c=="-":
print "减法运算:",a-b
elif c=="*":
print "乘法运算:",a*b
elif c=="/":
print "除法运算:",a/b
elif c=="%":
print "取余运算:",a%b
else:
print "erron"
##7-3. 数据类型
案例: 123和“123”一样么?
从数字角度讲
从程序语言的识别来讲
>>> a = 123
>>> stra = "123"
>>> a == stra
False
>>> print a
123
>>> print stra
123
>>> a + stra
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
数字:
整型
>>> num1 = 123
>>> type(num1)
<type 'int'>
>>> type(123)
<type 'int'>
长整形
>>> num2 = 999999999999999
>>> type(num2)
<type 'int'>
强制定义为长整型: num3 = 123L
>>> num3 = 123L
>>> type(num3)
<type 'long'>
浮点型:表示小数
>>> f1 = 12
>>> type(f1)
<type 'int'>
>>> f2 = 12.0
>>> type(f2)
<type 'float'>
复数类型:python对复数提供内嵌支持,eg: 3.14j, 8.32e-36j
>>> c = 3.14
>>> type(c)
<type 'float'>
>>> c = 3.14j
>>> type(c)
<type 'complex'>
字符串: 常用三种定义方式
>>> str1 = 'our company is westos'
>>> str2 = "our company is westos"
>>> str3 = """our company is westos"""
>>> type(str1)
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
>>> say = 'let\'s go'
>>> say
"let's go"
>>> say = "let's go "
>>> say
"let's go "
**转义符号
>>> mail = "tom: hello i am westos "
>>> print mail
tom: hello i am westos
>>> mail = "tom:\n hello\n i am westos "
>>> print mail
tom:
hello
i am westos
**三重引号
其他用法:
注释
函数的doc文档
>>> mail = """tom:
... i am jack
... good luck
... """
>>> print mail
tom:
i am jack
good luck
'tom:\n\ti am jack\n\tgood luck\n'
**字符串索引取出相应的值
>>> a = 'abcde'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[3]
'd'
>>> a[0]+a[1]
'ab'
>>> a[0]+a[2]
'ac'
**切片
>>> a
'abcde'
>>> a[1:5:2]
'bd'
>>> a[1:5] //代表切片取出第2个到第4个
'bcde'
>>> a[:5]
'abcde'
>>> a[4:]
'e'
>>> a[4:1] //python中默认是从左向右取值
''
>>> a[4:1:-1] //当步长为-1时,从右向左取值
'edc'
>>> a[:]
'abcde'
>>> a[-1]
'e'
>>> a[-4:-1] //代表倒数第2个到倒数第4个切片
'bcd'
>>> a[-2:-4]
''
>>> a[-2:-4:1]
''
>>> a[-2:-4:-1]
'dc'
字符串判断是不是副串在主串之中:
in not in
#!/usr/bin/env python
#coding=utf-8
a=raw_input("input master str:")
b=raw_input("input slave str:")
if b in a:
print "this word belong to the str so that`s true"
else:
print "this word is not belong to the str so that`s false"
输出20组相同的字符串
print "@"*20
字符串的操作:
a="172848236487"
max(a)
min(a)
b="374673648"
cmp (str1,str2)
元组
元组的定义:
- 定义空元组 tuple = ()
- 定义单个值的元组 tuple = (fentiao,)
- 一般的元组 tuple = (fentiao, 8, male)
为什么需要元组?
>>> userinfo1 = "fentiao 4 male"
>>> userinfo2 = "westos 10 unknown"
>>> userinfo1[:7]
'fentiao'
>>> userinfo2[:6]
'westos'
字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组与列表这两个数据类型
>>> t1 = ("fentiao",4,"male")
>>> t2 = ("westos", 10, "unknown")
>>> type(t1)
<type 'tuple'>
>>> type(t2)
<type 'tuple'>
>>> t1[0]
'fentiao'
>>> t2[0]
'westos'
>>> t2[0:2]
('westos', 10)
不能对元组的值任意更改
>>> t1
('fentiao', 4, 'male')
>>> t1[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
t1.index(1) ##查找1在元组中出现第一次的位置
t1.index(1,4,9) ##从元组4到9中查找1第一次出现的位置
t1.conut(1) ##1在元组中出现的次数
对元组分别赋值,引申对多个变量也可通过元组方式分别赋值
>>> t1
('fentiao', 4, 'male')
>>> name,age,gender=t1
>>> print name,age,gender
fentiao 4 male
>>> a,b,c=(1,2,3)
>>> print a,b,c
1 2 3
注意:
- C语言中,定义一类型,必须先开辟一存储空间,当后期重新赋值时也一定是整型的;
- python中,先在内存上存储数据后,再通过标签去引用。不同的字符串占用不同的存储空间。
>>> str1
'12345'
>>> id(str1)
140205776037520
>>> str1 = "abcde"
>>> id(str1)
140205776037424
>>> str2 = "12345"
>>> id(str2)
140205776037520
列表
li.append ##添加
li.extend ##扩展
In [60]: li
Out[60]: ['yiyi', 21, 'ice', 2, 4, 9, 4, 9, 4, [1, 2, 3, 4]]
In [61]: li.extend([1,2,3,4])
In [62]: li
Out[62]: ['yiyi', 21, 'ice', 2, 4, 9, 4, 9, 4, [1, 2, 3, 4], 1, 2, 3, 4]
li.insert(index, object) ##在index前面插入object
li.remove(object) ##删除元素
li.sort ##排序
li.count(object) ##object在列表中总共出现的次数
li.index(object) ##object在列表中出现第一次的位置
li.pop ##将最后一个元素弹出,也可以加入索引
li.reverse ##将列表反转
列表的定义:
list = ["fentiao", 4, gender]
列表是可变类型的序列,而元组与字符串是不可变类型的序列
>>> list1 = ["fentiao", 4, "male"]
>>> type(list1)
<type 'list'>
>>> list1[1]
4
>>> list1[1] = 5
>>> list1
['fentiao', 5, 'male']
列表的操作:理解"对象=属性+方法"与类
>>> list1
['fendai', 5, 'male']
- 取值:索引和切片
>>> list1[0]
'fentiao'
- 添加:list.append()
>>> list1[3] = "cat"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> list1.append('cat')
>>> list1
['fentiao', 5, 'male', 'cat']
- 删除:del(list[]), list.remove(list[])
方法一:
>>> list1.remove("cat")
>>> list1
['fendai', 5, 'male']
方法二:
>>> list1.remove(list1[3])
>>> list1
['fendai', 5, 'male']
方法三:
>>> del(list1[3])
>>> list1
['fendai', 5, 'male']
- 修改:list[]=x
>>> list1
['fentiao', 5, 'male', 'cat']
>>> id(list1)
140205776057408
>>> list1[0] = "fendai"
>>> id(list1)
140205776057408
- 查找:var in list
t=(1,2,3[1,2,3])
t[3][0]=9
**练习
打印1-100中所有的偶数
打印1-100中所有的奇数
for i in range(1,101)
if i%2 ==0:
print i
for i in range(1,101)
if i%2!=0
print i
集合
s1={1,2,3,4}
s2={1,2,3}
s1 - s2 ##差集
s1.difference(s2) ##差集
s1.difference_update(s2) ##差集并更新结果给s1
s1 & s2 ##并集
si.intersection(s2)
s1|s2 ##交集
s1.union(s2) ##交集
In [169]: s1.issubset(s2) ##s1是不是s2的子集
Out[169]: True
In [174]: s2.issuperset(s1) ##s2是不是s1的真子集
Out[174]: True
In [170]: s1.isdisjoint(s2) ##是不是有交集 因为是dis 所以返回的布尔值是反的
Out[170]: False
In [171]: s1
Out[171]: {1, 2, 3}
In [172]: s2
Out[172]: {1, 2, 3, 4}
s1.discard(9) ##删除没有的元素的时候不会报错 remove删除的时候会报错
s1.pop() ##随机弹出
字典
为什么需要字典类型?
>>> list1 = ["name", "age", "gender"]
>>> list2 = ["fentiao", 5, "male"]
>>> zip(list1, list2) //通过zip内置函数将两个列表结合,help(zip)
[('name', 'fentiao'), ('age', 5), ('gender', 'male')]
>>> list2[0] //在直接编程时,并不能理解第一个索引表示姓名
'fentiao'
>>> list2[name]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
故字典是python中唯一的映射类型,key-value(哈希表),字典对象是可变的,但key必须用不可变对象。
字典的定义:
- 简单字典创建
>>> dic = {"name":"fentiao", "age":5, "gender":"male"}
>>> dic[0] //不能通过索引提取value值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> dic["name"] //根据key找出value值
'fentiao'
- 内建方法:fromkeys
>>> ddict = {}.fromkeys(('username','password'),'fentiao')
//字典中的key有相同的value值,默认为None
>>> ddict
{'username': 'fentiao', 'password': 'fentiao'}
>>> ddict = {}.fromkeys(('username','password'),)
>>> ddict
{'username': None, 'password': None}
访问字典的值:
- 直接通过key访问
- 循环遍历
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao'}
>>> for k in dic:
... print k
...
gender
age
name
>>> for k in dic:
... print dic[k]
...
male
8
fentiao
- 使用迭代器
字典的key-value值添加:
>>> dic["kind"] = "cat"
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
字典的删除:
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
>>> dic.pop("kind") //弹出字典中key值为"kind"的元素并返回该key的元素
'cat'
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao'}
>>> dic.clear() //删除字典的所有元素
>>> dic
{}
>>> del dic //删除整个字典
>>> dic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dic' is not defined
字典的常用方法:
- dict.get() //如果key存在于字典中,返回对应value值
>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
>>> dic.get(3)
>>> dic.get("name")
'fentiao'
- dic.keys()
>>> dic
{'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
>>> dic.keys()
['gender', 'age', 'name', 'kind']
自己试试:
len(), hash()
dict.clear()
dict.fromkeys(seq, value=None)
dict.get()
dict.has_keys(), in, not in
dict.items()
dict.keys()
dict.pop()
dict.setdefault()
dict.update()
dict.values()
总结:
序列:列表, 元组, 字符串
序列的两个主要特点:
- 索引操作符
- 切片操作符
序列的基本操作:
len()
>>> str1
'abcde'
>>> len(str1)
5
+
>>> str2 = "hello"
>>> str1 + str2
'abcdehello'
* //某一元素重复几次
>>> str1*5
'abcdeabcdeabcdeabcdeabcde'
>>> "#" * 40
'########################################'
in //判断元素是否在序列中
not in //与in相反
>>> str1
'abcde'
>>> 'c' in str1
True
>>> 'f' in str1
False
注意: a与'a'不同, ‘a’代表字符a, 而a代表变量a,实质存放的数值为100
>>> a = 100
>>> 'a' in str1
True
>>> a in str1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
max()
min()
>>> str3 = '12345'
>>> max(str3)
'5'
>>> min(str3)
'1'
cmp(tuple1:tuple2)
>>> str1 = "12345"
>>> str2 = "12345"
>>> cmp(str1,str2)
0
>>> str2 = "12"
>>> cmp(str1,str2)
1
>>> cmp(str2,str1)
-1
python流程控制:
if结构
- if-else结构:
- if-elif-else结构:
- if条件表达式:
逻辑值(bool)用来表示诸如对与错,真与假,空与非空等概念,True与False.
逻辑运算符:and,or,not
for循环:让循环执行一定的次数,eg:遍历列表,字符串,元组
for iterating_var in sequence:
statements(s)
序列遍历的两种方式:
- 直接从序列中取值
- 通过序列的索引取值
字典遍历的两种方式:
- dic[key]
- 元组的拆分 key,value = dic,items()
while循环:
while expression:
statement(s)
跳出while循环的两种方式:
- 表达式
- 代码块跳出
while中的else语句块:当条件失败正常跳出循环时,执行的代码块
函数
- 目标:
实现一个小的工具集
排序
极值
- 使用函数的优点
降低编程难度
代码重用
- 函数的定义
def 函数名(参数列表):
函数体
- 参数
形参:定义函数时的变量名称
实参:调用函数时的变量名称
缺省参数/默认参数:def(x,y=1)
多类型传值:
向函数传元组和字典,
传值冗余:接收多个值,元组和字典
- 变量的作用域
局部变量:只能在函数内部使用的变量
全局变量:在整个程序中使用的变量
global:强制将局部变量转换为全局变量
- 函数返回值
return在一个函数中只执行一次,并结束函数的执行
- 匿名函数(lambda表达式): lambda 参数... : 返回值
省去定义函数的过程,让代码更加精简;
对于抽象的不再复用的函数,不需要考虑命名的问题
有些时候让代码更容易理解
>>> def f(x,y):
... return x*y
...
>>> f(2,3)
6
>>> g = lambda x,y : x*y
>>> g(2,3)
6
- lambda应用实例
reduce为逐次操作list里的每项,接收的参数为2个,最后返回值为1个结果。
递归调用
>>> reduce(lambda x,y : x*y, range(1,6))
120
- switch函数的实现(python本身不提供switch语句)
通过字典,dict.get("key")
- 常用内建函数
abs(), max(), min(), len(), divmod(), round()
callable() //函数是否可以被调用
isinstance() //某一对象是否为什么类型
cmp()
range() //快速生成一序列,返回序列
xrange() //快速生成一序列,返回一对象/生成器
类型转换:int(), float(), long(), complex(),
str(), list(), tuple(), hex(), oct(), chr(), ord()
string内置函数:
str.capitalize() //字符串首字母大写
str.replace("a", "b") //将字符串中的a替换为b
str.spilt(".",3) //以.为分隔符切割3次,类似于import string, string.spilt(str,".",3 )
序列处理函数:
len(), max(), min()
filter(fun or None, seq) //对序列做f函数的操作,将返回值为Ture的值保留
zip(seq1,seq2...) //遍历多个序列,返回最短的序列
map(fun or None, seq1, se2) //遍历多个序列并做运算,不够的序列用None填充
reduce()
**练习:
print filter(lambda x:x%3==0, range(1,101))
print map(lambda x:x*2+10, range(1,11))
print reduce(lambda x,y:x+y, range(1,101))
break,continue与pass:
练习:
1. 实现1+2+3+...+100
2. 实现阶乘