Python

freeCodeCamp是Python上最受欢迎的课程之一。它是完全免费的（甚至没有任何广告）。您可以watch it on YouTube here

``````>>> 3.14
3.14
>>> 314\.    # Trailing zero(s) not required.
314.0
>>> .314    # Leading zero(s) not required.
0.314
>>> 3e0
3.0
>>> 3E0     # 'e' or 'E' can be used.
3.0
>>> 3e1     # Positive value after e moves the decimal to the right.
30.0
>>> 3e-1    # Negative value after e moves the decimal to the left.
0.3
>>> 3.14e+2 # '+' not required but can be used for exponent part.
314.0
``````

（减号）运算符在文字前没有空格：

``````>>> -3.141592653589793
-3.141592653589793
>>> type(-3.141592653589793)
<class 'float'>
``````

（加）运算符在字面之前没有空格。平时`+`

``````>>> +3.141592653589793
3.141592653589793
``````

``````>>> 0.0
0.0
>>> 00.00
0.0
>>> 00100.00100
100.001
>>> 001e0010      # Same as 1e10
10000000000.0
``````

`float` constructor

``````>>> a = 3.14         # Prefer floating point literal when possible.
>>> type(a)
<class 'float'>
>>> b = int(3.14)    # Works but unnecessary.
>>> type(b)
<class 'float'>
``````

``````>>> a = 4
>>> type(a)
<class 'int'>
>>> print(a)
4
>>> b = float(4)
>>> type(b)
<class 'float'>
>>> print(b)
4.0
>>> float(400000000000000000000000000000000)
4e+32
>>> float(.00000000000000000000000000000004)
4e-32
>>> float(True)
1.0
>>> float(False)
0.0
``````

`float`

``````>>> float('1')
1.0
>>> float('.1')
0.1
>>> float('3.')
3.0
>>> float('1e-3')
0.001
>>> float('3.14')
3.14
>>> float('-.15e-2')
-0.0015
``````

`float`

（不是数字），否定`infinity`
`infinity`
（请注意，这些字符串不区分大小写）：

``````>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('infinity')
inf
>>> float('-infinity')
-inf
``````

`bool()`

`x`

## Return Value {#return-value}

;否则它会返回`True`

## Code Sample {#code-sample}

``````print(bool(4 > 2)) # Returns True as 4 is greater than 2
print(bool(4 < 2)) # Returns False as 4 is not less than 2
print(bool(4 == 4)) # Returns True as 4 is equal to 4
print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds
print(bool(4)) # Returns True as 4 is a non-zero value
print(bool(-4)) # Returns True as -4 is a non-zero value
print(bool(0)) # Returns False as it is a zero value
print(bool('dskl')) # Returns True as the string is a non-zero value
print(bool([1, 2, 3])) # Returns True as the list is a non-zero value
print(bool((2,3,4))) # Returns True as tuple is a non-zero value
print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing
``````

Python Docs - Boolean Operations

OperationResultNotes x或y如果x为假，则为y，否则x（1）x和y如果x为假，则为x，否则y（2）不为x如果x为假，则为True，否则为False（3）。

Notes:

1. This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
2. This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

## Examples: {#examples-}

### `not`: {#not-}

``````>>> not True
False
>>> not False
True
``````

### `and`: {#and-}

``````>>> True and False    # Short-circuited at first argument.
False
>>> False and True    # Second argument is evaluated.
False
>>> True and True     # Second argument is evaluated.
True
``````

### `or`: {#or-}

``````>>> True or False    # Short-circuited at first argument.
True
>>> False or True    # Second argument is evaluated.
True
>>> False or False   # Second argument is evaluated.
False
``````

• `True`: The true value of the bool type. Assignments to `True` raise a SyntaxError .
• `False`: The false value of the bool type. Assignments to `False` raise a SyntaxError .
• `None` : The sole value of the type NoneType . None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to `None` raise a SyntaxError .

• `NotImplemented`: Special value which should be returned by the binary special methods, such as `__eg__()`, `__add__()`, `__rsub__()`, etc.) to indicate that the operation is not implemented with respect to the other type.
• `Ellipsis`: Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
• `__debug__`: True if Python was not started with an -o option.

• quit(code=None)
• exit(code=None)

