Introduction to Python

  • Wrap C/C++ libraries into Python via Cython and CFFI.

  • Python implementations for production quality:

    • CPython (Classic Python)

      • Implemented in C
      • Python Software Foundation License V2, compatible with GPL, proprietary, free, BSD/Apache/MIT.
    • Jython: on JVM

    • IronPython: support for .NET

    • PyPy: generate native machine code “just in time” when running the program. Thus it has substantial advantages in speed and memory management.

    • Pyston

  • IPython

    • It enhances the standard CPython with more powerful and convenient interactive use.
    • Abbreviated function call syntax.
    • magics
    • shell escapes
    • Use ? to query object’s documentation.
    • IPython Notebook now renamed as the Jupyter Notebook.
  • Anaconda distribution

    • It includes enormous number of preconfigured and tested modules.
    • It contains all the dependencies.
  • Nuitka: a compiler which converts Python to C++.

The Python Language

Lexical structure

  • Python statements don’t need ; to terminate.

  • line continuation symbol: \.

  • Blocks are defined via indentation. Use white space to indent instead of TAB.

  • Language structure

    • Tokens

      • Identifiers: specify the name of a variable, function, class, module etc.
      • Keywords
      • Operators
      • Delimiters
      • Literals
    • Statements

      • Simple statements
      • Compound statements (as a block)

Data types

  • Numbers

    • Integers

      • Decimal literal (no prefix): 1, 2, 3
      • Binary literal (0b prefix): 0b01001
      • Octal literal (0o prefix): 0o13
      • Hexadecimal literal (0x prefix): 0x17
    • Floating point numbers

    • Complex numbers: use $j$ as the imaginary unit.

  • Sequences

    • Iterable concept (an abstract higher level than sequences)

      • All sequence types in Python are iterables, which represent linear data structure as the concepts commonly used in C++ generic programming.
      • An iterable is bounded, due to the limited computer memory.
    • Except string type, sequences in Python are neither simple arrays as in C, nor template-based containers which can include only one type of data as in C++. They are generic containers which can include any type of data.

    • Strings

      • A string in Python is a sequence of byte objects.

      • A string is an immutable sequence.

      • Triple-quoted string: a whole paragraph of strings can be directly quoted without the need of a line-continuation symbol \. This is the so-called "here-document" in Bash.

      • Raw string

        • Starts with r or R.
        • Escape characters are not interpreted.
    • Tuples

      • A tuple is an immutable ordered sequence of items.
      • Tuple literal with only one item needs a trailing comma.
      • Use parentheses to wrap a tuple literal.
      ()                    # Empty tuple literal
      (1,) # Singleton tuple literal
      (1, 'good', 3) # Normal tuple literal
      tuple() # Create an empty tuple.
      tuple(iterable) # Create a tuple from an iterable.
      tuple('hello') # Create a tuple from a string sequence, which is also an iterable.
    • Lists

      • A list is a mutable ordered sequence of items.
      • A singleton list literal does not need a trailing comma.
      • Use brackets to wrap a list literal.
      [2, 'a', 5]           # Normal list literal
      [100] # Singleton list literal
      [] # Empty list literal
      list() # Create an empty list.
      list(iterable) # Create a list from an iterable.
      list('hello') # Create a list from a string sequence, which is also an iterable.
  • Sets

    • Unordered collections of unique items. This is consistent with the set concept in mathematics.

    • Two types of sets in Python

      • set (non-frozen set)

        • Mutable
        • Not hashable
        • frozenset can be an element of a set.
      • frozenset

        • Immutable
        • Hashable
        • frozenset can be an element of a frozenset.
    • Use braces to wrap a set literal.

      {5, 6, 'hello'}
      {10}
      # {}: Empty set literal is invalid.
      set() # Create an empty set from an iterable.
      set(iterable) # Create a set from an iterable.
      frozenset() # Create an empty frozenset from an iterable.
      frozenset(iterable) # Create a frozenset from an iterable.
  • Dictionaries

    • The concept of mapping

      • Key-value pair
      • Mutable
      • Unordered
    • A collection of key/value pairs.

    • Keys in a dictionary

      • Can be different types
      • Hashable (therefore, a frozenset can be the data structure for keys in a dictionary.)
    • Values in a dictionary

      • Can be different types
      {'name':'Mary', 'gender':60}    # Normal dictionary literal
      {} # Empty dictionary literal
      dict() # Empty dictionary
      dict(name='Mary', gender=60)
      dict([('name', 'Mary'), ('gender', 60)]) # Dictionary constructed from a list of tuples.
      dict.fromkeys(iterable, value)
  • None: a null object.

  • Callables: functions

    • Built-in functions
    • User-defined functions
    • Types: which can be considered as the constructor of a class.
    • Methods
  • Boolean

