{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# About Python (关于Python)\n", "\n", "Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale.\n", "\n", "The language Python is named after the BBC show _Monty Python’s Flying Circus_ and has nothing to do with reptiles.\n", "\n", "Python supports multiple programming paradigms, including _object-oriented_, _imperative_ and _functional programming_ or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.\n", "\n", "\n", "Python was conceived in the late 1980s, and its implementation was started in December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language (itself inspired by SETL) capable of exception handling and interfacing with the Amoeba operating system. Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, benevolent dictator for life.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Features (语言特征)\n", "\n", "The core philosophy of the language is summarized by the document \"PEP 20 (The Zen of Python)\", which includes aphorisms such as:\n", "\n", "- Beautiful is better than ugly\n", "- Explicit is better than implicit\n", "- Simple is better than complex\n", "- Complex is better than complicated\n", "- Readability counts\n", "\n", "Python enables programs to be written compactly and readably. Programs written in Python are typically much shorter than equivalent C, C++, or Java programs, for several reasons:\n", "\n", "- the high-level data types allow you to express complex operations in a single statement;\n", "- statement grouping is done by **indentation** instead of beginning and ending brackets;\n", "- no variable or argument declarations are necessary.\n", "\n", "Python is extensible: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and use it as an extension or command language for that application.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Installing Python (安装Python)\n", "\n", "On Linux machine, Python is usually installed by default. To install Python on other systems, check out the [Python Setup and Usage section in Python help documentation](https://docs.python.org/2.7/using/index.html).\n", "\n", "If you are using Windows, [Anaconda](https://www.anaconda.com/download/) is a good choice." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Using Python (使用Python)\n", "\n", "The Python interpreter is usually installed as `/usr/bin/python` on those machines where it is available.\n", "\n", "- To start a Python interpreter, type the command in your terminal: `python`.\n", "\n", "- To terminate the Python interpreter, type an end-of-file character (`Control-D` on Unix, `Control-Z` on Windows) at the primary prompt. If that doesn’t work, you can exit the interpreter by typing the following command: `quit()`.\n", "\n", "```\n", "fli@carbon:~$ python\n", "Python 2.7.9 (default, Mar 1 2015, 12:57:24) \n", "[GCC 4.9.2] on linux2\n", "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n", ">>> exit()\n", "```" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Executing Python scripts (如何执行Python脚本)\n", "\n", "- Write down your Python script and name it as `hello.py` with `.py` extension\n", "\n", "- Your script contents look like this \n", " \n", " ```\n", " #!/usr/bin/python\n", " print('Hello World')\n", " ```\n", " \n", "- Go to your terminal, make your script _executable_\n", " \n", " ```\n", " chmod +x hello.py\n", " ```\n", "- Run the script in your terminal\n", "\n", " ```\n", " ./hello.py\n", " ```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** The line `#!/usr/bin/python` should appear at the very beginning of your file. Alternatively, you can let your environment variable to specify which Python to use as \n", "```\n", "#!/usr/bin/env python\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is possible to use encodings different than ASCII in Python source files. The best way to do it is to put one more special comment line right after the `#!` line to define the source file encoding:\n", "\n", "```\n", "# -*- coding: utf-8 -*-\n", "```\n", "\n", "Your `hello.py` will be able handle more complicated texts. By using UTF-8, characters of most languages in the world can be used simultaneously in string literals and comments. Using non-ASCII characters in identifiers is not supported. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using IPython shell (Python交互式编程环境)\n", "\n", "IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history. IPython provides the following features:\n", "\n", "- Interactive shells (terminal and Qt-based).\n", "- A browser-based notebook with support for code, text, mathematical expressions, inline plots and other media.\n", "- Support for interactive data visualization and use of GUI toolkits.\n", "- Flexible, embeddable interpreters to load into one's own projects.\n", "- Tools for parallel computing.\n", "\n", "\n", "To start iPython interactive environment, type `ipython` in your terminal." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Getting help (获取帮助)\n", "\n", "- Help is available in Python sessions using `help(function)` . \n", "\n", "- Some functions (and modules) have very long help files. When using IPython, these can be paged using the command `?function` or `function?` so that the text can be scrolled using page up and down and `q` to `quit`. `??function` or `function??` can be used to type the entire function including both the `docstring` and the code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Libraries (Python库)\n", "\n", "Python has a large standard library, commonly cited as one of Python's greatest strengths, providing tools suited to many tasks. This is deliberate and has been described as a \"batteries included\" Python philosophy. For Internet-facing applications, a large number of standard formats and protocols are supported. Modules for creating graphical user interfaces, connecting to relational databases, pseudo random number generators, arithmetic with arbitrary precision decimals, manipulating regular expressions, and doing unit testing are also included.\n", "\n", "Some parts of the standard library are covered by specifications, but the majority of the modules are not. They are specified by their code, internal documentation, and test suite (if supplied). However, because most of the standard library is cross-platform Python code, there are only a few modules that must be altered or completely rewritten by alternative implementations.\n", "\n", "The standard library is not essential to run Python or embed Python within an application. Blender 2.49, for instance, omits most of the standard library.\n", "\n", "As of August 2015, the Python Package Index, the official repository of third-party software for Python, contains more than 65,000 packages offering a wide range of functionality, including:\n", "\n", "- graphical user interfaces, web frameworks, multimedia, databases, networking and communications\n", "- test frameworks, automation and web scraping, documentation tools, system administration\n", "- scientific computing, text processing, image processing\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Text Editors/IDEs (Python编辑器)\n", "\n", "To edit Python code, you just need a handy text editor. There are many available, check out the following pages \n", "\n", "- [Text editors in Python Wiki](https://wiki.python.org/moin/PythonEditors)\n", "- [Comparison_of_text_editors in Wikipedia](https://en.wikipedia.org/wiki/Comparison_of_text_editors)\n", "- [Integrated Development Environments](https://wiki.python.org/moin/IntegratedDevelopmentEnvironments)\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Using Python as a Calculator (Python基本使用)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 + 2 +4" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 + 4*3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Division (除法)\n", "\n", "The return type of a division (/) operation depends on its operands. If both operands are of type int, floor division is performed and an int is returned. If either operand is a float, classic division is performed and a float is returned. The // operator is also provided for doing floor division no matter what the operands are." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1.6" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8/5 #In Python 2, int / int -> int, you will get 1 instead of 1.6. But in Python 3 will get precise division" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1.6" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8/5.0 # int / float -> float" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8//5.0 # explicit floor division discards the fractional part" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The remainder can be calculated with the % operator" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 % 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** To always get precise division in Python 2, use\n", "```\n", "from __future__ import division\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Powers (幂)\n", "\n", "With Python, it is possible to use the \\*\\* operator to calculate powers. **Note** Caret (^) in Python behaves differently. It invokes the exclusive OR of the object: a logical operation that outputs true only when both inputs differ (one is true, the other is false). " ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5**2" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2^3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 3\n", "b = 5\n", "c = a + b\n", "c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In interactive mode, the last printed expression is assigned to the variable \\_. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "33.333333333333336" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100/3.0" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "33.333333333333336" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings (字符串)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes (\"...\") with the same result. " ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true, "scrolled": true }, "outputs": [], "source": [ "LastName = \"Li\"" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": true, "scrolled": true }, "outputs": [], "source": [ "FirstName = \"Feng\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\\ can be used to escape quotes:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello \n", " World!\n" ] } ], "source": [ "print(\"Hello \\n World!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you don't want characters prefaced by \\ to be interpreted as special characters, you can use raw strings by adding an `r` before the first quote:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello \\n World!\n" ] } ], "source": [ "print(r\"Hello \\n World!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings can be concatenated (glued together) with the `+` operator, and repeated with `*`:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'I Looooove you'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"I \" + 'L' + 'o'*5 + 've' + ' you'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The built-in function `len()` returns the length of a string:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(\"Feng Li\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'FengLi'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"Feng\" \"Li\"" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hi, my name is Feng Li. And I am from Beijing.\n" ] } ], "source": [ "print(\"Hi, my name is Feng Li.\" \n", " \" And I am from Beijing.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'F'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name = \"Feng Li\"\n", "Name[0]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'i'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[-1]" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'L'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[-2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'Feng'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[0:4]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember that [0:4] mathematically means [0, 4)." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'Feng'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[:4]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'Li'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[5:]" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'Li'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[-2:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, out of range slice indexes are handled gracefully when used for slicing:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'Li'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Name[5:100]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists (列表)\n", "\n", "Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "scrolled": true }, "outputs": [], "source": [ "values = [1,5,7,9,12]" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(values)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values[0]" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[9, 12]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values[-2:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists also supports operations like concatenation:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[1, 5, 7, 9, 12, '22', '33', '22', '33', '22', '33', '22', '33', '22', '33']" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values + [\"22\",\"33\"]*5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists are a mutable type, i.e. it is possible to change their content:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 67, 22]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values = [1,2,3,4,67,22]\n", "values" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 1000, 4, 67, 22]" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values[2] = 1000\n", "values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also add new items at the end of the list, by using the append() method" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 1000, 4, 67, 22, 9999]" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values.append(9999)\n", "values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 2, 3, 4, 67, 22]" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values[2:4] = [2,3,4]\n", "values" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "values[:] = []\n", "values\n", "len(values)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Building Functions (常用内置函数)\n", "\n", "The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order. Use e.g. `help(abs)` to see the function help.\n", "\n", "```\n", "abs() \tdivmod() \tinput() \topen() \t\n", "staticmethod() all() \tenumerate() \t\n", "int() \tord() \tstr() any() \t\n", "eval() \tisinstance() \tpow() \tsum()\n", "basestring() \texecfile() \tissubclass() \t\n", "print() \tsuper() bin() \tfile() \t\n", "iter() \tproperty() \ttuple() bool() \t\n", "filter() \tlen() \trange() \ttype()\n", "bytearray() \tfloat() \tlist() \t\n", "raw_input() \tunichr() callable() \t\n", "format() \tlocals() \treduce() \tunicode()\n", "chr() \tfrozenset() \tlong() \treload() \t\n", "vars() classmethod() \tgetattr() \tmap() \t\n", "repr() \txrange() cmp() \tglobals() \t\n", "max() \treversed() \tzip() compile() \t\n", "hasattr() \tmemoryview() \tround() \t\n", "__import__() complex() \thash() \tmin() \t\n", "set() \tapply() delattr() \thelp() \n", "next() \tsetattr() \tbuffer()\n", "dict() \thex() \tobject() \tslice() \t\n", "coerce() dir() \tid() \toct() \t\n", "sorted() \tintern()\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Import modules (导入模块)\n", "\n", "To import a module (like `math`) that is not in Python's default module, use" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": true, "scrolled": true }, "outputs": [], "source": [ "import math" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then you can use all the mathematical functions inside `math` module as:" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.exp(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can do the following changes" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "2.718281828459045" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import math as mt\n", "mt.exp(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you just want to import one or two functions from a module" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "20.085536923187668" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from math import exp\n", "exp(3)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "2.718281828459045" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from math import exp as myexp\n", "\n", "myexp(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control Flow Tools (控制语句)\n", "\n", "### The if statements (条件表达)\n", "Perhaps the most well-known statement type is the if statement. For example:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "More\n" ] } ], "source": [ "x = 5\n", "\n", "if x < 0:\n", " x = 0\n", " print('Negative changed to zero')\n", "elif x == 0:\n", " print('Zero')\n", "elif x == 1:\n", " print('Single')\n", "else:\n", " print('More')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** \n", "\n", "- the comma/colon sign(:) should be right after `if`, `elif` and `else` statement.\n", "- the indentation is very important. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The for Statements (for循环)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cat 3\n", "window 6\n", "defenestrate 12\n", "I am done!\n" ] } ], "source": [ "words = ['cat', 'window', 'defenestrate']\n", "\n", "for j in words:\n", " print(j,len(j))\n", "\n", "print(\"I am done!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Defining Functions (函数定义)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can create a function that writes the Fibonacci series to an arbitrary boundary.\n", "\n", "The first line should always be a short, concise summary of the object's purpose. For brevity, it should not explicitly state the object's name or type, since these are available by other means (except if the name happens to be a verb describing a function's operation). This line should begin with a capital letter and end with a period.\n", "\n", "If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object's calling conventions, its side effects, etc.\n", "\n", "The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or **docstring**. There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it's good practice to include docstrings in code that you write, so make a habit of it." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "scrolled": true }, "outputs": [], "source": [ "def fib(n): # write Fibonacci series up to n\n", " \"\"\"\n", " Print a Fibonacci series up to n.\n", "\n", " Usage\n", " \n", " fib(n)\n", " \"\"\" # the function help\n", " a, b = 0, 1\n", " while a < n:\n", " print(a, end=\" \")\n", " a, b = b, a+b" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function fib in module __main__:\n", "\n", "fib(n)\n", " Print a Fibonacci series up to n.\n", " \n", " Usage\n", " \n", " fib(n)\n", "\n" ] } ], "source": [ "help(fib)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 1 2 3 5 8 13 21 34 55 89 144 " ] } ], "source": [ "fib(200)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Function with default values (函数参数默认值)\n", "\n", "The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):\n", " while True:\n", " ok = input(prompt)\n", " if ok in ('y', 'ye', 'yes'):\n", " return True\n", " if ok in ('n', 'no', 'nop', 'nope'):\n", " return False\n", " retries = retries - 1\n", " if retries < 0:\n", " raise IOError('refusenik user')\n", " print(complaint)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** \n", "\n", "`raw_input()` only works with Python 2. To make it it work with Python 3, change `raw_input()` into `input`.\n", "\n", "The `return` statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None." ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Do you really want to go?hao\n", "Yes or no, please!\n", "Do you really want to go?keyi\n", "Yes or no, please!\n", "Do you really want to go?yes\n" ] }, { "data": { "text/plain": [ "True" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ask_ok(\"Do you really want to go?\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Anonymous functions (匿名函数)\n", "\n", "Small anonymous functions can be created with the `lambda` keyword. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope. The example uses a lambda expression to return a function" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "def make_incrementor(n):\n", " return lambda x: x + n\n", "f = make_incrementor(42)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(0)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "43" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Classes (Python的类)\n", "\n", "Compared with other programming languages, Python's class mechanism adds classes with a minimum of new syntax and semantics. Python classes provide all the standard features of Object Oriented Programming: \n", "\n", "- the class inheritance mechanism allows multiple base classes, \n", "- a derived class can override any methods of its base class or classes, and \n", "- a method can call the method of a base class with the same name. \n", "\n", "Class definitions, like function definitions (`def` statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.)\n", "\n", "In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods.\n", "\n", "When a class definition is entered, a new **namespace** is created, and used as the _local scope_ — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. \n", "\n", "Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.\n", "\n", "\n", "When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: _they are created at runtime, and can be modified further after creation_.\n", "\n", "\n", "- [Python tutorial: Classes](https://docs.python.org/3/tutorial/classes.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Class Objects (Python类的对象)\n", "\n", "Class objects support two kinds of operations: **attribute references** and **instantiation**." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class MyClass:\n", " \"\"\"A simple example class\"\"\"\n", " i = 12345\n", " def f(self):\n", " return 'hello world'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.MyClass at 0x7f50f839d2e8>" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "MyClass()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Attribute references** use the standard syntax used for all attribute references in Python: `obj.name`. Valid attribute names are all the names that were in the class’s namespace when the class object was created." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12345" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "MyClass.i" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "MyClass.f" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`MyClass.i` and `MyClass.f` are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of `MyClass.i` by assignment." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "MyClass.i = 3\n", "MyClass.i" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The **instantiation operation** (\"calling\" a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named `__init__()`, like this:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def __init__(self):\n", " self.data = []" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When a class defines an `__init__()` method, class instantiation automatically invokes `__init__()` for the newly-created class instance. So in this example, a new, initialized instance can be obtained by calling" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.MyClass object at 0x7f50f839deb8>\n" ] } ], "source": [ "x = MyClass()\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, the `__init__()` method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to `__init__()`." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3.0, -4.5)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Complex:\n", " def __init__(self, realpart, imagpart):\n", " self.r = realpart\n", " self.i = imagpart\n", "\n", "x = Complex(3.0, -4.5)\n", "x.r, x.i" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Coding Style (Python编程规范)\n", "\n", "\n", "\n", "- Use 4-space indentation, and no tabs.\n", " 4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.\n", "\n", "- Wrap lines so that they don't exceed 79 characters.\n", " This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.\n", "\n", "- Use blank lines to separate functions and classes, and larger blocks of code inside functions.\n", "\n", "- When possible, put comments on a line of their own.\n", "\n", "- Use docstrings.\n", "\n", "- Use spaces around operators and after commas, but not directly inside bracketing constructs: `a = f(1, 2) + g(3, 4)`.\n", "\n", "- Name your classes and functions consistently; the convention is to use **CamelCase** for classes and **lower_case_with_underscores** for functions and methods. Always use `self` as the name for the first method argument (see A First Look at Classes for more on classes and methods).\n", "\n", "- Don’t use fancy encodings if your code is meant to be used in international environments. Plain ASCII works best in any case.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5rc1" } }, "nbformat": 4, "nbformat_minor": 1 }