• copyright
• license
• credits

``````>>> def say_hello():
...     print('Hello')
...
>>> say_hello()
Hello
``````

``````>>> a = 1
>>> b = 10
>>> def fn():
...     print(a)    # local a is not assigned, no enclosing function, global a referenced.
...     b = 20      # local b is assigned in the local symbol table for the function.
...     print(b)    # local b is referenced.
...
>>> fn()
1
20
>>> b               # global b is not changed by the function call.
10
``````

``````>>> def greet(s):
...     s = "Hello " + s    # s in local symbol table is reassigned.
...     print(s)
...
>>> person = "Bob"
>>> greet(person)
Hello Bob
>>> person                  # person used to call remains bound to original object, 'Bob'.
'Bob'
``````

``````>>> def fn(arg):
...     arg.append(1)
...
>>> a = [1, 2, 3]
>>> fn(a)
>>> a
[1, 2, 3, 1]
``````

Python类提供面向对象编程的所有标准功能：类继承机制允许多个基类，派生类可以覆盖其基类或类的任何方法，并且方法可以调用具有相同名称的基类的方法。

#### Class Definition Syntax : {#class-definition-syntax-}

``````class ClassName:
<statement-1>
...
...
...
<statement-N>
``````

#### Class Objects: {#class-objects-}

。有效的属性名称是创建类对象时类的命名空间中的所有名称。所以，如果类定义看起来像这样：

``````class MyClass:
""" A simple example class """
i = 12345

def f(self):
return 'hello world'
``````

`MyClass.f`

``````x = MyClass()
``````

（）， 像这样：

``````def __init__(self):
self.data = []
``````

``````x = MyClass()
``````

。例如，

``````class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
...

x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
``````

，你的程序将崩溃。在编码时保持一致 - 选择使用制表符或空格缩进，并在整个程序中遵循您选择的约定。

#### Code Blocks and Indentation {#code-blocks-and-indentation}

Python最显着的特点之一是使用缩进来标记代码块。考虑我们简单的密码检查程序中的if语句：

``````if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')

print('All done!')
``````

#### If/elif-statements {#if-elif-statements}

if / elif语句是具有多个条件的通用if语句。它用于制定复杂的决策。例如，假设航空公司有以下"儿童"机票价格：2岁或以下的儿童免费飞行，2岁以上但13岁以下的儿童支付打折的儿童票价，13岁或以上的任何人支付正常的成人票价。以下计划确定乘客应支付的费用：

