十分鐘python入門教程

from: http://hi.baidu.com/wxipi/blog/item/dcbf1f500991975b1038c298.html

from: http://yunhaozou.org/perl-shell/314.html

from: http://roclinux.cn/?p=2338


看到好多同學在求Python教程,其實完全沒必要,
Python非常的簡單,簡單到恐怕用自然語言來看python就能看懂了...
這裏偶就簡單的寫個教程吧。


首先是數據結構,python所有的數據都是對象,包括0,1之類的:
數只有整數和浮點之分,整數是直接支持高精度的,因此,想知道12345的12345次方是多
少,直接輸入print 12345**12345就行了。
不過浮點數不是高精度的,表達範圍跟C的float一樣。


接下來是字符串,可以用''/""框起來,還有""" """對這裏就不提了。
沒有字符的概念,單個字符也是一個字符串。
字符串可以用類似matlab的下標方式操作,諸如a="abcd"
那麼a[0]=='a',a[1:3]=='bc',a[-1]='d',a[1:]='bcd',a[1::2]=='bd'等等等等
字符串是不可更改的。


接下來就是容器類:tuple/list/dict,分別用(),[],{}表示。比如
t=(1,2,"a"),l=[1,2,"a"]。無論是tuple還是list,都可以用類似字符串下標的形式訪問
,例如:
l[1]==2,l[-1]=='a'。
tuple和list的區別在於,tuple和字符串一樣不可修改,而list可以修改:
l[0]='p'       l變成['p',2,'a']
l[0:2]=[3,4]  l變成[3,4,'a']
l[::2]=[5,6]  l變成[5,2,6]
del l[1:]      l變成[5]
而dict則完成一個key->value的映射:
d={1:2,"a":4},那麼d[1]==2,d['a']==4。


接下來是Python靈活性的體現:list comprehension
例如:a=[1,2,3,4,5,6,7,8]
那麼[x+1 for x in a]->[2,3,4,5,6,7,8,9]
[x*2 for x in a if x>4]->[10,12,14,16]
list comprehension將操作和過濾融合在一起,而且讀起來就像是自然語言這麼自然,非
常的舒服。


接下來講分支/循環。這裏要提一下python以縮進來取代C裏面的{}對。
同樣的縮進表示這段代碼處於同一個層次。
下面是if分支:
if 條件:
   true分支
elif 條件2:
   true分支
else:
   else分支


接下來是循環:
for i in [1,2,3,4]:
    循環體
或者:
while 條件:
    循環體


接下來是函數:
def funcname(arg1,arg2):
    函數體
變參和默認值:
def funcname(arg1, arg2="default value", *varargs): pass
至於**kwargs偶就不提了。


好了基礎部分全部說完,下面纔是我最感興趣的部分,也是Python最核心的東西,就是namespace。
很多初學者學Python總是把Python和C,java等語言對比,
面對a=1這樣的語句,把a看作一個變量名,1是一個值,認爲這是一個賦值過程。
讓我們回顧一下賦值的定義:
賦值是指將一個數值存儲到一個空間中。例如以下C代碼:
int a,b;
a=1;b=1;
這個例子中,a和b都有各自的空間。裏面都存儲了一個值,爲1。這兩個數值是互不相關的。


而在python中,這裏要狠狠強調一下:Python裏面不存在賦值過程,也不存在變量!!!
a=1這個過程,在Python中解釋爲一個name對一個對象的綁定。
也就是說"a"這個名字指向了1這個對象。
由於Python裏面不存在變量的概念,所以自然也沒有變量的申明。Python裏面就是一大堆
的對象,以及各種名字指向這些對象:
a=1
b=2
c=a+b
在Python中,解釋爲讓"a"指向對象1,讓"b"指向對象2;對"a"所指對象以及"b"所指對象
運用add操作,
讓"c"指向得到的結果。
在Python中,你不需要關心對象的產生和銷燬。例如這個上面例子中,產生的對象3,如果
沒有名字指向它,就會被自動銷燬(這裏偶爲了便於理解撒了個謊。事實上爲了性能問題,
0-100這些對象是永遠存在的)


以上爲name的解釋
下面解釋space:


每一個name都有其存在的空間。
只有模塊,類,函數有其自己的子空間,而只有模塊,類的子空間可以被訪問。
例如:
def func():
    a=1
這個a就存在於func的空間中。
在func以外,這個a是無法被訪問到的。


另一個經常引起困擾的例子:
a=1
def func():
    print a    1.結果爲1
    a=2
    print a    2.結果爲2
