`
sillycat
  • 浏览: 2544165 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

DiveIntoPython(一)first program

阅读更多
DiveIntoPython(一)first program

英文书地址
http://diveintopython3.org/
下载得到PDF版本
http://diveintopython3.org/d/diveintopython3-pdf-r860-2010-01-13.zip
解开压缩得到文件diveintopython3-r860.pdf和很多example.
python本身的官方文档
http://docs.python.org/3.1/

以上是版本python3,后来再使用中发现google app engine和django都还没有支持到python3,所以我本机安装的python2.6.4,所以决定先从小版本看起。
英文书地址:
http://diveintopython.org/toc/index.html

chapter 1. Installing Python
1.1 介绍了两种方式下载python
1如果要最新版本,请下载官方版本,下载地址:http://www.python.org/
得到文件python-2.6.4.msi,双击安装
2比较实用,笔者推荐activePython,下载地址:http://www.activestate.com/activepython/downloads/
得到文件ActivePython-2.6.4.10-win32-x86.msi,双击安装
1.2 The Interactive Shell
An interactive shell can evaluate arbitrary statements and expressions.This is extremely useful for debugging,quick hacking and testing.

chapter 2.Your First Python Program
odbchelper.py in examples:
def buildConnectionString(params):
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret"
}
print buildConnectionString(myParams)
the output of odbchelper.py will look like this:
pwd=secret;database=master;uid=sa;server=mpilgrim

2.2 Declaring Function
def buildConnectionString(params):
python do not specify the type about return value and arguments.
2.2.2 How Python's Datatypes Compare to Other Programming Languages
statically typed language
A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
dynamically typed language
A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
strongly typed language
A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
weakly typed language
A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.

2.3.Documenting Functions
def buildConnectString(params):
  """ Build a connection string from a dictionary of parameters.
       Return string """
Python gives you an added incentive: the doc string is available at runtime as an attribute of the function.

2.4 Everything Is an Object
I type follow commands in my interactive shell:
>>> import odbchelper
>>> params = {"tt1":"tt1"}
>>> print odbchelper.buildConnectionString(params)
tt1=tt1
>>> print odbchelper.buildConnectionString.__doc__
Build a connection string from a dictionary

Returns string.
2.4.1 The Import Search Path:
>>> import sys
>>> sys.path
['', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info', 'E:\\book\\opensource\\python\\diveintopython-5.4\\py']

You can add a new directory to Python's search path at runtime by appending the directory name to sys.path, and then Python will look in that directory as well, whenever you try to import a module. The effect lasts as long as Python is running.

2.4.2 What's an Object
All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code.
everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.

2.5 Indenting Code   indent [in'dent, 'indent] n. 凹痕;订货单;契约;缩进 vt. 缩排
Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords.
bracket ['brækit]  n. 支架;括号;墙上凸出的托架
Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks.

2.6 Testing Modules
Modules are objects, and all modules have a built-in attribute __name__ and __doc__.

Chapter 3 . Native Datatypes
3.1 Introducing Dictionaries
One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.
A dictionary in Python is like an instance of the Hashtable class in Java.
3.1.1. Defining Dictionaries
example:
>>> d = {"server":"mpilogrim","database":"master"}
>>> d
{'database': 'master', 'server': 'mpilogrim'}
>>> d["server"]
'mpilogrim'
>>> d["database"]
'master'
>>> d["ccc"]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
KeyError: 'ccc'

the whole set of elements is enclosed in curly braces.And you can get values by key, but you can't get keys by value.

3.1.2 Modifying Dictionaries
>>> d["database"] = "pubs"
>>> d
{'database': 'pubs', 'server': 'mpilogrim'}
>>> d["uid"] = "sillycat"
>>> d
{'database': 'pubs', 'uid': 'sillycat', 'server': 'mpilogrim'}

You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; When working with dictionaries, you need to be aware that dictionary keys are case-sensitive.

examples:
>>> d["key"] = "other value"
>>> d
{'key': 'other value'}
>>> d["Key"] = "third value"
>>> d
{'Key': 'third value', 'key': 'other value'}

examples:
>>> d = {}
>>> d
{}
>>> d["retrycount"] = 3
>>> d
{'retrycount': 3}
>>> d[42] = "douglas"
>>> d
{'retrycount': 3, 42: 'douglas'}

Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed

Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.

3.1.3 Deleting Items From Dictionaries
examples:
>>> d
{'retrycount': 3, 42: 'douglas'}
>>> del d[42]
>>> d
{'retrycount': 3}
>>> d.clear()
>>> d
{}

del lets you delete individual items from a dictionary by key.
clear deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary without any items.

3.2 Introducing Lists
Lists are Python's workhorse datatype.A list in Python is much more than an array in Java.A better analogy would be to the ArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.

3.2.1 Defining Lists
examples:
>>> li = ["a","b","mpilgrim","zt","hha"]
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[0]
'a'
>>> li[4]
'hha'

First, you define a list of five elements. Note that they retain their original order. This is not an accident. A list is an ordered set of elements enclosed in square brackets.
A list can be used like a zero-based array. The first element of any non-empty list is always li[0].

Negative List Indices
indice   n. 指数;标记体  string indice: 字符串索引
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[-1]
'hha'
>>> li[-3]
'mpilgrim'

A negative index accesses elements from the end of the list counting backwards. The last element of any non-empty list is always li[-1].

Slicing a List
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[1:3]
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'zt']
>>> li[0:2]
['a', 'b']

You can get a subset of a list, called a “slice”, by specifying two indices. The return value is a new list containing all the elements of the list, in order, starting with the first slice index (in this case li[1]), up to but not including the second slice index (in this case li[3]).
Slicing works if one or both of the slice indices is negative. If it helps, you can think of it this way: reading the list from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don't want. The return value is everything in between.
Lists are zero-based, so li[0:3] returns the first three elements of the list, starting at li[0], up to but not including li[3].

Slicing Shorthand  shorthand ['ʃɔ:thænd]  n. 速记;速记法
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[:3]
['a', 'b', 'mpilgrim']
>>> li[3:]
['zt', 'hha']
>>> li[:]
['a', 'b', 'mpilgrim', 'zt', 'hha']

If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3]
Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as li[3:5], because this list has five elements
Note the symmetry here. In this five-element list, li[:3] returns the first 3 elements, and li[3:] returns the last two elements. In fact, li[:n] will always return the first n elements, and li[n:] will return the rest, regardless of the length of the list.
If both slice indices are left out, all elements of the list are included. But this is not the same as the original li list; it is a new list that happens to have all the same elements. li[:] is shorthand for making a complete copy of a list.

3.2.2 Adding Elements to Lists
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.insert(2,"new2")
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.extend(["two","elements"])
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new', 'two', 'elements']

append adds a single element to the end of the list.
insert inserts a single element into a list. The numeric argument is the index of the first element that gets bumped out of position. Note that list elements do not need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].
extend concatenates lists. Note that you do not call extend with multiple arguments; you call it with one argument, a list. In this case, that list has two elements.

The Difference between extend and append
examples:
>>> li = ["a","b","c"]
>>> li.extend(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)
6
>>> li[-1]
'f'
>>> li.append(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> len(li)
7
>>> li[-1]
['d', 'e', 'f']

Lists have two methods, extend and append, that look like they do the same thing, but are in fact completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list.
On the other hand, append takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements.

3.2.3 Searching Lists
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.index("b")
1
>>> li.index("f")
5
>>> li.index("test")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: list.index(x): x not in list
>>> "test" in li
False

index finds the first occurrence of a value in the list and returns the index.

If the value is not found in the list, Python raises an exception. This is notably different from most languages, which will return some invalid index. While this may seem annoying, it is a good thing, because it means your program will crash at the source of the problem, rather than later on when you try to use the invalid index.

To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.

3.2.4 Deleting List Elements
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("b")
>>> li
['a', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("test")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> li.pop()
['d', 'e', 'f']
>>> li
['a', 'c', 'd', 'e', 'f']

remove removes the first occurrence of a value from a list.

If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.

pop is an interesting beast. It does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[-1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.

3.2.5 Usinig List Operators
examples:
>>> li = ["a","b",'mpigra']
>>> li = li + ['example','new']
>>> li
['a', 'b', 'mpigra', 'example', 'new']
>>> li +=['two']
>>> li
['a', 'b', 'mpigra', 'example', 'new', 'two']
>>> li = [1,2]*3
>>> li
[1, 2, 1, 2, 1, 2]

Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.

The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.
分享到:
评论

相关推荐

    dive into python3 (中文版)

    Python是一种广泛使用的高级编程语言,以其简洁明了的语法和强大的功能而闻名。《深入Python3(中文版)》是一本系统介绍Python 3的书籍,旨在帮助读者深入学习Python 3的基本知识与应用。本文将根据给定文件的信息...

    《Dive Into Python 3中文版》PDF

    《Dive Into Python 3中文版》是一本深入学习Python 3编程语言的教程,适合初学者和有一定编程基础的开发者。这本书详细介绍了Python 3的各种特性,包括语法、数据结构、函数、类、模块、异常处理、输入/输出、网络...

    Dive into Python3

    《Dive into Python3》是一本专为Python 3编程语言设计的教程,旨在帮助初学者和有一定经验的程序员深入理解Python 3的核心概念和技术。这本书由Mark Pilgrim撰写,以其详细、实践性强的特点深受读者喜爱。尽管描述...

    Dive Into Python 中文译文版

    《Dive Into Python》是一本深受程序员喜爱的Python编程教程,中文译文版的发布为中文读者提供了便利,尤其对于初学者来说,是学习Python语言的一份宝贵资源。该资源包含两个部分:PDF版本的译文和帮助文档,以及...

    DiveIntoPython

    《Dive Into Python》是一本深受编程初学者和有经验开发者喜爱的Python编程教程。这本书以其深入浅出的讲解方式,让学习者能够快速掌握Python编程语言的核心概念和实际应用,特别是对于想要涉足Web开发领域的读者,...

    深入Python (Dive Into Python)

    深入python,深入Python (Dive Into Python) 译者序 by limodou 主页(http://phprecord.126.com) Python论坛 本书英文名字为《Dive Into Python》,其发布遵守 GNU 的自由文档许可证(Free Document Lience)的...

    Dive into python

    dive into python英文原版,Dive Into Python 3 covers Python 3 and its differences from Python 2. Compared to Dive Into Python, it’s about 20% revised and 80% new material. The book is now complete, ...

    Dive Into Python 2 中文版

    《Dive Into Python 2 中文版》是一本深度探讨Python编程语言的教程,适合已经有一定编程基础,希望深入理解Python特性和应用的读者。这本书以其详尽的解释和丰富的实例,为Python初学者和进阶者提供了全面的学习...

    Dive Into Python 3

    《深入Python 3》是一本全面且深入介绍Python 3编程语言的电子书籍,旨在帮助读者从...压缩包中的文件“diveintomark-diveintopython3-793871b”很可能是该书的源代码或HTML文件,可以配合阅读,加深对书中示例的理解。

    Dive Into Python 3 无水印pdf

    Dive Into Python 3 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Dive Into Python 3, r870 (2010).pdf

    Didyoureadtheoriginal“DiveIntoPython”?Didyoubuyit onpaper?(Ifso,thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthat istrue,you’dbebetteroffstartingatthebeginning.) Python3...

    Dive Into Python V5.4

    《Dive Into Python V5.4》是一本深入学习Python编程语言的经典教程,以其详尽的解释和丰富的实例深受程序员们的喜爱。这个版本是官方提供的最新版本,它不仅包含了PDF格式的完整书籍,还附带了书中所有示例代码,为...

    diveintopython3

    在“diveintopython3-master”这个压缩包中,包含了这本书的所有源代码示例。通过这些代码,我们可以学习到以下关键知识点: 1. **Python基础**:包括变量、数据类型(如整型、浮点型、字符串、列表、元组、字典)...

    dive-into-python3 (英文版)+深入python3(中文版)

    《Dive Into Python3》是一本面向实践的Python3入门书,它强调通过解决实际问题来学习语言,而不是仅仅讲解语法。书中涵盖了诸如数据类型、控制流、函数、模块、异常处理、面向对象编程、标准库使用等内容。此外,还...

    diveintopython-examples-5.4.rar

    diveintopython-examples-5.4.rardiveintopython-examples-5.4.rardiveintopython-examples-5.4.rardiveintopython-examples-5.4.rar

    Dive Into Python中文版

    Dive Into Python中文版,精心整理,epub版本方便阅读,下载阅读.

    Dive Into Python 3 中文版

    ### Dive Into Python 3 中文版 - 安装Python 3 #### 标题解析 - **Dive Into Python 3 中文版**:这本书名表明了内容将深入讲解Python 3的各项特性和使用方法,适合希望深入了解Python 3编程语言的读者。 #### ...

Global site tag (gtag.js) - Google Analytics