``````# airfare.py
age = int(input('How old are you? '))
if age <= 2:
print(' free')
elif 2 < age < 13:
print(' child fare)
else:
print('adult fare')
``````

#### Conditional expressions {#conditional-expressions}

Python有一个逻辑运算符，一些程序员喜欢（有些不喜欢！）。它本质上是可以直接在表达式中使用的if语句的简写符号。考虑以下代码：

``````food = input("What's your favorite food? ")
reply = 'yuck' if food == 'lamb' else 'yum'
``````

``````food = input("What's your favorite food? ")
if food == 'lamb':
reply = 'yuck'
else:
reply = 'yum'
``````

Python中有八个比较操作。它们都具有相同的优先级（高于布尔操作的优先级）。比较可以任意链接;例如，`x < y <= z`

， 除了那个`y`

OperationMeaning`<`

`<=`
`>`
`>=`

`__le__()`
`__gt__()`
，和`__ge__()`
（一般来说，`__lt__()`
`__eq__()`

`is not`

`>`

`3 == 5 < 5`

### Equality Comparisons - "is" vs "==" {#equality-comparisons-is-vs-}

&#39;是&#39;和&#39;==&#39;之间的关键区别可以概括为：

• `is` is used to compare identity
• `==` is used to compare equality

## Example {#example}

``````myListA = [1,2,3]
``````

``````myListB = myListA
``````

``````>>> myListA == myListB # both lists contains similar elements
True
>>> myListB is myListA # myListB contains the same elements
True
``````

``````myListC = [1,2,3]
``````

``````>>> myListA == myListC
True
``````

``````>>> myListA is myListC
False # both lists have different reference
``````

• An `is` expression outputs `True` if both variables are pointing to the same reference
• An `==` expression outputs `True` if both variables contain the same data

python中的Dictionary（又名"dict"）是一种可用于存储的内置数据类型 `key-value`

`1.0`
）然后它们可以互换使用来索引相同的字典条目。 （但请注意，由于计算机将浮点数存储为近似值，因此将它们用作字典键通常是不明智的。）

``````    >>> teams = {}
>>> type(teams)
>>> <class 'dict'>
``````

``````    >>> teams = {'barcelona': 1875, 'chelsea': 1910}
>>> teams
{'barcelona': 1875, 'chelsea': 1910}
``````

``````    >>> teams['santos'] = 1787
>>> teams
{'chelsea': 1910, 'barcelona': 1875, 'santos': 1787} # Notice the order - Dictionaries are unordered !
>>> # extracting value - Just provide the key
...
>>> teams['barcelona']
1875
``````

`del`

``````    >>> del teams['santos']
>>> teams
{'chelsea': 1910, 'barcelona': 1875}
>>> teams['chelsea'] = 2017 # overwriting
>>> teams
{'chelsea': 2017, 'barcelona': 1875}
``````

`in`
keyword可用于检查dict中是否存在密钥：

``````    >>> 'sanots' in teams
False
>>> 'barcelona' in teams
True
>>> 'chelsea' not in teams
False
``````

`keys`

``````    >>> club_names = list(teams.keys())
>>> club_names
['chelsea', 'barcelona']
``````

``````    >>> players = dict( [('messi','argentina'), ('ronaldo','portugal'), ('kaka','brazil')] ) # sequence of key-value pair is passed
>>> players
{'ronaldo': 'portugal', 'kaka': 'brazil', 'messi': 'argentina'}
>>>
>>> # If keys are simple strings, it's quite easier to specify pairs using keyword arguments
...
>>> dict( totti = 38, zidane = 43 )
{'zidane': 43, 'totti': 38}
``````

``````    >>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
``````

Looping in Dictionary

``````    >>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for key in d:
...     print(key) # do something
...
x
y
z
``````

``````    >>> for key, item in d.iteritems():
...     print items
...
1
2
3
``````

``````    >>> for key, item in d.items():
...     print(key, items)
...
x 1
y 2
z 3
``````

Objects

type
，和 value

values

（属性）。例如，在javascript中`undefined`
`null`
`boolean`
`string`
`number`
，和`symbol`
（ECMAScript 2015中的新内容）是原始的。

booleans
strings
numbers
， 乃至 functions

`True`
，和`False`
objects

``````>>> id(None)
4550218168
>>> type(None)
<class 'NoneType'>
>>> dir(None)
[__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> issubclass(type(None), object)
True
``````

``````>>> id(True)
4550117616
>>> type(True)
<class 'bool'>
>>> dir(True)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(True), object)
True
``````

``````>>> id(False)
4550117584
>>> type(False)
<class 'bool'>
>>> dir(False)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(False), object)
True
``````

Strings

``````>>> id("Hello campers!")
4570186864
>>> type('Hello campers!')
<class 'str'>
>>> dir("Hello campers!")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> issubclass(type('Hello campers!'), object)
True
``````

``````>>> id(42)
4550495728
>>> type(42)
<class 'int'>
>>> dir(42)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(42), object)
True
``````

## Functions are Objects Too {#functions-are-objects-too}

Functions

，用。创建 identity
type
，和 value
。他们也可以传递给其他人 functions

``````>>> id(dir)
4568035688
>>> type(dir)
<class 'builtin_function_or_method'>
>>> dir(dir)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> issubclass(type(dir), object)
True
``````

``````>>> a = dir
>>> print(a)
<built-in function dir>
>>> a(a)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
``````

Creation:

``````    >>> empty_tuple = ()
>>> print(empty_tuple)
()
>>> type(empty_tuple)
<class 'tuple'>
>>> len(empty_tuple)
0
``````

，是例外的可选项）：

``````    >>> tuple_1 = 1, 2, 3       # Create tuple without round brackets.
>>> print(tuple_1)
(1, 2, 3)
>>> type(tuple_1)
<class 'tuple'>
>>> len(tuple_1)
3
>>> tuple_2 = (1, 2, 3)     # Create tuple with round brackets.
>>> print(tuple_2)
(1, 2, 3)
>>> tuple_3 = 1, 2, 3,      # Trailing comma is optional.
>>> print(tuple_3)
(1, 2, 3)
>>> tuple_4 = (1, 2, 3,)    # Trailing comma in round brackets is also optional.
>>> print(tuple_4)
(1, 2, 3)
``````

