假定你期望学习Python这门言语,却苦于找不到一个简略而全面的入门教程。那么本教程将花费十分钟的时刻带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因而只会包括一些根本概念。很显然,假如你期望真实学好一门言语,你仍是需求亲自动手实践的。在此,我会假定你已经有了必定的编程根底,因而我会越过大部分非Python言语的相关内容。本文将高亮显现重要的关键字,以便你可以很简单看到它们。别的需求留意的是,由于本教程篇幅有限,有许多内容我会直接运用代码来阐明加以少量注释。

Python的言语特性

Python是一门具有强类型(即变量类型是强制要求的)、动态性、隐式类型(不需求做变量声明)、大小写灵敏(var和VAR代表了不同的变量)以及面向方针(全部皆为方针)等特色的编程言语。

获取协助

你可以很简单的经过Python解说器获取协助。假如你想知道一个方针(object)是怎么作业的,那么你所需求做的便是调用help()!别的还有一些有用的办法,dir()会显现该方针的一切办法,还有.__doc__会显现其文档:

>>> help(5)

Help on int object:

(etc etc)

>>> dir(5)

['__abs__', '__add__', ...]

>>> abs.__doc__

'abs(number) -> number

Return the absolute value of the argument.'

语法

Python中没有强制的句子停止字符,且代码块是经过缩进来指示的。缩进表明一个代码块的开端,逆缩进则表明一个代码块的完毕。声明以冒号(:)字符完毕,而且敞开一个缩进等级。单行注释以井号字符(#)最初,多行注释则以多行字符串的办法呈现。赋值(事实上是将方针绑定到姓名)经过等号(“=”)完成,双等号(“==”)用于持平判别,”+=”和”-=”用于增加/削减运算(由符号右边的值确认增加/削减的值)。这适用于许多数据类型,包括字符串。你也可以在一行上运用多个变量。例如:

>>> myvar = 3

>>> myvar += 2

>>> myvar

5

>>> myvar -= 1

>>> myvar

4

"""This is a multiline comment.

The following lines concatenate the two strings."""

>>> mystring = "Hello"

>>> mystring += " world."

>>> print mystring

Hello world.

# This swaps the variables in one line(!).

# It doesn't violate strong typing because values aren't

# actually being assigned, but new objects are bound to

# the old names.

>>> myvar, mystring = mystring, myvar

数据类型

Python具有列表(list)、元组(tuple)和字典(dictionaries)三种根本的数据结构,而调集(sets)则包括在调集库中(但从Python2.5版别开端正式成为Python内建类型)。列表的特色跟一维数组相似(当然你也可以创立相似多维数组的“列表的列表”),字典则是具有相关联系的数组(一般也叫做哈希表),而元组则是不可变的一维数组(Python中“数组”可以包括任何类型的元素,这样你就可以运用混合元素,例如整数、字符串或是嵌套包括列表、字典或元组)。数组中第一个元素索引值(下标)为0,运用负数索引值可以从后向前拜访数组元素,-1表明最终一个元素。数组元素还能指向函数。来看下面的用法:

>>> sample = [1, ["another", "list"], ("a", "tuple")]

>>> mylist = ["List item 1", 2, 3.14]

>>> mylist[0] = "List item 1 again" # We're changing the item.

>>> mylist[-1] = 3.21 # Here, we refer to the last item.

>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}

>>> mydict["pi"] = 3.15 # This is how you change dictionary values.

>>> mytuple = (1, 2, 3)

>>> myfunction = len

>>> print myfunction(mylist)

3

你可以运用:运算符拜访数组中的某一段,假如:左面为空则表明从第一个元素开端,同理:右边为空则表明到最终一个元素完毕。负数索引则表明从后向前数的方位(-1是最终一个项目),例如:

>>> mylist = ["List item 1", 2, 3.14]

>>> print mylist[:]

['List item 1', 2, 3.1400000000000001]

>>> print mylist[0:2]

['List item 1', 2]

>>> print mylist[-3:-1]

['List item 1', 2]

>>> print mylist[1:]

[2, 3.14]

# Adding a third parameter, "step" will have Python step in

# N item increments, rather than 1.

# E.g., this will return the first item, then go to the third and

# return that (so, items 0 and 2 in 0-indexing).

>>> print mylist[::2]

['List item 1', 3.14]

字符串

