Python基础语法(2)

时间:2022-05-07
本文章向大家介绍Python基础语法(2),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、控制流

1. if 语句

i = 10
n = int(raw_input("enter a number:"))

if n == i:
    print "equal"
elif n < i:
    print "lower"
else:
    print "higher"

2. while语句

while True:
    pass
else:
    pass
#else语句可选,当while为False时,else语句被执行。 pass是空语句。

3. for 循环 for..in

for i in range(0, 5):
    print i
else:
    pass
# 打印0到4

  注:当for循环结束后执行else语句;

    range(a, b)返回一个序列,从a开始到b为止,但不包括b,range默认步长为1,可以指定步长,range(0,10,2);

4. break语句

    终止循环语句,如果从for或while中终止,任何对应循环的else将执行。

5. continue语句

    continue语句用来调过当前循环的剩余语句,然后继续下一轮循环。

二、函数

  函数通过def定义。def关键字后跟函数的标识符名称,然后跟一对圆括号,括号之内可以包含一些变量名,该行以冒号结尾;接下来是一块语句,即函数体。

def sumOf(a, b):
    return a + b

1. 函数形参

    函数中的参数名称为‘形参’,调用函数时传递的值为‘实参’

2. 局部变量

    在函数内定义的变量与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是局部的。这称为变量的作用域。

    global语句, 为定义在函数外的变量赋值时使用global语句。

def func():
    global x
    print "x is ", x
    x = 1

x = 3
func()
print x

#3
#1 

3. 默认参数

    通过使用默认参数可以使函数的一些参数是‘可选的’。

def say(msg, times =  1):
    print msg * times

say("peter")
say("peter", 3)

    注意:只有在形参表末尾的那些参数可以有默认参数值,即不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参,只是因为赋给形参的值是根据位置而赋值的。

4. 关键参数

    如果某个函数有很多参数,而现在只想指定其中的部分,那么可以通过命名为这些参数赋值(称为‘关键参数’)。

    优点:不必担心参数的顺序,使函数变的更加简单;假设其他参数都有默认值,可以只给我们想要的那些参数赋值。

def func(a, b=2, c=3):
    print "a is %s, b is %s, c is %s" % (a, b, c)

func(1) #a is 1, b is 2, c is 3
func(1, 5) #a is 1, b is 5, c is 3
func(1, c = 10) #a is 1, b is 2, c is 10
func(c = 20, a = 30) #a is 30, b is 2, c is 20

5. return 语句

    return语句用来从一个函数返回,即跳出函数。可从函数返回一个值。

    没有返回值的return语句等价于return None。None表示没有任何东西的特殊类型。

6. DocStrings (文档字符串)

def func():
    '''This is self-defined function

Do nothing'''
    pass

print func.__doc__

#This is self-defined function
#
#Do nothing

三、模块

  模块就是一个包含了所有你定义的函数和变量的文件,模块必须以.py为扩展名。模块可以从其他程序中‘输入’(import)以便利用它的功能。

  在python程序中导入其他模块使用'import', 所导入的模块必须在sys.path所列的目录中,因为sys.path第一个字符串是空串''即当前目录,所以程序中可导入当前目录的模块。

1. 字节编译的.pyc文件

    导入模块比较费时,python做了优化,以便导入模块更快些。一种方法是创建字节编译的文件,这些文件以.pyc为扩展名。

    pyc是一种二进制文件,是py文件经编译后产生的一种byte code,而且是跨平台的(平台无关)字节码,是有python虚拟机执行的,类似于

  java或.net虚拟机的概念。pyc的内容,是跟python的版本相关的,不同版本编译后的pyc文件是不同的。

2. from .. import

    如果想直接使用其他模块的变量或其他,而不加'模块名+.'前缀,可以使用from .. import。

    例如想直接使用sys的argv,from sys import argv 或 from sys import *

3. 模块的__name__

    每个模块都有一个名称,py文件对应模块名默认为py文件名,也可在py文件中为__name__赋值;如果是__name__,说明这个模块被用户

  单独运行。

4. dir()函数

    dir(sys)返回sys模块的名称列表;如果不提供参数,即dir(),则返回当前模块中定义名称列表。

    del -> 删除一个变量/名称,del之后,该变量就不能再使用。

四、数据结构

  python有三种内建的数据结构:列表、元组和字典。

1. 列表

    list是处理一组有序项目的数据结构,列表是可变的数据结构。列表的项目包含在方括号[]中,eg: [1, 2, 3], 空列表[]。判断列表中是否包含某项可以使用in, 比如 l = [1, 2, 3]; print 1 in l; #True;支持索引和切片操作;索引时若超出范围,则IndexError;使用函数len()查看长度;使用del可以删除列表中的项,eg: del l[0] # 如果超出范围,则IndexError

    list函数如下:

append(value)  ---向列表尾添加项value

l = [1, 2, 2]
l.append(3) #[1, 2, 2, 3]

count(value)  ---返回列表中值为value的项的个数

l = [1, 2, 2]
print l.count(2) # 2

extend(list2)  ---向列表尾添加列表list2

l = [1, 2, 2]
l1 = [10, 20]
l.extend(l1)
print l   #[1, 2, 2, 10, 20]

index(value, [start, [stop]])  ---返回列表中第一个出现的值为value的索引,如果没有,则异常 ValueError

l = [1, 2, 2]
a = 4
try:
    print l.index(a)
except ValueError, ve:
    print "there is no %d in list" % a

insert(i, value)  ---向列表i位置插入项vlaue,如果没有i,则添加到列表尾部

l = [1, 2, 2]

l.insert(1, 100)
print l #[1, 100, 2, 2]

l.insert(100, 1000)
print l #[1, 100, 2, 2, 1000]

pop([i])  ---返回i位置项,并从列表中删除;如果不提供参数,则删除最后一个项;如果提供,但是i超出索引范围,则异常IndexError

l = [0, 1, 2, 3, 4, 5]

print l.pop() # 5
print l #[0, 1, 2, 3, 4]

print l.pop(1) #1
print l #[0, 2, 3, 4]

try:
    l.pop(100)
except IndexError, ie:
    print "index out of range"

remove(value)  ---删除列表中第一次出现的value,如果列表中没有vlaue,则异常ValueError

l = [1, 2, 3, 1, 2, 3]

l.remove(2)
print l #[1, 3, 1, 2, 3]

try:
    l.remove(10)
except ValueError, ve:
    print "there is no 10 in list"

reverse()  ---列表反转

l = [1, 2, 3]
l.reverse()
print l #[3, 2, 1]

sort(cmp=None, key=None, reverse=False)  ---列表排序

【Python Library Reference】 cmp:cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: "cmp=lambda x,y: cmp(x.lower(), y.lower())" key:key specifies a function of one argument that is used to extract a comparison key from each list element: "key=str.lower" reverse:reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.

l5 = [10, 5, 20, 1, 30]
l5.sort()
print l5 #[1, 5, 10, 20, 30]

l6 = ["bcd", "abc", "cde", "bbb"]
l6.sort(cmp = lambda s1, s2: cmp(s1[0],s2[1]))
print l6 #['abc', 'bbb', 'bcd', 'cde']

l7 = ["bcd", "abc", "cde", "bbb", "faf"]
l7.sort(key = lambda s: s[1])
print l7 #['faf', 'abc', 'bbb', 'bcd', 'cde']