``````    >>> not_tuple = (2)    # No trailing comma makes this not a tuple.
>>> print(not_tuple)
2
>>> type(not_tuple)
<class 'int'>
>>> a_tuple = (2,)     # Single element tuple. Requires trailing comma.
>>> print(a_tuple)
(2,)
>>> type(a_tuple)
<class 'tuple'>
>>> len(a_tuple)
1
>>> also_tuple = 2,    # Round brackets omitted. Requires trailing comma.
>>> print(also_tuple)
(2,)
>>> type(also_tuple)
<class 'tuple'>
``````

``````    >>> print(1,2,3,4,)          # Calls print with 4 arguments: 1, 2, 3, and 4
1 2 3 4
>>> print((1,2,3,4,))        # Calls print with 1 argument: (1, 2, 3, 4,)
(1, 2, 3, 4)
>>> 1, 2, 3 == (1, 2, 3)     # Equivalent to 1, 2, (3 == (1, 2, 3))
(1, 2, False)
>>> (1, 2, 3) == (1, 2, 3)   # Use surrounding round brackets when ambiguous.
True
``````

``````    >>> empty_tuple = tuple()
>>> print(empty_tuple)
()
>>> tuple_from_list = tuple([1,2,3,4])
>>> print(tuple_from_list)
(1, 2, 3, 4)
>>> tuple_from_string = tuple("Hello campers!")
>>> print(tuple_from_string)
('H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!')
>>> a_tuple = 1, 2, 3
>>> b_tuple = tuple(a_tuple)    # If the constructor is called with a tuple for
the iterable,
>>> a_tuple is b_tuple          # the tuple argument is returned.
True
``````

Accessing elements of a `tuple`:

``````    >>> my_tuple = 1, 2, 9, 16, 25
>>> print(my_tuple)
(1, 2, 9, 16, 25)
``````

Zero indexed

``````    >>> my_tuple[0]
1
>>> my_tuple[1]
2
>>> my_tuple[2]
9
``````

Wrap around indexing

``````    >>> my_tuple[-1]
25
>>> my_tuple[-2]
16
``````

Packing and Unpacking:

`54321`
`'hello!'`

``````    >>> x, y, z = t
``````

``````    >>> t = 1, 2, 3    # Tuple packing.
>>> print(t)
(1, 2, 3)
>>> a, b, c = t    # Sequence unpacking.
>>> print(a)
1
>>> print(b)
2
>>> print(c)
3
>>> d, e, f = 4, 5, 6    # Multiple assignment combines packing and unpacking.
>>> print(d)
4
>>> print(e)
5
>>> print(f)
6
>>> a, b = 1, 2, 3       # Multiple assignment requires each variable (right)
have a matching element (left).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
``````

Immutable:

`tuples`

``````    >>> a_list = []
>>> a_tuple = (a_list,)    # A tuple (immutable) with a list (mutable) element.
>>> print(a_tuple)
([],)

>>> a_list.append("Hello campers!")
>>> print(a_tuple)         # Element of the immutable is mutated.
(['Hello campers!'],)
``````

Uses:

``````    >>> greeting = ["Hello", "campers!"]
>>> enumerator = enumerate(greeting)
>>> enumerator.next()
>>> enumerator.__next__()
(0, 'Hello')
>>> enumerator.__next__()
(1, 'campers!')
``````

### Assigning funtions to a variables: {#assigning-funtions-to-a-variables-}

``````def greet(name):
return "Hello "+name
greet_someone = greet
print greet_someone("John")
``````

Run code

### Defining functions inside other functions: {#defining-functions-inside-other-functions-}

``````def greet(name):
def get_message():
return "Hello "
result = get_message()+name
return result
print(greet("John"))
``````

Run code

### Functions can also be passed as parameters to other functions: {#functions-can-also-be-passed-as-parameters-to-other-functions-}

``````def greet(name):
return "Hello " + name
def call_func(func):
other_name = "John"
return func(other_name)
print call_func(greet)
``````

