python学习第二讲
来源:互联网 发布:欧洲旅游机票软件 编辑:程序博客网 时间:2024/05/22 10:35
在python的代码编写中,很是讲究缩进
迭代:
In [2]: c = iter({1,3,2,4,6,5})
In [8]: c.next()
Out[8]: 1
In [9]: c.next()
Out[9]: 2
In [10]: c.next()
Out[10]: 3
In [11]: c.next()
Out[11]: 4
In [12]: c.next()
Out[12]: 5
In [13]: c.next()
Out[13]: 6
In [14]: c.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-14-50b4dad19337> in <module>()
----> 1 c.next()
StopIteration:
字典:
In [35]: dic = {"name":"jet","sex":"man","age":18}
In [36]: dic.keys
Out[36]: <function keys>
In [37]: dic.keys()
Out[37]: ['age', 'name', 'sex']
In [38]: dic.values()
Out[38]: [18, 'jet', 'man']
In [39]: dic.it
dic.items dic.iteritems dic.iterkeys dic.itervalues
In [39]: dic.items()
Out[39]: [('age', 18), ('name', 'jet'), ('sex', 'man')]
In [40]: for k,v in dic.ite
dic.items dic.iteritems dic.iterkeys dic.itervalues
In [40]: for k,v in dic.items():
....: print "项目:%s 数值:%s" %(k,v)
....:
项目:age 数值:18
项目:name 数值:jet
项目:sex 数值:man
#############################
In [16]: dic
Out[16]: {'age': 18, 'name': 'jet', 'sex': 'man'}
In [10]: a = dic.iterkeys()
In [12]: a.next()
Out[12]: 'age'
In [13]: a.next()
Out[13]: 'name'
In [14]: a.next()
Out[14]: 'sex'
In [15]: a.next()
In [17]: b=dic.itervalues()
In [18]: b.next()
Out[18]: 18
In [19]: b.next()
Out[19]: 'jet'
In [20]: b.next()
Out[20]: 'man'
In [28]: dic
Out[28]: {'age': 18, 'name': 'jet', 'sex': 'man'}
In [29]: de
%%debug %debug def del delattr
In [29]: del
del delattr
In [29]: del dic["sex"]
In [30]: dic
Out[30]: {'age': 18, 'name': 'jet'}
In [31]: dic.po
dic.pop dic.popitem
In [31]: dic.pop("age")
Out[31]: 18
In [32]: dic
Out[32]: {'name': 'jet'}
2.python流程控制:
if结构
- if-else结构:
- if-elif-else结构:
- if条件表达式:
逻辑值(bool)用来表示诸如对与错,真与假,空与非空等概念,True与False.
逻辑运算符:and,or,not
example:
#!/usr/bin/env python
#coding=utf-8
a=2
b=3
if a>b:
print "max:%s" %a
else:
print "max:%s" %b
for循环:让循环执行一定的次数
for iterating_var in sequence:
statements(s)
序列遍历的两种方式:
- 直接从序列中取值
- 通过序列的索引取值
字典遍历的两种方式:
- dic[key]
- 元组的拆分 key,value = dic,items()
example:
#!/usr/bin/env python
#coding=utf-8
for i in range(3):
a=raw_input("q or e")
if a == "q":
break
elif a == "e":
continue
elif a == "n":
pass
else:
print "xiababa"
else:
print "error string"
while循环:
while expression:
statement(s)
跳出while循环的两种方式:
- 表达式
- 代码块跳出
while中的else语句块:当条件失败正常跳出循环时,执行的代码块
example:
while 1:
num=raw_input("plese input q or c(w is quit):")
if num == 'q':
print "your choice:%s" %num
elif num == 'c':
print "your choice:%s" %num
elif num == 'w':
break
else:
print "error string"
测试结果:
plese input q or c(w is quit):q
your choice:q
plese input q or c(w is quit):c
your choice:c
plese input q or c(w is quit):w
example2;
#!/usr/bin/env python
#coding=utf-8
count=input("请输入需要统计几人姓名:")
li = []
i = 0
while i < (count):
i +=1
name=raw_input("姓名:")
end=len(name)-1
numdouhao=name.count(",")
if "," in name:
if (name[0] != ",") and (name[end] != ","):
if (numdouhao == 1):
li.append(name)
else:
print "你的输入出现多个逗号,请确认(姓,名)"
else:
print "你的逗号出现在首端或尾端,请确认(姓,名)"
else:
print "请按照正确格式输入(姓,名)"
else:
print sorted(li)
3.函数
- 目标:
实现一个小的工具集
排序
极值
- 使用函数的优点
降低编程难度
代码重用
- 函数的定义
def 函数名(参数列表):
函数体
- 参数
形参:定义函数时的变量名称
实参:调用函数时的变量名称
缺省参数/默认参数:def(x,y=1)
多类型传值:
向函数传元组和字典,
传值冗余:接收多个值,元组和字典
In [4]: def cp():
...: print "this is cp()"
...:
In [5]: cp()
this is cp()
- 变量的作用域
局部变量:只能在函数内部使用的变量
全局变量:在整个程序中使用的变量
global:强制将局部变量转换为全局变量
a = 1
b = 2
def cp():
a = 3
print "a=%d" %a
print "b=%d" %b
cp()
测试结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/笔记.py
a=3 ##局部变量
b=2 ##全局变量
- 函数返回值
return在一个函数中只执行一次,并结束函数的执行
In [6]: def add(x,y):
...: return x+y
...:
In [7]: add(2,4)
Out[7]: 6
- 匿名函数(lambda表达式): lambda 参数... : 返回值
省去定义函数的过程,让代码更加精简;
对于抽象的不再复用的函数,不需要考虑命名的问题
有些时候让代码更容易理解
In [8]: g=lambda x,y : x+y
In [9]: g(2,3)
Out[9]: 5
- switch函数的实现(python本身不提供switch语句)
通过字典,dict.get("key")
example:四则运算
#!/usr/bin/env python
#coding=utf-8
num1=int(raw_input("请输入第一个数字:"))
oper=raw_input("运算符:")
num2=int(raw_input("第二个数字:"))
dic={"+":num1+num2,"-":num1-num2,"*":num1*num2,"/":num1/num2}
print "%s%s%s=%s" %(num1,oper,num2,dic[oper])
- 常用内建函数
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()
迭代:
In [2]: c = iter({1,3,2,4,6,5})
In [8]: c.next()
Out[8]: 1
In [9]: c.next()
Out[9]: 2
In [10]: c.next()
Out[10]: 3
In [11]: c.next()
Out[11]: 4
In [12]: c.next()
Out[12]: 5
In [13]: c.next()
Out[13]: 6
In [14]: c.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-14-50b4dad19337> in <module>()
----> 1 c.next()
StopIteration:
字典:
In [35]: dic = {"name":"jet","sex":"man","age":18}
In [36]: dic.keys
Out[36]: <function keys>
In [37]: dic.keys()
Out[37]: ['age', 'name', 'sex']
In [38]: dic.values()
Out[38]: [18, 'jet', 'man']
In [39]: dic.it
dic.items dic.iteritems dic.iterkeys dic.itervalues
In [39]: dic.items()
Out[39]: [('age', 18), ('name', 'jet'), ('sex', 'man')]
In [40]: for k,v in dic.ite
dic.items dic.iteritems dic.iterkeys dic.itervalues
In [40]: for k,v in dic.items():
....: print "项目:%s 数值:%s" %(k,v)
....:
项目:age 数值:18
项目:name 数值:jet
项目:sex 数值:man
#############################
In [16]: dic
Out[16]: {'age': 18, 'name': 'jet', 'sex': 'man'}
In [10]: a = dic.iterkeys()
In [12]: a.next()
Out[12]: 'age'
In [13]: a.next()
Out[13]: 'name'
In [14]: a.next()
Out[14]: 'sex'
In [15]: a.next()
In [17]: b=dic.itervalues()
In [18]: b.next()
Out[18]: 18
In [19]: b.next()
Out[19]: 'jet'
In [20]: b.next()
Out[20]: 'man'
In [28]: dic
Out[28]: {'age': 18, 'name': 'jet', 'sex': 'man'}
In [29]: de
%%debug %debug def del delattr
In [29]: del
del delattr
In [29]: del dic["sex"]
In [30]: dic
Out[30]: {'age': 18, 'name': 'jet'}
In [31]: dic.po
dic.pop dic.popitem
In [31]: dic.pop("age")
Out[31]: 18
In [32]: dic
Out[32]: {'name': 'jet'}
2.python流程控制:
if结构
- if-else结构:
- if-elif-else结构:
- if条件表达式:
逻辑值(bool)用来表示诸如对与错,真与假,空与非空等概念,True与False.
逻辑运算符:and,or,not
example:
#!/usr/bin/env python
#coding=utf-8
a=2
b=3
if a>b:
print "max:%s" %a
else:
print "max:%s" %b
for循环:让循环执行一定的次数
for iterating_var in sequence:
statements(s)
序列遍历的两种方式:
- 直接从序列中取值
- 通过序列的索引取值
字典遍历的两种方式:
- dic[key]
- 元组的拆分 key,value = dic,items()
example:
#!/usr/bin/env python
#coding=utf-8
for i in range(3):
a=raw_input("q or e")
if a == "q":
break
elif a == "e":
continue
elif a == "n":
pass
else:
print "xiababa"
else:
print "error string"
while循环:
while expression:
statement(s)
跳出while循环的两种方式:
- 表达式
- 代码块跳出
while中的else语句块:当条件失败正常跳出循环时,执行的代码块
example:
while 1:
num=raw_input("plese input q or c(w is quit):")
if num == 'q':
print "your choice:%s" %num
elif num == 'c':
print "your choice:%s" %num
elif num == 'w':
break
else:
print "error string"
测试结果:
plese input q or c(w is quit):q
your choice:q
plese input q or c(w is quit):c
your choice:c
plese input q or c(w is quit):w
example2;
#!/usr/bin/env python
#coding=utf-8
count=input("请输入需要统计几人姓名:")
li = []
i = 0
while i < (count):
i +=1
name=raw_input("姓名:")
end=len(name)-1
numdouhao=name.count(",")
if "," in name:
if (name[0] != ",") and (name[end] != ","):
if (numdouhao == 1):
li.append(name)
else:
print "你的输入出现多个逗号,请确认(姓,名)"
else:
print "你的逗号出现在首端或尾端,请确认(姓,名)"
else:
print "请按照正确格式输入(姓,名)"
else:
print sorted(li)
3.函数
- 目标:
实现一个小的工具集
排序
极值
- 使用函数的优点
降低编程难度
代码重用
- 函数的定义
def 函数名(参数列表):
函数体
- 参数
形参:定义函数时的变量名称
实参:调用函数时的变量名称
缺省参数/默认参数:def(x,y=1)
多类型传值:
向函数传元组和字典,
传值冗余:接收多个值,元组和字典
In [4]: def cp():
...: print "this is cp()"
...:
In [5]: cp()
this is cp()
- 变量的作用域
局部变量:只能在函数内部使用的变量
全局变量:在整个程序中使用的变量
global:强制将局部变量转换为全局变量
a = 1
b = 2
def cp():
a = 3
print "a=%d" %a
print "b=%d" %b
cp()
测试结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/笔记.py
a=3 ##局部变量
b=2 ##全局变量
- 函数返回值
return在一个函数中只执行一次,并结束函数的执行
In [6]: def add(x,y):
...: return x+y
...:
In [7]: add(2,4)
Out[7]: 6
- 匿名函数(lambda表达式): lambda 参数... : 返回值
省去定义函数的过程,让代码更加精简;
对于抽象的不再复用的函数,不需要考虑命名的问题
有些时候让代码更容易理解
In [8]: g=lambda x,y : x+y
In [9]: g(2,3)
Out[9]: 5
- switch函数的实现(python本身不提供switch语句)
通过字典,dict.get("key")
example:四则运算
#!/usr/bin/env python
#coding=utf-8
num1=int(raw_input("请输入第一个数字:"))
oper=raw_input("运算符:")
num2=int(raw_input("第二个数字:"))
dic={"+":num1+num2,"-":num1-num2,"*":num1*num2,"/":num1/num2}
print "%s%s%s=%s" %(num1,oper,num2,dic[oper])
- 常用内建函数
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()
0 0
- python学习第二讲
- C++学习 第二讲
- Java学习,第二讲
- swift 学习第二讲
- 机器学习 第二讲
- 机器学习 - 第二讲
- Python第二讲基本数据类型
- 斯坦福大学-机器学习20讲-第二讲
- ng 机器学习第二讲
- Java SE 学习 第二讲
- spring学习总结-第二讲
- springmvc4开发学习(第二讲)
- vueJs第二讲学习笔记
- java基础学习第二讲
- python学习第三讲
- python学习第四讲
- RNN学习第二讲-通过Python,numpy 和 theano实现一个RNN网络
- PYTHON第二讲:输入基本控制结构
- Android基础总结——进程优先级及提高优先级的方法
- C++ ofstream和ifstream详细用法
- Windows has triggered a breakpoint
- cvpr常用资源整理
- Android图文混排
- python学习第二讲
- java.lang.OutOfMemoryError: PermGen space及其解决方法
- 一个在黑客界引起轰动的菜鸟教材---跟我学编程系列
- 开发模式、代码分层结构
- Android重力感应开发
- $.json $.each $.getJSON的使用
- 基于DragonBoard 410c的家庭智能环保卫士——(11)室内栅格地图位置更新Python实现
- iOS笔记—对象的结构体属性单个修改方式
- 算法训练 字串统计