Sequence operations

Sequences in general

  • len:to get the length of any container.

  • max

  • min

  • sum

  • +: the operators for concatenation of two sequences.

  • S * n: a sequence multiplied by an integer, then the result sequence is the concatenation of n copies of S.

  • x in S: test if the element x is in the sequence S.

  • Sequence slicing

    • S[i:j]: N.B. the element S[j] is excluded.
    • S[i:j:k]: i is the starting index, j is the pass-the-end index, k is the stride.

Lists

x = [1, 2, 3, 4]
del x[1] # Delete the 2nd element from x.
x[2:3] = [] # Delete the 3rd element from x.
x[2:2] = ['a','b'] # Insert a list ['a', 'b'] before the 2nd element.

Set operations

  • Test membership: k in S

  • Set methods

    • S.copy(): shallow copy of a set.

    • Common set operations

      • S1.intersection(S2)
      • S1.union(S2)
      • S1.difference(S2)
      • S1.symmetric_difference(S2): $\{x \vert x \notin S1 \cap S2\}$
      • S1.issubset(S2)
      • S1.issuperset(S2)

Dictionary operations

  • Test membership: k in D

  • Indexing a dictionary

    • Use key as the index
    d = {'1': 'hello', '2':'world'}
    d['1']
    d['2']
  • Dictionary methods

    • D.copy(): shall copy of a dictionary.
    • D.get(k): get the value corresponding to the key k.
    • D.items(): returns an iterable of type dict_items.
    • D.keys(): returns an iterable of type dict_keys.
    • D.values(): returns an iterable of type dict_values.

Control flow statements

if statement

if predicate:
statement
elif predicate:
statement
...
else:
statement

while statement

while expression:
statement
...

for statement

# General form.
for element in iterable:
statement
... # Accept multiple values by unpacking the assignment.
for key, value in dict_items:
statement
...

The usage of iterator in a for loop

# The equivalent formulation of the for loop using iterator.
# iter returns the iteration before the first item in the linear data.
current_iter = iter(iterable)
while True:
# N.B. next first move the iterator to the next, then returns the object the iterator points to. When the iterator passes then end of the linear data, an exception StopIteration is raised.
try: current_object = next(current_iter)
except StopIteration: break print(current_object)

The usage of range in a for loop

range(start, stop, stride): the generated range does not include stop.

In v3, range returns an object similar to xrange in v2. Therefore, to obtain a normal list, the list function should be called:

# Generate a normal list from a range.
list(range(1, 11))

List comprehension

It is used for generating a list by iterating through a list and performing some operations if some condition is satisfied.

my_list = list(range(1, 11))
print([x + 1 for x in my_list])
print([x + 1 for x in my_list if x >= 5])
my_list_of_sublists = [list(range(1, 6)), list(range(5, 11)), list(range(10, 16))]
print([x + 1 for sublist in my_list_of_sublists for x in sublist])

Set comprehension

Similar as the list comprehension, but use bracket to wrap the resulting set.

Dictionary comprehension

Similar as the set comprehension, but the returned element should be a pair.

Functions

  • Functions are objects in Python.
def function_name(parameters):
function body
...

Parameters

  • The names of parameters exist in the function's local namespace.

  • Types of parameters

    • Positional parameters: mandatory parameters.

    • Named parameters: optional parameters.

      • Declaration in the function signature: identifier = expression
      • The default value assigned to a named parameter is only initialized once in a Python program.
      • If the default value assigned to a named parameter is a mutable, its value can be changed inside the function body.
    • Special forms

      • *args: it is used to collect any extra positional arguments into a tuple.
      • **kwds: it is used to collect any extras named arguments into a dictionary.
    • Keyword-only parameters (V3)

      • When the function is called, keyword-only parameters must appear in the form of "identifier = expression", otherwise they should not appear.
      • They come between *args and **kwds. If there is no *args, a * should be used as a placeholder.
      • They can be specified in the parameter list with or without a default value. Then, the former is mandatory parameters and the latter is an optional parameters.

Attributes of function objects

  • __name__: identifier stringed the function name.
  • __defaults__: a tuple of the optional parameters, if there are any.
  • __doc__: docstring of the function. Use triple-quotation for the docstring.

Namespaces

  • global: it is used to declare a name to be used is in the global name space.
  • nonlocal (v3 only): it is used to declare a name to be searched in the lexical scope.
  • Nested function can access values from outer local variables, which is known as a closure. In this way, a function can be dynamically constructed depending on some variables.

Lambda expressions

It is useful for creating a simple function on-the-fly.

lambda parameters: expression

Recursion

Python dose not implement the tail-recursion as in List or Scheme.