Run code

### Functions can return other functions: {#functions-can-return-other-functions-}

``````def compose_greet_func():
def get_message():
return "Hello there!"
return get_message
greet = compose_greet_func()
print(greet())
``````

Run code

### Inner functions have access to the enclosing scope {#inner-functions-have-access-to-the-enclosing-scope}

。我们在构建装饰器时会遇到的一个非常强大的模式。另外需要注意的是，Python只允许read access to the outer scope

``````def compose_greet_func(name):
def get_message():
return "Hello there "+name+"!"
return get_message
greet = compose_greet_func("John")
print(greet())
``````

Run code

## Composition of Decorators {#composition-of-decorators}

``````def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)

def p_decorate(func):
def func_wrapper(name):
return "`<p>`{0}`</p>`".format(func(name))
return func_wrapper

my_get_text = p_decorate(get_text)
print (my_get_text("John"))
``````

lorem ipsum，John dolor坐下来`</p>`

Run code

，我们只需要分配get text to the result of p

``````get_text = p_decorate(get_text)
print (get_text("John"))
``````

### Python's Decorator Syntax {#python-s-decorator-syntax}

Python使程序员通过一些创建和使用装饰器更清洁，更好syntactic sugar
。装饰得到 text we don't have to get
text = p decorator(get

``````def p_decorate(func):
def func_wrapper(name):
return "`<p>`{0}`</p>`".format(func(name))
return func_wrapper

@p_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)

print get_text("John")
``````

lorem ipsum，John dolor坐下来`</p>`

Run code

``````def p_decorate(func):
def func_wrapper(name):
return "`<p>`{0}`</p>`".format(func(name))
return func_wrapper

def strong_decorate(func):
def func_wrapper(name):
return "`<strong>`{0}`</strong>`".format(func(name))
return func_wrapper

def div_decorate(func):
def func_wrapper(name):
return "`<div>`{0}`</div>`".format(func(name))
return func_wrapper
``````

``````get_text = div_decorate(p_decorate(strong_decorate(get_text)))
``````

``````@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)

print (get_text("John"))
``````

lorem ipsum，John dolor坐下来`</strong></p></div>`

Run code

### Decorating Methods {#decorating-methods}

``````def p_decorate(func):
def func_wrapper(self):
return "`<p>`{0}`</p>`".format(func(self))
return func_wrapper

class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"
@p_decorate
def get_fullname(self):
return self.name+" "+self.family

my_person = Person()
print (my_person.get_fullname())
``````

Run code

``````def p_decorate(func):
def func_wrapper(*args, **kwargs):
return "`<p>`{0}`</p>`".format(func(*args, **kwargs))
return func_wrapper

class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"
@p_decorate
def get_fullname(self):
return self.name+" "+self.family

my_person = Person()
print (my_person.get_fullname())
``````

Run code

### Passing arguments to decorators {#passing-arguments-to-decorators}

``````def tags(tag_name):
def tags_decorator(func):
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator

@tags("p")
def get_text(name):
return "Hello "+name

print (get_text("John"))
``````

Run code

### Debugging decorated functions {#debugging-decorated-functions}

``````print (get_text.__name__)
``````

doc
，和 module

Functools to the rescue

``````from functools import wraps
def tags(tag_name):
def tags_decorator(func):
@wraps(func)
def func_wrapper(name):
return "`<{0}>`{1}`</{0}>`".format(tag_name, func(name))
return func_wrapper
return tags_decorator

@tags("p")
def get_text(name):
"""returns some text"""
return "Hello "+name

print (get_text.__name__) # get_text
print (get_text.__doc__) # returns some text
print (get_text.__module__) # __main__
``````

Run code

Python利用for循环迭代元素列表。这与C或Java不同，它使用for循环来逐步更改值并使用该值访问诸如数组之类的内容。

For循环遍历基于集合的数据结构，如列表，元组和字典。

``````for value in list_of_values:
# use value inside this block
``````

``````list_of_tuples = [(1,2), (3,4)]

for a, b in list_of_tuples:
print("a:", a, "b:", b)
``````

``````for person in load_persons():
print("The name is:", person.name)

