【转载】10分钟学会Python

原文:http://article.yeeyan.org/view/linghucong/1543?from_com

英语原文:http://www.poromenos.org/tutorials/python

 

 

1. 准备工作

哦,你是要学习Python编程语言但是又苦于找不到一个简洁但是全面的教程么?这个教程就是要试图在10分钟内让你掌握Python。可能它有点不像一个教程,或者说应该介于教程和cheatsheet[可以快速查找的一个简单表单,不知道怎么翻译,译注]之间,所以在这里我只能向你展示一些最基本的概念,旨在让你能够快速入门。显然,如果你真要学习一门编程语言,你需要使用它编码一段时间。我假定你已经有一些熟知的编程知识,因此在这里我就不再讲那些与语言无关的编程知识。教程中的关键字我都让它高亮显示,这样你就可以一眼就看清楚。另外,为了保持教程的简洁,一些知识就只在代码中展示,只有一些简单的注释。

2. 特性

Python是一个强类型(也就是类型都是强制指定的),动态,隐式类型的(即,你不需要声明变量),大小写敏感(var和VAR是两个不同的变量),面向对象(一切皆是对象)的语言。[专业术语翻译有点别扭,译注]

3. 语法

Python 没有命令结束标志,并且,使用缩进来区分程序块。块开始的时候缩进开始,块结束的时候缩进结束。声明需要一个:来引领一个缩进块。注释使用#开始并且只占一行。多行注释使用多行字符串。赋值使用等号(“=”),测试是否相等使用两个等号(“==”)。可以分别使用+=或者-=来增加或者减少变量值。这在多个数据结构上都适用,包括字符串。你也可以在一行上使用多个变量。举例来说:
>>> myvar = 3
>>> myvar += 2
>>> myvar -= 1
"""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(!).
>>> myvar, mystring = mystring, myvar

4. 数据类型

在Python中可用的数据类型有列表、元组以及字典。在集合库中集合也可用。列表就像是以维数组(但是你还可以有列表的列表),字典就是关联数组(或者叫哈希表),元组就是不可变一维数组(Python中数组可以是任何类型,因此你可以在列表、字典或者元组中混合使用数字、字符串等数据类型)。在所有的数组类型中第一个元素的标号都是0,负数表示从后向前数,-1则表示最后一个元素。变量可以指向函数。用法如下:
>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again"
>>> mylist[-1] = 3.14
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.14
>>> 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]
5. 字符串

字符串可以使用单引号或者双引号,你可以在使用一个引号的里面嵌套使用另一种引号(也就是说,"He said 'hello'."是合法的)。多行字符串则使用三引号(单双皆可)。Python还可以让你设置Unicode编码,语法如下:u"This is a unicode string".使用值填充一个字符串的时候可以使用%(取模运算符)和一个元组。每个%s使用元组中的一个元素替换,从左到右。你还可以使用字典。如下所示:
>>>print "Name: %snNumber: %snString: %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.
6. 流程控制

流程控制使用while,if,以及for。没有select[和哪种语言对比?不知道。译注],使用if代替。使用for来列举列表中的元素。要得到一个数字的列表,可以使用 range(<number>)。这些声明的语法如下:
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
7. 函数

函数使用def关键字。可选参数在必须参数之后出现,并且可以被赋一默认值。对命名参数而言,参数名参数名被赋一个值。函数可以返回一个元组(打开元组你就可以实现返回多个值)。Lanbda函数是个特例,它由一个表达式构成。参数使用引用传递,但是可变类型(元组,列表,数字,字符串等等)不能被改变。举例如下:

# arg2 and arg3 are optional, they have default values
# if one is not passed (100 and "test", respectively).
def myfunction(arg1, arg2 = 100, arg3 = "test"):
return arg3, arg2, arg1
 
>>>ret1, ret2, ret3 = myfunction("Argument 1", arg3 = "Named argument")
# Using "print" with multiple values prints them all, separated by a space.
>>> print ret1, ret2, ret3
Named argument 100 Argument 1
 
# Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
8. 类

Python部分支持类的多重继承。私有变量和方法可以使用至少两个"_"开始并且至少一个"_"结束来声明,比如"__spam"(这只是约定,语言中并没有强制规定)。我们可以给类的实例赋任意的变量。请看下例:
class MyClass:
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 create a new one on the class
# instance and assign the value to that.
>>> 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. Multiple
# inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
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
9. 异常处理

Python中的异常处理使用try-except [exceptionname]程序块:
def somefunction():
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Oops, invalid."
 
>>> fnExcept()
Oops, invalid.

10. 包的导入

使用import [libname]导入外部包,你也可以为单独的函数使用from [libname] import [funcname]这种形式来导入。下面是一个例子:

import random
from time import clock
 
randomint = random.randint(1, 100)
>>> print randomint
64

11.文件I/O

Python有一个很大的内建库数组来处理文件的读写。下面的例子展示如何使用Python的文件I/O来序列化(使用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 = file(r"C:binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
 
myfile = file(r"C:text.txt", "w")
myfile.write("This is a sample string")
myfile.close()
 
myfile = file(r"C:text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()
 
# Open the file for reading.
myfile = file(r"C:binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]

[有关资料显示,使用另一个库CPickle效率比pickle高1000倍,因为CPickle使用C实现的,使用方法和pickle基本一样。译注]

12. 其他


  
  
    • 条件语句可以链接使用。1 < a < 3检查a是否介于1和3之间。
    • 可以使用del删除数组中的元素或者变量。
    • List comprehensions[不知怎么翻译,译注]提供一个强大的方法来创建和操作list(列表)。它由一个后跟一个for语句的表达式组成,这个for语句后跟一个或者多个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
      # Check how many items have this property.
      >>> sum(1 for i in [3, 3, 4, 4, 3] if i == 3)
      3
      >>> 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 assigned to before printing. Python knows that it a
      # value will be assigned to it later and creates a new, local
      # number instead of accessing the global one.
      print number
      number = 3
       
      def yetanotherfunc():
      global number
      # This will correctly change the global.
      number = 3
13. 结束语

这个教程并没有列出Python的全部细节(甚至连一个子集都算不上)。Python还有一系列的库以及许多其他功能,这就需要你通过其他途径来学习了,比如很优秀的在线教程 Dive into Python。我只希望这个教程能让你对Python快速上手。如果你觉得有什么需要改进或者添加的地方,或者你想看到的其他任何东西(类,错误处理,任何东西),那就在这里留言吧。

 

原文:http://article.yeeyan.org/view/linghucong/1543?from_com

英语原文:http://www.poromenos.org/tutorials/python


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值