Notes for "Python in a Nutshell"的更多相关文章

  1. study notes for python

    some useful materials Python完全新手教程 http://www.cnblogs.com/taowen/articles/11239.aspx (from taowen, B ...

  2. notes for python简明学习教程(2)

    方法是只能被该类调用的函数 print函数通常以换行作为输出结尾 字典的items方法 返回的是元组列表 即列表中的每个元素都是元组 切片左闭右开 即开始位置包含在切片中 结束位置不在 每一个对象都能 ...

  3. notes for python简明学习教程(1)

    print总是以(\n)作为结尾,不换行可以指定一个空 end='' 字符串前面+r, 原始字符串 \ 显示行连接 input()函数以字符串的形式 返回键入的内容 函数参数, 有默认值的形参要放在形 ...

  4. 70个注意的Python小Notes

    Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要.旨在注意一些细节问题,在今后项目中灵活运用 ...

  5. [Python] 学习资料汇总

    Python是一种面向对象的解释性的计算机程序设计语言,也是一种功能强大且完善的通用型语言,已经有十多年的发展历史,成熟且稳定.Python 具有脚本语言中最丰富和强大的类库,足以支持绝大多数日常应用 ...

  6. python——有一种线程池叫做自己写的线程池

    这周的作业是写一个线程池,python的线程一直被称为鸡肋,所以它也没有亲生的线程池,但是竟然被我发现了野生的线程池,简直不能更幸运~~~于是,我开始啃源码,实在是虐心,在啃源码的过程中,我简略的了解 ...

  7. Python学习资料下载地址(转)

    [转]Python学习资料和教程pdf 开发工具: Python语言集成开发环境 Wingware WingIDE Professional v3.2.12 Python语言集成开发环境 Wingwa ...

  8. 史上最全的Python电子书教程资源下载(转)

    网上搜集的,点击即可下载,希望提供给有需要的人^_^   O'Reilly.Python.And.XML.pdf 2.02 MB   OReilly - Programming Python 2nd. ...

  9. [转]Python学习资料和教程pdf

    开发工具: Python语言集成开发环境 Wingware WingIDE Professional v3.2.12 Python语言集成开发环境 Wingware WingIDE Professio ...

随机推荐

  1. python基础之小数据池、代码块、编码和字节之间换算

    一.代码块.if True: print(333) print(666) while 1: a = 1 b = 2 print(a+b) for i in '12324354': print(i) 虽 ...

  2. bzoj 2816: [ZJOI2012]网络 (LCT 建多棵树)

    链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2816 题面: http://www.lydsy.com/JudgeOnline/upload ...

  3. HDOJ5543 Pick The Sticks

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5543 题目大意:有n个金条,每个金条有长度和价值,给一个长度为L的容器,当金条在容器两端的时候,只要重 ...

  4. JVM运行时内存组成分为一些线程私

    JVM运行时内存组成分为一些线程私有的,其他的是线程共享的. 线程私有 程序计数器:当前线程所执行的字节码的行号指示器. Java虚拟机栈:java方法执行的内存模型,每个方法被执行时都会创建一个栈帧 ...

  5. SpringBoot2.0初识

    核心特性 组件自动装配: Web MVC , Web Flux , JDBC 等 激活: @EnableAutoConfiguration 配置: /META_INF/spring.factories ...

  6. [Ynoi2018]五彩斑斓的世界

    题目描述 二阶堂真红给了你一个长为n的序列a,有m次操作 1.把区间[l,r]中大于x的数减去x 2.查询区间[l,r]中x的出现次数 题解 做YNOI真**爽... 我们发现这道题的操作非常诡异,把 ...

  7. bzoj4514 数字配对

    思路 首先想到费用流. 对于每个点拆点.然后考虑我们怎样才能保证每个点只被用一次. 如果\(i\)与\(j\)满足条件.那么就从\(i\)向\(j\)连一条边并且从\(j\)向\(i\)连一条边.这样 ...

  8. 测试框架httpclent 3.获取cookie的信息,然后带cookies去发送请求

    在properties文件里面: startupWithCookies.json [ { "description":"这是一个会返回cookies信息的get请求&qu ...

  9. IIS虚拟目录内的视频文件访问出错:HTTP 错误 404.3 - Not Found 由于扩展配置问题而无法提供您请求的页面。如果该页面是脚本,请添加处理程序。如果应下载文件,请添加 MIME 映射。

    MIME类型就是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开.多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式. 我是 ...

  10. matlab中randi代替randint生成随机均匀分布信号的用法

    %%新函数  2*randi([0,1],2,1)-1   等价于老函数     2*randint(2,1)-1 函数形式:randi([imin,imax],m,n) 参数解释: [imin,im ...