for character in ["P", "y", "t", "h", "o", "n"]:
print("Give me a '{}'!".format(character))
``````

Iterate over the range() function

``````for i in range(10):
print(i)
``````

``````>
0
1
2
3
4
5
6
7
8
9
>
``````

``````for i in range(4,10,2): #From 4 to 9 using a step of two
print(i)
``````

``````>
4
6
8
>
``````

xrange() function

Iterate over values in a list or tuple

``````A = ["hello", 1, 65, "thank you", [2, 3]]
for value in A:
print(value)
``````

``````>
hello
1
65
thank you
[2, 3]
>
``````

Iterate over keys in a dictionary (aka hashmap)

``````fruits_to_colors = {"apple": "#ff0000",
"lemon": "#ffff00",
"orange": "#ffa500"}

for key in fruits_to_colors:
print(key, fruits_to_colors[key])
``````

``````>
apple #ff0000
lemon #ffff00
orange #ffa500
>
``````

Iterate over two lists of same size in a single loop with the zip() function

``````A = ["a", "b", "c"]
B = ["a", "d", "e"]

for a, b in zip(A, B):
print a, b, a == b
``````

``````>
a a True
b d False
c e False
>
``````

Iterate over a list and get the corresponding index with the enumerate() function

``````A = ["this", "is", "something", "fun"]

for index,word in enumerate(A):
print(index, word)
``````

``````>
0 this
1 is
2 something
3 fun
>
``````

``````for name, phonenumber in contacts.items():
print(name, "is reachable under", phonenumber)
``````

！这是一个非常糟糕的做法，会让你从高级Python开发人员那里得到很多笑声。使用内置功能`enumerate()`

``````for index, item in enumerate(shopping_basket):
print("Item", index, "is a", item)
``````

for/else statements
Pyhton允许你在for循环中使用else，当循环体中没有条件满足时执行else case。要使用我们必须使用的其他`break`

``````week_days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
today = 'Saturday'
for day in week_days:
if day == today:
print('today is a week day')
break
else:
print('today is not a week day')
``````

Iterate over a list using inline loop function

``````A = ["this", "is", "awesome", "shinning", "star"]

UPPERCASE = [word.upper() for word in A]
print (UPPERCASE)
``````

``````>
['THIS', 'IS', 'AWESOME', 'SHINNING', 'STAR']
``````

`len()`
，您还可以定义自己的功能，以便在项目中使用。

### Syntax {#syntax}

1. 关键字`def`

2. 一个功能名称

3. 括号&#39;（）&#39;，括号内的输入参数，尽管输入参数是可选的。

4. 冒号&#39;：&#39;

5. 一些要执行的代码块

6. 一个return语句（可选）

# a function with no parameters or returned values

def sayHello（）：print（"你好！"）

sayHello（）＃调用函数，&#39;你好！&#39;打印到控制台

# a function with a parameter

def helloWithName（name）：print（"Hello"+ name +"！"）

helloWithName（"Ada"）＃调用函数&#39;Hello Ada！&#39;打印到控制台

# a function with multiple parameters with a return statement

def multiply（val1，val2）：返回val1 * val2

乘以（3,5）＃将15打印到控制台

Python中的函数是使用`def`

``````# this is a basic sum function
def sum(a, b):
return a + b

result = sum(1, 2)
# result = 3
``````

``````def sum(a, b=3):
return a + b

result = sum(1)
# result = 4
``````

``````result = sum(b=2, a=2)
# result = 4
``````

``````result = sum(3, b=2)
#result = 5
result2 = sum(b=2, 3)
#Will raise SyntaxError
``````

``````s = sum
result = s(1, 2)
# result = 3
``````

### Notes {#notes}

``````print(multiply(3))  # TypeError: multiply() takes exactly 2 arguments (0 given)

print(multiply('a', 5))  # 'aaaaa' printed to the console

print(multiply('a', 'b'))  # TypeError: Python can't multiply two strings
``````

``````def myFunc():
print('this will print')
print('so will this')

x = 7
# the assignment of x is not a part of the function since it is not indented
``````

``````def double(num):
x = num * 2
return x

print(x)  # error - x is not defined
print(double(4))  # prints 8
``````

Python仅在调用函数时解释函数块，而不是在定义函数时解释。因此，即使函数定义块包含某种错误，python解释器也只会在调用函数时指出它。

