1:循环 range:range
返回一个序列的数。这个序列从第一个数开始到第二个数为止。例如,range(1,5)
给出序列[1,
2, 3, 4]
。默认地,range
的步长为1。如果我们为range
提供第三个数,那么它将成为步长。例如,range(1,5,2)
给出[1,3]
。记住,range 向上 延伸到第二个数,即它不包含第二个数。以冒号结束
例如:
for
i
in
range
(
1
,
5
):
print
i
else
:
print
'The for loop is over'
2:函数定义def 以冒号结束
例如:
def
printMax
(a,
b):
if
a > b:
print
a,
'is
maximum'
else
:
print
b,
'is
maximum'
3:使用外部变量 global:
global
语句被用来声明x
是全局的
使用
global
语句可以清楚地表明变量是在外面的块定义的
例如:
def
func
():
global
x
print
'x is'
,
x
x =
2
print
'Changed local x to'
,
x
x =
50
func()
print
'Value of x is'
,
x
输出:
x
is 50
Changed global x to 2
Value of x is 2
4:默认参数值:在函数定义的形参名后加上赋值运算符(=)和默认值,从而给形参指定默认参数值。
例如:
def
say
(message,
times =
1
):
print
message * times
重要
只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。
这是因为赋给形参的值是根据位置而赋值的。例如,def func(a, b=5)
是有效的,但是def
func(a=5, b)
是 无效 的。
另外一种赋值:
如果你的某个函数有许多参数,而你只想指定其中的一部分,那么你可以通过命名来为这些参数赋值——这被称作 关键参数 ——我们使用名字(关键字)而不是位置(我们前面所一直使用的方法)来给函数指定实参
这样做有两个 优势 ——一,由于我们不必担心参数的顺序,使用函数变得更加简单了。二、假设其他参数都有默认值,我们可以只给我们想要的那些参数赋值。
例如:
def
func
(a,
b=
5
, c=
10
):
print
'a is'
,
a,
'and b is'
, b,
'and
c is'
, c
func(
3
,
7
)
func(
25
,
c=
24
)
func(c=
50
,
a=
100
)
模块的__name__:引用时候走A和运行时候走B,控制程序流程5:
当一个模块被第一次输入的时候,这个模块的主块将被运行。假如我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,我们该怎么做呢?这可以通过模块的__name__属性完成
例如:
if
__name__
==
'__main__'
:
print
'This program is being
run by itself'
else
:
print
'I am being imported
from another module'
6:数据结构
Python中有三种内建的数据结构——列表、元组和字典
6.1 列表:可以增加字段可以排序,插入,删除
shoplist=['c2','a3','e4','b5']
6.2 元组:元组和字符串一样是 不可变的 即你不能修改元组
zoo
= (
'wolf'
,
'elephant'
,
'penguin'
)
//打印 %s 链接
age =
22
name =
'Swaroop'
print
'%s
is %d years old'
% (name, age)
print
'Why
is %s playing with that python?'
% name
6.3 字典:把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的
。
键值对在字典中以这样的方式标记:
d
= {key1 : value1, key2 : value2 }
。
注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
例如:
ab
= {
'Swaroop'
:
'swaroopch@byteofpython.info'
,
'Larry'
:
'larry@wall.org'
,
'Matsumoto'
:
'matz@ruby-lang.org'
,
'Spammer'
:
'spammer@hotmail.com'
}
//添加
ab[
'Guido'
]
=
'guido@python.org'
//删除
del
ab[
'Spammer'
]
//循环
for
name,
address
in
ab.items():
print
'Contact %s at %s'
%
(name, address)
if
'Guido'
in
ab:
#
OR ab.has_key('Guido')
print
"\nGuido's
address is %s"
% ab[
'Guido'
]