Python中的字符串运用单引号(‘)或是双引号(“)来进行标明,而且你还可以在经过某一种标明的字符串中运用别的一种标明符(例如 “He said ‘hello’.”)。而多行字符串可以经过三个接连的单引号(”’)或是双引号(“””)来进行标明。Python可以经过u”This is a unicode string”这样的语法运用Unicode字符串。假如想经过变量来填充字符串,那么可以运用取模运算符(%)和一个元组。运用办法是在方针字符串中从左至右运用%s来指代变量的方位,或许运用字典来替代,示例如下:

>>>print "Name: %s

Number: %s

String: %s" % (myclass.name, 3, 3 * "-")

Name: Poromenos

Number: 3

String: ---

strString = """This is

a multiline

string."""

# WARNING: Watch out for the trailing s in "%(key)s".

>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}

This is a test.

流程操控

Python中可以运用if、for和while来完成流程操控。Python中并没有select,取而代之运用if来完成。运用for来枚举列表中的元素。假如期望生成一个由数字组成的列表,则可以运用range()函数。以下是这些声明的语法示例:

rangelist = range(10)

>>> print rangelist

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in rangelist:

# Check if number is one of

# the numbers in the tuple.

if number in (3, 4, 7, 9):

# "Break" terminates a for without

# executing the "else" clause.

break

else:

# "Continue" starts the next iteration

# of the loop. It's rather useless here,

# as it's the last statement of the loop.

continue

else:

# The "else" clause is optional and is

# executed only if the loop didn't "break".

pass # Do nothing

if rangelist[1] == 2:

print "The second item (lists are 0-based) is 2"

elif rangelist[1] == 3:

print "The second item (lists are 0-based) is 3"

else:

print "Dunno"

while rangelist[1] == 1:

pass

函数

函数经过“def”关键字进行声明。可选参数以调集的办法呈现在函数声明中并紧跟着必选参数,可选参数可以在函数声明中被赋予一个默认值。已命名的参数需求赋值。函数可以回来一个元组(运用元组拆包可以有用回来多个值)。Lambda函数是由一个独自的句子组成的特别函数,参数经过引证进行传递,但关于不可变类型(例如元组,整数,字符串等)则不可以被改动。这是由于只传递了该变量的内存地址,而且只要丢掉了旧的方针后,变量才干绑定一个方针,所以不可变类型是被替换而不是改动(译者注:尽管Python传递的参数办法本质上是引证传递,可是会发生值传递的效果)。例如:

# 效果等同于 def funcvar(x): return x + 1

funcvar = lambda x: x + 1

>>> print funcvar(1)

2

# an_int 和 a_string 是可选参数,它们有默认值

# 假如调用 passing_example 时只指定一个参数,那么 an_int 缺省为 2 ,a_string 缺省为 A default string。假如调用 passing_example 时指定了前面两个参数,a_string 仍缺省为 A default string。

# a_list 是必备参数,由于它没有指定缺省值。

def passing_example(a_list, an_int=2, a_string="A default string"):

a_list.append("A new item")

an_int = 4

return a_list, an_int, a_string

>>> my_list = [1, 2, 3]

>>> my_int = 10

>>> print passing_example(my_list, my_int)

([1, 2, 3, 'A new item'], 4, "A default string")

>>> my_list

[1, 2, 3, 'A new item']

>>> my_int

10

Python支撑有限的多承继办法。私有变量和办法可以经过增加至少两个前导下划线和最多跟随一个下划线的办法进行声明(如“__spam”,这仅仅常规,而不是Python的强制要求)。当然,咱们也可以给类的实例取恣意称号。例如:

class MyClass(object):

common = 10

def __init__(self):

self.myvariable = 3

def myfunction(self, arg1, arg2):

return self.myvariable

# This is the class instantiation

>>> classinstance = MyClass()

>>> classinstance.myfunction(1, 2)

3

# This variable is shared by all classes.

>>> classinstance2 = MyClass()

>>> classinstance.common

10

>>> classinstance2.common

10

# Note how we use the class name

# instead of the instance.

>>> MyClass.common = 30

>>> classinstance.common

30

>>> classinstance2.common

30

# This will not update the variable on the class,

# instead it will bind a new object to the old

# variable name.

>>> classinstance.common = 10

>>> classinstance.common

10

>>> classinstance2.common

30

>>> MyClass.common = 50

# This has not changed, because "common" is

# now an instance variable.

>>> classinstance.common

10

>>> classinstance2.common