`yield`

``````def my_generator():
yield 'hello'
yield 'world'
yield '!'

for item in my_generator():
print(item)

# output:
# hello
# world
# !
``````

``````g = my_generator()
print(next(g))
# 'hello'
print(next(g))
# 'world'
print(next(g))
# '!'
print(next(g))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# StopIteration
``````

``````def fib(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a + b

for x in fib(1000000):
print(x)
``````

Python支持迭代容器的概念。这是使用两种不同的方法实现的;这些用于允许用户定义的类支持迭代。

Python Docs - Iterator Types

• Objects can implement a `__iter__()` method that returns an iterator object to support iteration.

• `__iter__()`: returns the iterator object.
• `__next__()`: returns the next object of the container.iterator object = 'abc'. iter () print(iterator object) print(id(iterator object)) print(id(iterator object. iter ())) # Returns the iterator itself. print(iterator object. next ()) # Returns 1st object and advances iterator. print(iterator object. next ()) # Returns 2nd object and advances iterator. print(iterator object. next ()) # Returns 3rd object and advances iterator. print(iterator object. next ()) # Raises StopIteration Exception.

``````<str_iterator object at 0x102e196a0>
4343305888
4343305888
a
b
c
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-1-d466eea8c1b0> in <module>()
6 print(iterator_object.__next__())     # Returns 2nd object and advances iterator.
7 print(iterator_object.__next__())     # Returns 3rd object and advances iterator.
----> 8 print(iterator_object.__next__())     # Raises StopIteration Exception.

StopIteration:
``````

Python中的三元操作（通常也称为条件表达式）允许程序员执行评估并根据给定条件的真实性返回值。

`else`
`elif`

### Example {#example-1}

#### Input {#input}

``````for val in range(1, 11):
is_even = "Even" if val % 2 == 0 else "Odd"
print(val, is_even, sep=' = ')
``````

#### Output {#output}

``````1 = Odd
2 = Even
3 = Odd
4 = Even
5 = Odd
6 = Even
7 = Odd
8 = Even
9 = Odd
10 = Even
``````

Python利用了`while`

``````counter = 0
while counter < 10:
# Execute the block of code here as
# long as counter is less than 10
``````

``````days = 0
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
while days < 7:
print("Today is " + week[days])
days += 1
``````

``````Today is Monday
Today is Tuesday
Today is Wednesday
Today is Thursday
Today is Friday
Today is Saturday
Today is Sunday
``````

1. the variable 'days' is set to a value 0.
2. a variable week is assigned to a list containing all the days of the week.
3. while loop starts
4. the block of code will be executed until the condition returns 'true'.
5. the condition is 'days<7' which roughly says run the while loop until the point the variable days is less than 7
6. So when the days=7 the while loop stops executing.
7. the days variable gets updated on every iteration.
8. When the while loop runs for the first time, the line 'Today is Monday' is printed onto the console and the variable days becomes equal to 1.
9. Since the variable days is equal to 1 which is less than 7, the while loop is executed again.
10. It goes on again and again and when the console prints 'Today is Sunday' the variable days is now equal to 7 and the while loop stops executing.

。根据您的操作系统（Windows或Linux或OSX），您可能希望安装Python 3these instructions

## Using Virtual Environments {#using-virtual-environments}

。该 System Python

。相反，你可以使用Virtualenv

### Virtualenvwrapper {#virtualenvwrapper}

Virtualenvwrapper module

Cloud9
，您需要在创建新的开发环境时选择Django框。

sign是终端提示的简写，它不是命令的一部分。我的终端提示符如下所示：

``````alayek:~/workspace (master) \$
``````

`ls`

``````alayek:~/workspace (master) \$ ls
``````

``````\$ ls
``````

``````\$ mkvirtualenv py3 --python=/usr/bin/python3
``````

``````\$ workon
``````

，你可以使用`workon`

``````\$ workon py3
``````

``````(py3)alayek:~/workspace (master) \$
``````

``````\$ deactivate
``````

### Pipenv {#pipenv}

。它会自动为您的项目创建虚拟环境，并维护一个`Pipfile`

。皮彭夫很容易specify which version of Python

（未经同意，请勿转载）