print a        3.結果爲1
func()
print a        4.結果還是1
這個例子中,第一個print a執行的時候,func的子空間中不存在a,這個時候就自動的訪
問上一層空間,
也就是全局空間,得到了a。
隨後的a=2賦值,在func的子空間中創造了a的name,並指向2。
於是在第二個print a執行的時候,直接打印了func子空間中的a;
在第三個、第四個print a執行的都是全局a的結果。


恩,不知道說清楚了沒有。
因爲我比較懶,沒有說class,以及module,所以目前看來namespace似乎沒啥。
其實namespace是Python的關鍵中的關鍵。理解了這個才能駕馭Python~


如果這些都充分理解了,下面就可以自己去翻翻python library reference,看看python
豐富的庫了~





Preliminary fluff

So, you want to learn the Python programming language but can’t find a concise and yet full-featured tutorial. This tutorial will attempt to teach you Python in 10 minutes. It’s probably not so much a tutorial as it is a cross between a tutorial and a cheatsheet, so it will just show you some basic concepts to start you off. Obviously, if you want to really learn a language you need to program in it for a while. I will assume that you are already familiar with programming and will, therefore, skip most of the non-language-specific stuff. The important keywords will be highlighted so you can easily spot them. Also, pay attention because, due to the terseness of this tutorial, some things will be introduced directly in code and only briefly commented on.

Properties

Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don’t have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object).

Getting help

Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call help(<object>)! Also useful are dir(), which shows you all the object’s methods, and <object>.doc, which shows you its documentation string:

>>> help(5)
Help on int object:
(etc etc)

>>> dir(5)
['__abs__', '__add__', ...]

>>> abs.__doc__
‘abs(number) -> number\n\nReturn the absolute value of the argument.’

Syntax

Python has no mandatory statement termination characters and blocks are specified by indentation. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments. Values are assigned (in fact, objects are bound to names) with the equals sign (”=”), and equality testing is done using two equals signs (”==“). You can increment/decrement values using the += and -= operators respectively by the right-hand amount. This works on many datatypes, strings included. You can also use multiple variables on one line. For example:

>>> 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

Data types

The data structures available in python are lists, tuples and dictionaries. Sets are available in the sets library (but are built-in in Python 2.5 and later). Lists are like one-dimensional arrays (but you can also have lists of other lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays (Python “arrays” can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples). The index of the first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. Variables can point to functions. The usage is as follows:

>>> 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.15
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print myfunction(mylist)
3

You can access array ranges using a colon (:). Leaving the start index empty assumes the first item, leaving the end index assumes the last item. Negative indexes count from the last item backwards (thus -1 is the last item) like so:

>>> 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]

Strings

Its strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. “He said ‘hello’.” is valid). Multiline strings are enclosed in triple double (or single) quotes(”“”). Pythonsupports Unicode out of the box, using the syntax u“This is a unicode string”. To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions, like so:

>>>print ”Name: %s\nNumber: %s\nString: %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.

Flow control statements

Flow control statements are iffor, and while. There is no select; instead, use if. Use for to enumerate through members of a list. To obtain a list of numbers, userange(<number>). These statements’ syntax is thus:

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

Functions

Functions are declared with the “def” keyword. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values).Lambda functions are ad hoc functions that are comprised of a single statement. Parameters are passed by reference, but immutable types (tuples, ints, strings, etc)cannot be changed. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. For example:

# Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and “A default string”, respectively).
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

Classes

Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared (by convention, this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e.g. “__spam”). We can also bind arbitrary names to class instances. An example follows:

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 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. 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

Exceptions

Exceptions in Python are handled with try-except [exceptionname] blocks:

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.

Importing

External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. Here is an example:

import random
from time import clock

randomint = random.randint(1, 100)
>>> print randomint
64

File I/O

Python has a wide array of libraries built in. As an example, here is how serializing(converting data structures to strings using the pickle library) with file I/O is used:

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]

Miscellaneous

  • Conditions can be chained. 1 < a < 3 checks that a is both less than 3 and more than 1.
  • You can use del to delete variables or items in arrays.
  • List comprehensions provide a powerful way to create and manipulate lists. They consist of an expression followed by a for clause followed by zero or more ifor for clauses, like so:

>>> 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 variables are declared outside of functions and can be read without any special declarations, but if you want to write to them you must declare them at the beginning of the function with the “global” keyword, otherwise Python will bind that object to a new local variable (be careful of that, it’s a small catch that can get you if you don’t know it). For example:

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

Epilogue

This tutorial is not meant to be an exhaustive list of all (or even a subset) of Python. Python has a vast array of libraries and much much more functionality which you will have to discover through other means, such as the excellent book Dive into Python. I hope I have made your transition in Python easier. Please leave comments if you believe there is something that could be improved or added or if there is anything else you would like to see (classes, error handling, anything).



發佈了37 篇原創文章 · 獲贊 19 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章