50

# This class inherits from MyClass. The example

# class above inherits from "object", which makes

# it what's called a "new-style class".

# Multiple inheritance is declared as:

# class OtherClass(MyClass1, MyClass2, MyClassN)

class OtherClass(MyClass):

# The "self" argument is passed automatically

# and refers to the class instance, so you can set

# instance variables as above, but from inside the class.

def __init__(self, arg1):

self.myvariable = 3

print arg1

>>> classinstance = OtherClass("hello")

hello

>>> classinstance.myfunction(1, 2)

3

# This class doesn't have a .test member, but

# we can add one to the instance anyway. Note

# that this will only be a member of classinstance.

>>> classinstance.test = 10

>>> classinstance.test

10

反常

Python中的反常由 try-except [exceptionname] 块处理,例如:

def some_function():

try:

# Division by zero raises an exception

10 / 0

except ZeroDivisionError:

print "Oops, invalid."

else:

# Exception didn't occur, we're good.

pass

finally:

# This is executed after the code block is run

# and all exceptions have been handled, even

# if a new exception is raised while handling.

print "We're done with that."

>>> some_function()

Oops, invalid.

We're done with that.

导入

外部库可以运用 import [libname] 关键字来导入。一起,你还可以用 from [libname] import [funcname] 来导入所需求的函数。例如:

import random

from time import clock

randomint = random.randint(1, 100)

>>> print randomint

64

文件I / O

Python针对文件的处理有许多内建的函数库可以调用。例如,这儿演示了怎么序列化文件(运用pickle库将数据结构转换为字符串):

import pickle

mylist = ["This", "is", 4, 13327]

# Open the file C:binary.dat for writing. The letter r before the

# filename string is used to prevent backslash escaping.

myfile = open(r"C:binary.dat", "w")

pickle.dump(mylist, myfile)

myfile.close()

myfile = open(r"C:text.txt", "w")

myfile.write("This is a sample string")

myfile.close()

myfile = open(r"C:text.txt")

>>> print myfile.read()

'This is a sample string'

myfile.close()

# Open the file for reading.

myfile = open(r"C:binary.dat")

loadedlist = pickle.load(myfile)

myfile.close()

>>> print loadedlist

['This', 'is', 4, 13327]

其它杂项

  • 数值判别可以链接运用,例如 1<3 可以判别变量 a 是否在1和3之间。
  • 可以运用 del 删去变量或删去数组中的元素。
  • 列表推导式(List Comprehension)供给了一个创立和操作列表的有力东西。列表推导式由一个表达式以及紧跟着这个表达式的for句子构成,for句子还可以跟0个或多个if或for句子,来看下面的比如:

>>> lst1 = [1, 2, 3]

>>> lst2 = [3, 4, 5]

>>> print [x * y for x in lst1 for y in lst2]

[3, 4, 5, 6, 8, 10, 9, 12, 15]

>>> print [x for x in lst1 if 4 > x > 1]

[2, 3]

# Check if an item has a specific property.

# "any" returns true if any item in the list is true.

>>> any([i % 3 for i in [3, 3, 4, 4, 3]])

True

# This is because 4 % 3 = 1, and 1 is true, so any()

# returns True.

# Check how many items have this property.

>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)

2

>>> del lst1[0]

>>> print lst1

[2, 3]

>>> del lst1

  • 全局变量在函数之外声明,而且可以不需求任何特别的声明即能读取,但假如你想要修正全局变量的值,就有必要在函数开端之处用global关键字进行声明,不然Python会将此变量依照新的局部变量处理(请留意,假如不留意很简单被坑)。例如:

number = 5

def myfunc():

# This will print 5.

print number

def anotherfunc():

# This raises an exception because the variable has not

# been bound before printing. Python knows that it an

# object will be bound to it later and creates a new, local

# object instead of accessing the global one.

print number

number = 3

def yetanotherfunc():

global number

# This will correctly change the global.

number = 3

小结

本教程并未包括Python言语的全部内容(甚至连一小部分都称不上)。Python有十分多的库以及许多的功用特色需求学习,所以要想学好Python你有必要在此教程之外经过其它办法,例如阅览Dive into Python。我期望这个教程能给你一个很好的入门辅导。假如你觉得本文还有什么地方值得改善或增加,或是你期望可以了解Python的哪方面内容,请留言。(需求Python材料,转发私信小编“Python”)

推荐阅读