Python实践基础

jopen 10年前

Python简介

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和Web编程。Python已经成为最受欢迎的程序设计语言之一。20111月,它被TIOBE编程语言排行榜评为2010年度语言。自从2004年以后,python的使用率是呈线性增长,一直稳居编程语言Top10

 

-- 摘自百度百科

 

Python安装

Python稳定的生产版本有2.73.3。考虑到3.3可能和一些第三方库不兼容,建议采用2.7作为生产版本。

下载

下载地址:http://www.python.org/getit/releases/2.7.6/

q1.png

环境变量配置

将Python安装目录添加到系统环境变量Path中去,结果如下图:

q2.png

Python基础

命令行工具

Python安装完成后,即可通过开始菜单启动Python命令行工具。

 

Python数据类型

Number(数字)         包括int,long,float,double,complex

String(字符串)        例如:hello,"hello",hello

List(列表)                 例如:[1,2,3],[1,2,3,[1,2,3],4]

Dictionary(字典)       例如:{1:"nihao",2:"hello"}

Set(集合)           例如:set([1,2])

Tuple(元组)            例如:(1,2,3,abc)

File(文件)                 例如:f =open(a.txt,rw)

 

命令行依次输入以下命令(或者在Python GUI下新建文件并运行):

# -*- coding: utf-8 -*-

a = 2

print(type(a))

print(a)

 

a = int("2")

print(type(a))

print(a)

 

a = 2.3

print(type(a))

print(a)

 

a = long(3.4)

print(type(a))

print(a)

 

a = "hello"

print(type(a))

print(a)

 

a = []

print(type(a))

print(a)

a = [1,"hello"]

print(a)

 

a = {1:"hello","name":"world"}

print(type(a))

print(a)

 

a = [1,2,3,3]

b = set(a)

print(type(b))

print(b)

 

a = (1,2)

type(a)

print(a)

a = (1)

print(type(a)) #结果是什么类型?

代码块

Python用缩进来定义一个代码块,类似于C语言中{}的功能。

Python支持Tab或空格缩进,但是应该避免两者混用。建议充分利用编辑器的Tab转换功能 ,比如设置编辑器自动将Tab转换成4个空格。

If 语句

标准if语句格式如下:

1)

if expression:

    if_suite

2)

if expression:

    if_suite

else:

    else_suite

3)

if expression1:

    if_suite

elif expression2:

    elif_suite

else:

    else_suite

 

示例:

a = 1

if (a>1):

    print(“yes”)

else:

    print(“no”)

 

While 循环

while expression:

    while_suite

 

For循环

有别于传统C语言中的for循环,更类似于C#的foreach。比如:

a = [1,2,3]

for b in a

    print(b)

 

文件操作

Python文件操作功能非常强大而简单,比如:

handle =open(r”c:\example.txt”, “r”)

data =handle.readlines()

handle.close()

for line in data:

print(line)

异常处理

try
    语句块
Except 异常类型1, 异常1
    语句块
Except 异常类型2
    语句块
Else
    语句快
Finally
    语句块

 

比如:

#-*- coding: utf-8 -*-

try:

    f_name =r"c:\temp\botovatest_sent.xml"

    f = open(f_name, "r")

    for line in f:

        print(line)

    f.close();

except IOError, e:

    print("文件操作异常:" + e.strerror)

else:

    print("未知错误")

finally:   

    print("over")

 

其中:

不带异常类型的except泛指所以类型的异常。

else块不是必须的。

finnaly块不是必须的。

 

函数

定义和调用

定义和调用函数的格式如下:

# -*- coding: utf-8 -*-

# 定义函数

def add (x,y):

    'apply + operation to argument'

   

    return (x + y)

 

#调用函数

print(add(1,2))

默认参数

以下调用结果将输出“5”。

# -*- coding: utf-8 -*-

# 定义函数

def add (x,y=2):

    'apply + operation to argument'   

    return (x + y)

 

#调用函数

print(add(3))

 

注意:避免使用可变类型的参数默认值,比如list,dictionary。

deffunction(data=[]): 

    data.append(1) 

    return data

 

print(function())

print(function())

print(function())

 

输出结果为:

[1]

[1, 1]

[1, 1, 1]

 

参考:http://www.cnblogs.com/congbo/archive/2012/11/20/2777031.html

可变数量参数

1)一个星号的参数

def funcD(a, b, *c):

  print a

  print b

  print "length of c is: %d " %len(c)

  print c

 

funcD(1, 2, 3, 4, 5, 6)

 

输出 结果为:

1

2

length of c is: 4

(3, 4, 5, 6)

 

2)两个星号的参数

def funcD(a, b, **c):

  print a

  print b

  print "length of c is: %d " %len(c)

  print c

  print type(c)

 

funcD(1, 2, c=1,d=2)

输出结果为:

1

2

length of c is: 2

{'c': 1, 'd': 2}

<type 'dict'>

与Java或其他语言中的定义相似,用于封装数据和操作,便于复用。

模块

Python中一个模块可理解为一个文件,其中定义了一些函数和变量。导入模块后即可复用这些函数和变量。

 

假设m1.py文件内容如下:

def func(a, b):

  print a

  print b 

 

则如果需要在m2.py中调用m1.py中的func函数,可以编辑m2内容如下:

import m1

m1.func(1,2)

 

或者:

from m1 import func

func(1,2)

 

或者:

from m1 import *

func(1,2)

 

注意:尽量不要使用import *。

把一组相关的模块放在同一目录下,再加上__init__.py文件就构成了一个包。