fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,29 @@
---
title: Python Abs Function
localeTitle: Python Abs函数
---
`abs()`是Python 3中的内置函数用于计算任何数字的绝对值。数字的绝对值“仅表示数字与0之间的距离” 1它需要一个参数`x` 。参数甚至可以是一个[复数](https://docs.python.org/3.0/library/cmath.html) ,在这种情况下,它的[模数](http://www.mathcentre.ac.uk/resources/sigma%20complex%20number%20leaflets/sigma-complex9-2009-1.pdf)被返回。
## 论据
它需要一个参数`x` - 一个整数,或十进制,或一个复数。
## 回报价值
返回值为正数。即使传递了复数,也会返回其大小,按复数代数计算。
## 代码示例
```python
print(abs(3.4)) # prints 3.4
print(abs(-6)) # prints 6
print(abs(3 + 4j)) # prints 5, because |3 + 4j| = 5
```
[🚀运行代码](https://repl.it/CL8k/0)
[官方文件](https://docs.python.org/3/library/functions.html#abs)
### 来源
1. [数学很有趣。访问时间2017年10月25日](https://www.mathsisfun.com/numbers/absolute-value.html)

View File

@ -0,0 +1,43 @@
---
title: Python All Iterable
localeTitle: Python所有Iterable
---
`all()`是Python 3中的内置函数以及2.5版以来的Python 2用于检查[_iterable的_](https://docs.python.org/3/glossary.html#term-iterable)所有项是否为`True` 。它需要一个参数, `iterable`
## 论据
### 迭代
`iterable`参数是要检查其条目的集合。它可以是`list` `str` `dict` `tuple`等。
## 回报价值
返回值是一个布尔值。当且仅当`iterable` **所有**条目都是[真实的时](https://guide.freecodecamp.org/python/truth-value-testing) ,它返回`True` 。该函数基本上对所有元素执行布尔`AND`运算。
如果它们中的一个不是真的,则返回`False`
`all()`操作等效于(不是内部实现完全像这样)
```
def all(iterable):
for element in iterable:
if not element:
return False
return True
```
## 代码示例
```
print(all([])) #=> True # Because an empty iterable has no non-truthy elements
print(all([6, 7])) #=> True
print(all([6, 7, None])) #=> False # Because it has None
print(all([0, 6, 7])) #=> False # Because it has zero
print(all([9, 8, [1, 2]])) #=> True
print(all([9, 8, []])) #=> False # Because it has []
print(all([9, 8, [1, 2, []]])) #=> True
print(all([9, 8, {}])) #=> False # Because it has {}
print(all([9, 8, {'engine': 'Gcloud'}])) #=> True
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CL9U/0)
[官方文件](https://docs.python.org/3/library/functions.html#all)

View File

@ -0,0 +1,27 @@
---
title: Anaconda
localeTitle: 蟒蛇
---
**Anaconda**是一个包管理器环境管理器和Python发行版包含许多软件包。 Anaconda与平台无关因此无论您使用的是WindowsMacOS还是Linux都可以使用它。 Anaconda可以轻松地在本地计算机上的环境之间创建保存加载和切换。它是为Python程序创建的但它可以为任何语言打包和分发软件。 作为包管理器的Anaconda可帮助您查找和安装包。如果您需要一个需要不同版本Python的软件包则无需切换到其他环境管理器因为Anaconda也是一个环境管理器。只需几个命令您就可以设置一个完全独立的环境来运行不同版本的Python同时继续在正常环境中运行您常用的Python版本。
## 概观
开始使用conda的最快方法是通过 20分钟[conda](https://conda.io/docs/user-guide/getting-started.html)指南[入门](https://conda.io/docs/user-guide/getting-started.html) 。
`conda`命令是用于管理的主要接口 各种包装的安装。它可以:
* 查询并搜索Anaconda包索引和当前 Anaconda安装。
* 创建新的conda环境。
* 安装包并将其更新到现有的conda环境中。
提示:您可以缩写许多常用的命令选项 之前是2个破折号 `--` 到1个破折号和第一个破折号 选项的信。所以`--name``-n`是相同的,并且 `--envs``-e`是一样的。
有关每个命令的完整用法(包括缩写),请参阅 [命令参考](https://conda.io/docs/commands.html) 。
### 来源
1. [Anaconda文档](https://docs.anaconda.com/)
2. [Conda文档](https://conda.io/docs/)

View File

@ -0,0 +1,42 @@
---
title: Python Any Iterable
localeTitle: Python任何可迭代的
---
`any()`是Python 3以及2.5版以来的Python 2 `any()`中的内置函数,用于检查[_iterable的_](https://docs.python.org/3/glossary.html#term-iterable)任何项是否为`True` 。它需要一个参数, `iterable`
## 论据
### 迭代
`iterable`参数是要检查其条目的集合。它通常可以是`list` `str` `dict` `tuple`等,甚至是`file object`
## 回报价值
返回值是一个布尔值。当且仅当iterable的**所有**条目都为`False` ,或者`iterable`为空时;它返回`False` 。该函数基本上对所有元素执行布尔`OR`运算。
如果其中一个为`True` ,则返回`True`
`any()`操作等效于(内部,可能不完全像这样实现)
```
def any(iterable):
for element in iterable:
if element:
return True
return False
```
## 代码示例
```
print(any([])) #=> False
print(any({})) #=> False
print(any([None])) #=> False
print(any(['', {}, 0])) #=> False
print(any([6, 7])) #=> True
print(any([6, 7, None])) #=> True
print(any([0, 6, 7])) #=> True
print(any([9, 8, [1, 2]])) #=> True
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CL9c/0)
[官方文件](https://docs.python.org/3/library/functions.html#any)

View File

@ -0,0 +1,47 @@
---
title: Relationships between * and args
localeTitle: *和args之间的关系
---
## 在函数定义中存在\*
```Python
# How does *args work in a function definition
def hardFunc(arg1, arg2):
# create a tuple and pollute it with arguments passed to hardFunc
args=(arg1, arg2)
# print out results
print(args[0])
print(args[1])
hardFunc('hard_one', 'hard_two')
# output — Try it yourself now and in sequential snippets!
def softFunc(*args):
# at this point after calling softFunc a tuple with a name of a word
# followed by * is created automatically (in this case the name is args)
# print out results
print(args[0])
print(args[1])
softFunc('soft_one', 'soft_two')
# Now try to do something illegal
hardFunc('one', 'two', 'three')
# Now do things legally
softFunc('one', 'two', 'three')
# or even
softFunc('one', 'two', 'three', 'infinity')
# softFunc handles arbitrary amount of arguments easily by virtue of * syntax
# So using a single variable name in conjuction with * we gained the ability
# to invoke a function with arbitrary amount of arguments.
# Once again when softFunc is called the newly args
# tuple filled with provided arguments is created
# Conclusion softFunc is a more flexible/dynamic verson of a hardFunc
```

View File

@ -0,0 +1,328 @@
---
title: Basic Operators
localeTitle: 基本运营商
---
## 基本运营商
运算符是告诉解释器执行特定操作的符号(即算术,比较,逻辑等)
下面列出了Python中不同类型的运算符
1. 算术运算符
2. 关系运算符
3. 按位运算符
4. 分配运营商
5. 逻辑运算符
6. 会员运营商
7. 身份运营商
#### 算术运算符
算术运算符将两个操作数作为输入,执行计算并返回结果。
考虑表达式**“a = 2 + 3”** 。这里, `2``3`是_操作数_ `+`是_算术运算符_ 。操作的结果存储在变量a中。
操作者
描述
用法
+
对操作数执行添加
12 + 3 = 15
\-
在操作数上执行减法。 从左操作数中减去右操作数
12 - 3 = 9
\*
对操作数执行乘法运算
12 \* 3 = 36
/
对操作数执行分区。 将左操作数除以右操作数
12/3 = 4
注意当使用两个整数时Python 2和Python 3之间的结果不同。
Python 2中5/2 = 2
Python 3中5/2 = 2.5
对操作数执行模数。 返回将左操作数除以右操作数时获得的余数
163 = 1
\*\*
执行指数操作。 左操作数被提升到右操作数的幂
12 \*\* 3 = 1728
//
执行Floor Division操作。 返回右操作数跳转左操作数后获得的商的整数部分
18 // 5 = 3
注意要使结果为浮点类型其中一个操作数也必须是float类型。
#### 关系运算符
关系运算符用于比较两个操作数以确定它们之间的关系。它根据条件返回一个布尔值。
操作者
描述
用法
\>
如果左操作数大于右操作数则返回True 否则返回False
12> 3返回True
<
如果右操作数大于左操作数则返回True 否则返回False
12 <3返回False
\==
如果两个操作数相等则返回True 否则返回False
12 == 3返回False
\> =
如果左操作数大于或等于右操作数则返回True 否则返回False
12> = 3返回True
<=
如果右操作数大于或等于左操作数则返回True 否则返回False
12 <= 3返回False
=
如果两个操作数不相等则返回True 否则返回False
12= 3返回True
#### 按位运算符
按位运算符逐位对操作数执行操作
对于以下用法考虑a = 2二进制表示法10和b = 3二进制表示法11
操作者
描述
用法
对操作数执行按位AND运算
ab = 2 二进制10和11 = 10
|
对操作数执行按位OR运算
一个| b = 3 二进制10 | 11 = 11
^
对操作数执行按位XOR运算
a ^ b = 1 二进制10 ^ 11 = 01
对操作数执行按位NOT运算 翻转操作数中的每一位
~a = -3 二进制00000010=11111101
\>>
执行按位右移。将左操作数的位移位,右移指定为右操作数的位数
a >> b = 0 二进制00000010 >> 00000011 = 0
<<
执行按位左移移位左操作数的位左移指定为右操作数的位数
a << b = 16 二进制00000010 << 00000011 = 00001000
#### 分配运营商
赋值运算符用于为变量赋值这通常与其他运算符如算术按位组合其中对操作数执行操作结果分配给左操作数
考虑以下示例 **a = 18** Here `=`是赋值运算符结果存储在变量a中 **a + = 10** 这里`+=`是赋值运算符结果存储在变量a中这与a = a + 10相同
操作者
用法
\=
a = 5.将值5分配给变量a
\+ =
a + = 5相当于a = a + 5
\- =
a - = 5相当于a = a - 5
\* =
a \* = 3相当于a = a \* 3
/ =
a / = 3相当于a = a / 3
=
a= 3相当于a = a3
\*\* =
a \*\* = 3相当于a = a \*\* 3
// =
a // = 3相当于a = a // 3
=
a= 3相当于a = a3
| =
a | = 3相当于a = a | 3
^ =
a ^ = 3相当于a = a ^ 3
\>> =
a >> = 3相当于a = a >> 3
<< =
a << = 3相当于a = a << 3
#### 逻辑运算符
逻辑运算符用于基于多个条件做出决策 Python中使用的逻辑运算符是 `and` `or` `not`
操作者
描述
用法
如果两个操作数均为True则返回True 否则返回False
a和b
要么
如果任何一个操作数为True则返回True 否则返回False
a或b
如果操作数为False则返回True 否则返回False
不是
#### 会员运营商
成员资格运算符用于标识任何序列列表字符串元组的成员资格 `in``not in`会员运营商
`in`如果在序列中找到指定的值则返回True否则返回False `not in`返回true如果指定的值不是序列中发现的否则返回False
###### 示例用法
```py
a = [1,2,3,4,5]
#Is 3 in the list a?
print 3 in a # prints True
#Is 12 not in list a?
print 12 not in a # prints True
str = "Hello World"
#Does the string str contain World?
print "World" in str # prints True
#Does the string str contain world? (note: case sensitive)
print "world" in str # prints False
print "code" not in str # prints True
```
#### 身份运营商
身份运算符用于检查两个变量是否共享相同的内存位置 `is``is not`身份运营商
如果操作数引用同一个对象 `is`返回True否则返回False 如果操作数不引用同一对象 `is not`返回True否则返回False
请注意两个值相等时无需暗示它们是相同的
###### 示例用法
```py
a = 3
b = 3
c = 4
print a is b # prints True
print a is not b # prints False
print a is not c # prints True
x = 1
y = x
z = y
print z is 1 # prints True
print z is x # prints True
str1 = "FreeCodeCamp"
str2 = "FreeCodeCamp"
print str1 is str2 # prints True
print "Code" is str2 # prints False
a = [10,20,30]
b = [10,20,30]
print a is b # prints False (since lists are mutable in Python)
```

View File

@ -0,0 +1,32 @@
---
title: Python Bool Function
localeTitle: Python Bool函数
---
`bool()`是Python 3中的内置函数。此函数返回一个布尔值即True或False。它需要一个参数 `x`
## 参数
它需要一个参数, `x` 。使用标准[真值测试程序](https://docs.python.org/3/library/stdtypes.html#truth)转换`x`
## 回报价值
如果`x`为false或省略则返回`False` ;否则返回`True`
## 代码示例
```
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
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CVCS/2)
[官方文件](https://docs.python.org/3/library/functions.html#bool)

View File

@ -0,0 +1,52 @@
---
title: Python Boolean Operations
localeTitle: Python布尔运算
---
[`and`](https://docs.python.org/3/reference/expressions.html#and) [`or`](https://docs.python.org/3/reference/expressions.html#or) [`not`](https://docs.python.org/3/reference/expressions.html#not)
[Python Docs - 布尔运算](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
这些是布尔运算,按升序排序:
操作|结果|笔记
\--------- | ------------------------------------ | -----
x或y |如果x为假则为y否则为x | 1
x和y |如果x为假则为x否则为y | 2
不是x |如果x为假则为True否则为False | 3
**笔记:**
1. 这是一个短路运算符因此只有在第一个参数为False时才会计算第二个参数。
2. 这是一个短路操作符因此只有在第一个参数为True时才会计算第二个参数。
3. 没有比非布尔运算符更低的优先级因此不是a == b被解释为不是a == b而a ==不是b是语法错误。
## 例子:
### `not`
```
>>> not True
False
>>> not False
True
```
### `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`
```
>>> 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
```

View File

@ -0,0 +1,30 @@
---
title: Python Built in Constants
localeTitle: Python内置常量
---
[常量](https://docs.python.org/3/library/constants.html)
三种常用的内置常量:
* `True` _bool_类型的真正价值。赋值为`True`引发_SyntaxError_ 。
* `False` _bool_类型的错误值。赋值为`False`引发_SyntaxError_ 。
* `None` _NoneType_类型的唯一值。 None通常用于表示缺少值因为默认参数未传递给函数。分配给`None`引发_SyntaxError_ 。
其他内置常量:
* `NotImplemented` :特殊值,应该由二进制特殊方法返回,例如`__eg__()` `__add__()` `__eg__()` `__add__()` `__rsub__()`等),以指示操作未针对其他类型实现。
* `Ellipsis` :特殊值主要与扩展切片语法一起用于用户定义的容器数据类型。
* `__debug__` 如果Python没有使用-o选项启动 `__debug__` True。
站点模块添加的常量 站点模块(在启动期间自动导入,除非给出了-S命令行选项向内置命名空间添加了几个常量。它们对交互式解释器shell很有用不应该在程序中使用。
打印时的对象打印消息如“使用退出或Ctrl-D即EOF退出”并在调用时使用指定的退出代码引发SystemExit
* 退出(代码=无)
* 出口(代码=无)
打印时的对象,打印“类型许可证()以查看完整的许可证文本”等消息,并在调用时,以类似寻呼机的方式显示相应的文本(一次一个屏幕):
* 版权
* 执照
* 学分

View File

@ -0,0 +1,53 @@
---
title: Python Calling Functions
localeTitle: Python调用函数
---
函数定义语句不执行该函数。执行(调用)函数是通过使用函数的名称,后跟括起所需参数(如果有)的括号来完成的。
```
>>> 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
```
调用函数调用的实际参数(参数)在被调用函数的本地符号表中引入;因此使用call by value传递参数其中值始终是对象引用而不是对象的值。当函数调用另一个函数时将为该调用创建一个新的本地符号表。
```
>>> 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]
```

View File

@ -0,0 +1,71 @@
---
title: Class
localeTitle: 类
---
## 类
类提供了将数据和功能捆绑在一起的方法。 创建新类会创建一种新类型的对象,从而允许创建该类型的新实例。 每个类实例都可以附加属性以维护其状态。 类实例还可以具有用于修改其状态的方法(由其类定义)。
与其他编程语言相比Python的类机制添加的类最少 新的语法和语义。它是C ++中的类机制的混合体。 Python类提供面向对象编程的所有标准功能 类继承机制允许多个基类, 派生类可以覆盖其基类或类的任何方法, 并且方法可以调用具有相同名称的基类的方法。 对象可以包含任意数量和种类的数据。 与模块一样类也参与Python的动态特性 它们是在运行时创建的,可以在创建后进一步修改。
#### 类定义语法:
最简单的类定义形式如下所示:
```python
class ClassName:
<statement-1>
...
...
...
<statement-N>
```
#### Class Objects:
Class objects support two kinds of operations: attribute references and instantiation.
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.
So, if the class definition looked like this:
```
蟒蛇 class MyClass “”一个简单的示例类“”“ 我= 12345
```
def f(self):
return 'hello world'
```
```
Then `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. `__doc__` is also a valid attribute, returning the docstring belonging to the class: `"A simple example class"`.
Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):
```
蟒蛇 x = MyClass
```
Creates a new instance of the class and assigns this object to the local variable x.
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:
```
蟒蛇 def **init** self self.data = \[\]
```
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:
```
蟒蛇 x = MyClass
```
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__()`. For example,
```
蟒蛇 类复杂: def **init** selfrealpartimagpart self.r = realpart self.i = imagpart ...
x =复数3.0-4.5
> > > xrxi 3.0-4.5 \`\`\`

View File

@ -0,0 +1,48 @@
---
title: Python Code Blocks and Indentation
localeTitle: Python代码块和缩进
---
在Python中编码时通常不要混合制表符和空格。这样做可能会导致`TabError` ,并且您的程序将崩溃。在编码时保持一致 - 选择使用制表符或空格缩进,并在整个程序中遵循您选择的约定。
#### 代码块和缩进
Python最显着的特点之一是使用缩进来标记代码块。考虑我们简单的密码检查程序中的if语句
\`\`\`python 如果pwd =='apple' 打印('登录...' 其他: 打印('密码错误。'
打印('全部完成!'
```
The lines print('Logging on ...') and print('Incorrect password.') are two separate code blocks. These ones happen to be only a single line long, but Python lets you write code blocks consisting of any number of statements.
To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.
In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to. For instance, the final print('All done!') is not indented, and so is not part of the else-block.
Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.
#### If/elif-statements
An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions. For example, suppose an airline has the following “child” ticket rates: Kids 2 years old or younger fly for free, kids older than 2 but younger than 13 pay a discounted child fare, and anyone 13 years or older pays a regular adult fare. The following program determines how much a passenger should pay:
```
蟒蛇
# airfare.py
age = int输入'你多大了?' 如果年龄<= 2 打印('免费' elif 2 <年龄<13岁 打印'儿童票价 其他 打印'成人票价'
```
After Python gets age from the user, it enters the if/elif-statement and checks each condition one after the other in the order they are given. So first it checks if age is less than 2, and if so, it indicates that the flying is free and jumps out of the elif-condition. If age is not less than 2, then it checks the next elif-condition to see if age is between 2 and 13. If so, it prints the appropriate message and jumps out of the if/elif-statement. If neither the if-condition nor the elif-condition is True, then it executes the code in the else-block.
#### Conditional expressions
Python has one more logical operator that some programmers like (and some don't!). It's essentially a shorthand notation for if-statements that can be used directly within expressions. Consider this code:
```
蟒蛇 food = input“你最喜欢的食物是什么 如果食物=='羊''其他'yum',回复='yuck'
```
The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either 'yuck' or 'yum'. It's equivalent to the following:
```
蟒蛇 food = input“你最喜欢的食物是什么 如果食物=='羊肉' 回复='哎' 其他 回复='yum' \`\`\`
条件表达式通常比相应的if / else语句短但不够灵活或易于阅读通常您应该在使代码更简单时使用它们
[Python文档 - 缩进](https://docs.python.org/3/reference/lexical_analysis.html#indentation)

View File

@ -0,0 +1,38 @@
---
title: Python Commenting Code
localeTitle: Python评论代码
---
注释用于注释描述或解释复杂或难以理解的代码。当解释器编译为字节码时Python会故意忽略注释。 [`PEP 8`](https://www.python.org/dev/peps/pep-0008/#comments)有一个处理注释的部分。它们还通过添加简单和描述性语言来增加代码的可读性,以便更好地理解。
**阻止**和**内联**注释以`#`开头,后跟注释前的空格:
```python
# This is a block comment.
print('Hello world!') # This is an inline commment.
```
Python没有包含编写多行注释的正式方法。跨越多行的注释的每一行应以`#`和空格开头:
```python
# This is the first line of a multiline comment.
# This is the second line.
```
另一种评论是**文档字符串** ,记录在[`PEP 257`](https://www.python.org/dev/peps/pep-0257/) 。文档字符串是一种特定类型的注释,它将成为`__doc__`属性。
要使字符串文字成为文档字符串,它必须以`\"\"\"`开头和结尾,并且是它正在记录的模块,函数,类或方法定义的第一个语句:
```python
class SomeClass():
"""Summary line for SomeClass.
More elaborate descriptions may require using a
a multiline docstring.
"""
def method_a(self):
"""Single line summary of method_a."""
pass
```
`"""`开头和结尾的字符串文字不是文档字符串(不是第一个语句),可以用于多行字符串。它们不会成为`__doc__`属性。如果它们没有分配给变量,它们将不会生成字节码。关于将它们用作[此处的](http://stackoverflow.com/questions/7696924/multiline-comments-in-python)多行注释,有一些讨论。

View File

@ -0,0 +1,84 @@
---
title: Python Comparisons
localeTitle: Python比较
---
[Python文档 - 比较](https://docs.python.org/3/library/stdtypes.html#comparisons)
Python中有八个比较操作。它们都具有相同的优先级高于布尔操作的优先级。比较可以任意链接;例如, `x < y <= z`等效于`x < y and y <= z` ,除了`y`仅被评估一次(但在两种情况下,当`x < y`被发现为假时,根本不评估`z` )。
此表总结了比较操作:
操作|含义
\--------- | -----------------------
`<` |严格不足
`<=` |小于或等于 `>` |严格大于 `>=` |大于或等于 `==` |等于 `!=` |不等于 `is` |对象身份
`is not` |否定了对象的身份
除了不同的数字类型之外,不同类型的对象永远不会相等。此外,某些类型(例如,函数对象)仅支持简并比较概念,其中该类型的任何两个对象都是不相等的。在将复数与另一个内置数值类型进行比较时,当对象具有无法比较的不同类型时,或者在没有定义的其他情况下, `<` `<=` `>``>=`运算符将引发`TypeError`异常排序。
除非类定义`__eq__()`方法,否则类的非相同实例通常会比较为不相等。
除非该类定义了足够多的方法`__lt__()` `__le__()` `__gt__()``__ge__()` ,否则不能对相同类的其他实例或其他类型的对象排序类的实例(一般情况下) `__lt__()``__eq__()`就足够了,如果你想要比较运算符的常规含义)。
`is``is not`运营商的行为无法定制;它们也可以应用于任何两个对象,并且永远不会引发异常。
我们还可以将`<``>`运算符链接在一起。例如, `3 < 4 < 5`将返回`True` ,但`3 < 4 > 5`将不返回`True` 。我们也可以链接相等运算符。例如, `3 == 3 < 5`将返回`True``3 == 5 < 5`将不返回`True`
### 平等比较 - “是”与“==”
在Python中有两个比较运算符允许我们检查两个对象是否相等。 `is`运算符和`==`运算符。但是,他们之间有一个关键的区别!
'是'和'=='之间的关键区别可以概括为:
* `is`用来比较**认同**
* `==`用于比较**相等**
## 例
首先在Python中创建一个列表。
```python
myListA = [1,2,3]
```
接下来,创建该列表的副本。
```python
myListB = myListA
```
如果我们使用'=='运算符或'is'运算符,两者都将产生**True**输出。
```python
>>> myListA == myListB # both lists contains similar elements
True
>>> myListB is myListA # myListB contains the same elements
True
```
这是因为myListA和myListB都指向同一个列表变量我在Python程序的开头定义了该变量。两个列表在身份和内容上完全相同。
但是,如果我现在创建一个新列表怎么办?
```python
myListC = [1,2,3]
```
执行`==`运算符仍然显示两个列表在内容方面是相同的。
```python
>>> myListA == myListC
True
```
但是,执行`is`运算符现在将生成`False`输出。这是因为myListA和myListC是两个不同的变量尽管包含相同的数据。即使它们看起来一样但它们是**不同的** 。
```python
>>> myListA is myListC
False # both lists have different reference
```
总结一下:
* 如果两个变量都指向同一个引用, `is`表达式输出为`True`
* 如果两个变量包含相同的数据,则`==`表达式输出`True`

View File

@ -0,0 +1,62 @@
---
title: Python Complex Numbers
localeTitle: Python复杂数字
---
复数具有实部和虚部,每个部分由浮点数表示。
可以使用虚构的文字创建复数的虚部,这会产生一个复数,其实部为`0.0`
```python
>>> a = 3.5j
>>> type(a)
<class 'complex'>
>>> print(a)
3.5j
>>> a.real
0.0
>>> a.imag
3.5
```
不存在用于创建具有非零实部和虚部的复数的文字。要创建非零实部复数,请将虚构文字添加到浮点数:
```python
>>> a = 1.1 + 3.5j
>>> type(a)
<class 'complex'>
>>> print(a)
(1.1+3.5j)
>>> a.real
1.1
>>> a.imag
3.5
```
或者使用[复杂的构造函数](https://docs.python.org/3/library/functions.html#complex) 。
```python
class complex([real[, imag]])
```
用于调用复杂构造函数的参数可以是任一参数的数字(包括`complex` )类型:
```python
>>> complex(1, 1)
(1+1j)
>>> complex(1j, 1j)
(-1+1j)
>>> complex(1.1, 3.5)
(1.1+3.5j)
>>> complex(1.1)
(1.1+0j)
>>> complex(0, 3.5)
3.5j
```
`string`也可以用作参数。如果将字符串用作参数,则不允许使用第二个参数
```python
>>> complex("1.1+3.5j")
(1.1+3.5j)
```

View File

@ -0,0 +1,7 @@
---
title: Python Containers
localeTitle: Python容器
---
某些对象包含对其他对象的引用;这些被称为容器。容器的示例是元组,列表和字典。引用是容器值的一部分。在大多数情况下,当我们谈论容器的价值时,我们意味着价值,而不是所包含对象的身份;但是,当我们谈论容器的可变性时,只暗示了直接包含的对象的身份。因此,如果不可变容器(如元组)包含对可变对象的引用,则如果更改了可变对象,则其值会更改。
[Python文档 - 对象值和类型](https://docs.python.org/3/reference/datamodel.html#objects-values-and-types)

View File

@ -0,0 +1,75 @@
---
title: Converting Integer to String in Python
localeTitle: 在Python中将整数转换为字符串
---
## 在Python中将整数转换为字符串
与许多其他语言不同Python在与字符串连接时不会隐式地将整数或浮点数强制转换为字符串。幸运的是Python有一个方便的内置函数`str()` ,它将传入的参数转换为字符串格式。
#### 错误的方法
来自其他语言的程序员可能会尝试执行以下字符串连接,从而产生错误:
```py
age = 18
string = "Hello, I am " + age + " years old"
```
[在repl.it上运行代码](https://repl.it/JyYH/0)
显示的错误是
```
Traceback (most recent call last):
File "python", line 3, in <module>
TypeError: must be str, not int
```
`TypeError: must be str, not int`表示必须首先将整数转换为要连接的字符串。
#### 正确的方式
简单连接示例:
```py
age = 18
print("Hello, I am " + str(age) + " years old")
# Output
# Hello, I am 18 years old
```
[在repl.it上运行代码](https://repl.it/Jz8Q/0)
使用单个字符串打印`1 2 3 4 5 6 7 8 9 10`
```py
result = ""
for i in range(1, 11):
result += str(i) + " "
print(result)
# Output
# 1 2 3 4 5 6 7 8 9 10
```
[在repl.it上运行代码](https://repl.it/KBLB/0)
#### 逐行解释上面的代码
1. 首先将变量“result”分配给空字符串。
2. For循环用于遍历数字列表。
3. 使用范围功能生成此数字列表。
4. 所以range1,11将生成一个从1到10的数字列表。
5. 在每个for循环迭代中这个'i'变量将占用1到10之间的值。
6. 在变量i = 1的第一次迭代时则变量\[result = result + stri+“(空格字符)”\]stri将作为整数值的'i'转换为字符串值。
7. 由于i = 1在第一次迭代时最终结果= 1。
8. 并且相同的过程一直持续到i = 10并且最后在最后一次迭代之后结果= 1 2 3 4 5 6 7 8 9 10。
9. 因此当我们最终在for循环后打印结果时控制台上的输出为'1 2 3 4 5 6 7 8 9 10'。
#### 更多信息:
[`str()`官方Python文档](https://docs.python.org/3/library/stdtypes.html#str)

View File

@ -0,0 +1,9 @@
---
title: Creating GUI's in Python3
localeTitle: 在Python3中创建GUI
---
# 在Python 3中创建GUI
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/java/collections/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。

View File

@ -0,0 +1,130 @@
---
title: The Python Dict
localeTitle: Python Dict
---
python中的Dictionary又名“dict”是一种内置数据类型可用于存储**`key-value`**对。这允许您将**`dict`**视为存储和组织数据的_数据库_ 。
关于字典的特殊之处在于它们的实现方式。类似哈希表的结构使其易于检查 存在 - 这意味着我们可以轻松确定字典中是否存在特定键而无需检查 每个元素。 Python解释器只需转到位置键并检查密钥是否存在。
字典几乎可以使用任意数据类型,如字符串,整数等,用于键。但是,不可清除的值, 也就是说,包含列表,字典或其他可变类型(通过值而不是通过对象标识进行比较)的值不能用作键。用于键的数字类型遵循用于数字比较的常规规则:如果两个数字比较相等(例如`1``1.0` ),则它们可以互换地用于索引相同的字典条目。 (但请注意,由于计算机将浮点数存储为近似值,因此将它们用作字典键通常是不明智的。)
字典的一个最重要的要求是密钥**必须**是唯一的。
要创建一个空字典,只需使用一对大括号:
```python
>>> teams = {}
>>> type(teams)
>>> <class 'dict'>
```
要创建包含一些初始值的非空字典,请放置以逗号分隔的键值对列表:
```python
>>> teams = {'barcelona': 1875, 'chelsea': 1910}
>>> teams
{'barcelona': 1875, 'chelsea': 1910}
```
将键值对添加到现有字典很容易:
```python
>>> 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`**运算符用于从dict中删除键值对。在已经使用的密钥再次用于存储值的情况下与该密钥关联的旧值完全丢失。另外请记住使用不存在的密钥提取值是错误的。
```python
>>> del teams['santos']
>>> teams
{'chelsea': 1910, 'barcelona': 1875}
>>> teams['chelsea'] = 2017 # overwriting
>>> teams
{'chelsea': 2017, 'barcelona': 1875}
```
**`in`** keyword可用于检查dict中是否存在密钥
```python
>>> 'sanots' in teams
False
>>> 'barcelona' in teams
True
>>> 'chelsea' not in teams
False
```
**`keys`**是一种内置_方法_ 可用于获取给定字典的键。要将dict中存在的键提取为列表
```python
>>> club_names = list(teams.keys())
>>> club_names
['chelsea', 'barcelona']
```
另一种创建字典的方法是使用**`dict()`**方法:
```python
>>> 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}
```
也可以使用Dict理解来从任意键和值表达式创建字典
```python
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
```
**在词典中循环**
简单地循环遍历字典中的键,而不是键和值:
```python
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for key in d:
... print(key) # do something
...
x
y
z
```
要循环键和值,您可以使用以下内容:
对于Python 2.x
```python
>>> for key, item in d.iteritems():
... print items
...
1
2
3
```
对Python 3.x使用**`items()`**
```python
>>> for key, item in d.items():
... print(key, items)
...
x 1
y 2
z 3
```

View File

@ -0,0 +1,118 @@
---
title: Python Floating Point Numbers
localeTitle: Python浮点数
---
有关浮点数的一般信息以及它们如何在Python中工作可以在[这里](https://docs.python.org/3/tutorial/floatingpoint.html)找到。
几乎所有Python的实现都遵循IEEE 754规范二进制浮点运算标准。更多信息可在[IEEE网站](http://grouper.ieee.org/groups/754/)上找到。
可以使用[浮点文字](https://docs.python.org/3/reference/lexical_analysis.html#floating-point-literals)创建浮动对象:
```
>>> 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`构造函数](https://docs.python.org/3/library/functions.html#float)是另一种创建`float`对象的方法。
在可能的情况下,首选创建具有浮点文字的`float`对象:
```
>>> a = 3.14 # Prefer floating point literal when possible.
>>> type(a)
<class 'float'>
>>> b = int(3.14) # Works but unnecessary.
>>> type(b)
<class 'float'>
```
但是float构造函数允许从其他数字类型创建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`对象:
```
>>> 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`构造函数也可用于表示`NaN` (非数字),负`infinity``infinity`数字表示(注意这些字符串不区分大小写):
```
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('infinity')
inf
>>> float('-infinity')
-inf
```

View File

@ -0,0 +1,18 @@
---
title: The Python Data Structures
localeTitle: Python数据结构
---
数据结构是在计算机中组织数据的特定方式,以便可以有效地使用它。 Python带有一组强大的内置数据结构。一些最常用的是 -
* 清单
* 元组
* 字典
主要是,数据结构可分为两类: -
* 可变: - 可变数据结构是一种结构,其状态可在创建后进行修改。 Python列表和字典是可变的。
* 不可变: - 不可修改不可变数据结构。示例: - 创建元组后,我们无法更新其中的值。
## 参考:
[Python数据结构](https://docs.python.org/3.7/tutorial/datastructures.html)

View File

@ -0,0 +1,165 @@
---
title: Python Integers
localeTitle: Python整数
---
python中整数的理论域是负无穷大到无穷大。实际上整数值受可用内存量的限制。
在Python 2中 **`int`** 数字适合32或64位_C长_ ,而**`long`**数字受可用内存限制。 Python 3将这两种类型统一为**`int`** ,更多信息在[PEP 237中](https://www.python.org/dev/peps/pep-0237/) 。
**使用整数文字创建`int`**
[整数文字](https://docs.python.org/3/reference/lexical_analysis.html#integer-literals)
可以使用整数文字创建_整数对象_ 。没有小数的简单数字是整数文字:
```
>>> 1234567890 # Unadorned numbers are integer literals
1234567890
>>> type(1234567890)
<class 'int'>
```
数字文字不包含符号,但是可以通过在文字前面没有空格的一元`-` 减号运算符作为前缀来创建负_整数对象_
```
>>> -1234567890
-1234567890
>>> type(-1234567890)
<class 'int'>
```
同样,可以通过在一元`+` (加号)运算符前面添加数字之前没有空格来创建正整数对象。通常`+`被忽略:
```
>>> +1234
1234
```
二进制基数2前缀 `0b``0B` 八进制基数8前缀 `0o``0O` 和十六进制基数16前缀 `0x``0X` )整数也可以使用整数文字创建:
```
>>> 0b1, 0b10, 0b11
(1, 2, 3)
>>> 0o1, 0o10, 0o11
(1, 8, 9)
>>> 0x1, 0x10, 0x11
(1, 16, 17)
```
请注意, **不允许使用**前导0表示非零整数文字
```
>>> 0 # Zero by itself is okay.
0
>>> 01 # Leading zero(s) cause SyntaxError.
File "<stdin>", line 1
01
^
SyntaxError: invalid token
```
`int` [构造函数](https://docs.python.org/3/library/functions.html#int)是另一种创建_整数对象的方法_ 。
```
class int(x=0)
class int(x, base=10)
```
在可能的情况下首选创建具有整数文字的_整数对象_
```
>>> a = 1 # Prefer integer literal when possible.
>>> type(a)
<class 'int'>
>>> b = int(1) # Works but unnecessary.
>>> type(b)
<class 'int'>
```
但是构造函数允许从其他数字类型创建_整数对象_
```
>>> a = 1.123
>>> type(a)
<class 'float'>
>>> print(a)
1.123
>>> b = int(1.123)
>>> type(b)
<class 'int'>
>>> print(b)
1
```
对浮点数使用`int`构造函数会将数字截断为零:
```
>>> int(-1.23)
-1
>>> int(1.23)
1
```
内置的`boolean`常量是`bool`类的实例,并且是`int`类的子类,使它们成为一种数字类型:
```
>>> type(True)
<class 'bool'>
>>> issubclass(bool, int)
True
```
如果这对你没有意义,请不要担心。现在只记得用`boolean`对象调用int构造函数将返回_整数对象_
```
>>> int(True)
1
>>> int(False)
0
```
`int`构造函数还将从字符串中生成_整数对象_
```
>>> a = "10"
>>> type(a)
<class 'str'>
>>> b = int("10")
>>> type(b)
<class 'int'>
```
`int`构造函数的_字符串_必须表示整数文字
`int`构造函数的第二个参数是指定一个base默认值10。有效基数为0和2-36。
如果提供了显式基数,则第一个参数必须是字符串。
```
>>> int("111", 2)
7
>>> int(111, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
```
用于具有显式基础的`int`构造函数的字符串必须是该基数的有效整数文字:
```
>>> int('11', 2)
3
>>> int('12', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '12'
```
可以使用前缀和非前缀的整数文字字符串,但是,如果使用,前缀必须与提供的基数匹配。
```
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0x1101', 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '0x1101'
```
如果使用带前缀的字符串和基数0则创建的整数对象将使用前缀指定的基数。如果没有使用前缀则假定基数为10
```
>>> int('100', 0)
100
>>> int('0b100', 0)
4
>>> int('0o100', 0)
64
```

View File

@ -0,0 +1,116 @@
---
title: The Python Objects
localeTitle: Python对象
---
> 在Python中一切都是_对象_ 。
_对象_表示属性的逻辑分组。属性是数据和/或功能。在Python中创建对象时将使用_标识_ _类型_和_值_创建对象。
在其他语言中, _原始数据_是没有_属性_ (属性) _值_ 。例如在javascript `undefined` `null` `boolean` `string` `number``symbol` ECMAScript 2015中的新内容是原语。
在Python中没有原语。 `None` _布尔值_ _字符串_ _数字_甚至_函数_都是_对象_无论它们是如何创建的。
我们可以使用一些内置函数来演示:
* [`id`](https://docs.python.org/3/library/functions.html#id)
* [`type`](https://docs.python.org/3/library/functions.html#type)
* [`dir`](https://docs.python.org/3/library/functions.html#dir)
* [`issubclass`](https://docs.python.org/3/library/functions.html#issubclass)
内置常量`None` `True``False`是_对象_
我们在这里测试`None`对象。
```python
>>> 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
```
接下来,让我们检查一下`True`
```python
>>> 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
```
没理由遗漏`False`
```python
>>> 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
```
_字符串_ 即使通过字符串文字创建的也是_对象_ 。
```python
>>> 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
```
与_数字_相同
```python
>>> 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
```
## 功能也是对象
> 在Python中函数是第一类对象。
Python中的_函数_也是使用_标识_ _类型_和_值_创建的_对象_ 。它们也可以传递给其他_函数_
```python
>>> 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
```
也可以将函数绑定到名称,并使用该名称调用绑定函数:
```python
>>> 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__']
```
资源:
* [点击这里](https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/)了解更多信息。

View File

@ -0,0 +1,87 @@
---
title: The Python Range
localeTitle: Python范围
---
## Python范围
范围实际上是[不可变的序列类型](https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types) 而不是函数通常用于在for循环中循环特定次数。
**创建:**
`ranges`是使用`range`构造函数创建的。构造函数的参数是:
* `start` 包含范围的第一个值可选整数默认为0
* `stop` :独占停止值,当提供此值或更大值时,范围停止(必需整数)。
* `step` 添加到当前值以获取下一个值的量可选整数默认为1
```python
>>> range(10) # Only the stop parameter is required.
range(0, 10)
>>> range(0, 10) # Default for start parameter is 0.
range(0, 10)
>>> range(0, 10, 1) # Default for step is 1\. Start parameter is required if
step is needed.
range(0, 10)
```
**例子:**
由于`ranges`是可迭代的,因此可以将它们传递给`list``tuple`构造函数以创建这些类型的序列。使用这个事实,我们可以想象一些例子:
```python
>>> list(range(10)) # range as argument for list constructor.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tuple(range(10)) # range as argument for tuple constructor.
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
```
零长度`ranges`
```python
>>> list(range(10, 0)) # start greater than stop with postive step.
[]
>>> list(range(10, 10)) # start equal to stop with postive step.
[]
>>> list(range(10, 10, -1)) # start equal to stop with negative step.
[]
>>> list(range(0, 10, -1)) # start less than stop with negative step.
[]
```
带步长参数的`ranges`
```python
>>> list(range(0, 10, 2)) # next value would be 10, stops at 8.
[0, 2, 4, 6, 8]
>>> list(range(0, 10, 3)) # next value would be 12, stops at 9.
[0, 3, 6, 9]
>>> list(range(0, 10, 4)) # next value would be 12, stops at 8.
[0, 4, 8]
>>> list(range(10, 0, -1)) # negative step makes decreasing ranges.
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list(range(-5, -30, -3)) # negative integers are valid arguments.
[-5, -8, -11, -14, -17, -20, -23, -26, -29]
```
**优点:**
使用`range`的好处是,无论指定的范围有多大,只需要少量内存来存储`range` 即startstop和step的值。在迭代时计算`ranges`的各个值。
```python
>>> import sys
>>> a_range = range(1000000)
>>> a_list = list(a_range)
>>> a_tuple = tuple(a_range)
>>> sys.getsizeof(a_range)
48
>>> sys.getsizeof(a_list)
9000112
>>> sys.getsizeof(a_tuple)
8000048
```
### 更多信息:
[Python Doc - Ranges](https://docs.python.org/3/library/stdtypes.html#ranges)
**TODO方法`ranges`是否实现**

View File

@ -0,0 +1,13 @@
---
title: The Python Scopes
localeTitle: Python范围
---
**TODO注意**
* 这属于代码块和缩进信息附近。
* 这也与变量有关,因为名称查找和绑定与范围有关。
**TODO内容**
* `global`
* `nonlocal`

View File

@ -0,0 +1,36 @@
---
title: The Python Strings
localeTitle: Python字符串
---
Python允许`str`对象或_字符串_以几种不同的方式表达
* 单引号: `'Single quote strings can have "double" quotes inside.'`
* 双引号: `"Double quote strings can have 'single' quotes inside."`
* 三重引用:
```
"""Triple quoted strings can span multiple lines.
Unescaped "double" and 'single' quotes in triple quoted strings are retained."""
'''Triple quoted strings can be 'single'or "double" quotes.
Unescaped newlines are also retained.'''
```
* 不可变:创建后不能直接编辑/更改Python字符串。例如如果您尝试直接重新分配/更改字符串中的第一个字母,则会引发错误。
```
>>> foo = "my string"
>>> foo[0] = "a"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
```
## 参考:
[文本序列类型_str_](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)

View File

@ -0,0 +1,196 @@
---
title: The Tuples
localeTitle: 元组
---
## 元组
元组是一系列Python对象。元组是不可变的这意味着它们在创建后不能被修改这与列表不同。
**创建:**
使用一对圆括号`()`创建一个空`tuple`
```shell
>>> empty_tuple = ()
>>> print(empty_tuple)
()
>>> type(empty_tuple)
<class 'tuple'>
>>> len(empty_tuple)
0
```
通过用逗号分隔元素来创建带元素的`tuple` (围绕圆括号, `()` ,可选,但有例外):
```shell
>>> 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)
```
具有单个元素的`tuple`必须具有尾随逗号(带或不带圆括号):
```shell
>>> 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'>
```
在歧义的情况下需要圆括号(如果元组是更大表达式的一部分):
> 请注意,它实际上是一个逗号,它产生一个元组,而不是括号。括号是可选的,除了空元组情况,或者需要它们以避免语法歧义。例如, `f(a, b, c)`是具有三个参数的函数调用,而`f((a, b, c))`是以3元组作为唯一参数的函数调用。
```shell
>>> 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
```
一个`tuple`也可以与创建的`tuple`的构造函数:
```shell
>>> 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
```
**访问`tuple`元素:**
访问`tuples`元素并以与`lists`相同的方式编制索引。
```shell
>>> my_tuple = 1, 2, 9, 16, 25
>>> print(my_tuple)
(1, 2, 9, 16, 25)
```
_零索引_
```shell
>>> my_tuple[0]
1
>>> my_tuple[1]
2
>>> my_tuple[2]
9
```
_包裹索引_
```shell
>>> my_tuple[-1]
25
>>> my_tuple[-2]
16
```
**包装和拆包:**
声明`t = 12345, 54321, 'hello!'`是元组封装的一个例子:值`12345` `54321``'hello!'`在元组中包装在一起。反向操作也是可能的:
```shell
>>> x, y, z = t
```
这足够恰当地称为序列解包,适用于右侧的任何序列。序列解包需要在等号左侧有尽可能多的变量,因为序列中有元素。请注意,多重赋值实际上只是元组打包和序列解包的组合。
```shell
>>> 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)
```
**一成不变的:**
`tuples`是不可变的容器,保证**其**对象它们含有不会改变。它并**不能**保证它们包含的对象不会改变:
```shell
>>> 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!'],)
```
**用途:**
函数只能返回单个值,但是,异构`tuple`可用于从函数返回多个值。一个例子是内置的`enumerate`函数,它返回一个可迭代的异构`tuples`
```shell
>>> greeting = ["Hello", "campers!"]
>>> enumerator = enumerate(greeting)
>>> enumerator.next()
>>> enumerator.__next__()
(0, 'Hello')
>>> enumerator.__next__()
(1, 'campers!')
```
### 更多信息:
[Python文档 - 元组](https://docs.python.org/3/library/stdtypes.html#tuples)

View File

@ -0,0 +1,263 @@
---
title: Python Decorators
localeTitle: Python装饰器
---
装饰器基本上用作包装器。它们在目标函数执行之前和之后修改代码的行为,而无需修改函数本身,增加原始功能,从而对其进行修饰。
在详细介绍装饰器之前有一些概念应该是清楚的。在Python中函数是对象我们可以用它们做很多有用的东西。
> ### 为变量分配功能:
```
def greet(name):
return "Hello "+name
greet_someone = greet
print greet_someone("John")
```
> 输出:你好约翰
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXGk)
> ### 在其他函数中定义函数:
```
def greet(name):
def get_message():
return "Hello "
result = get_message()+name
return result
print(greet("John"))
```
> 输出:你好约翰
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXGu)
> ### 函数也可以作为参数传递给其他函数:
```
def greet(name):
return "Hello " + name
def call_func(func):
other_name = "John"
return func(other_name)
print call_func(greet)
```
> 输出:你好约翰
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHC)
> ### 函数可以返回其他函数:
>
> 换句话说,函数生成其他函数。
```
def compose_greet_func():
def get_message():
return "Hello there!"
return get_message
greet = compose_greet_func()
print(greet())
```
输出:你好!
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHG)
> ### 内部函数可以访问封闭范围
>
> 通常称为[闭合](http://www.shutupandship.com/2012/01/python-closures-explained.html) 。我们在构建装饰器时会遇到的一个非常强大的模式。另外需要注意的是Python只允许[对外部作用域](http://www.tech-thoughts-blog.com/2013/07/writing-closure-in-python.html)进行[读访问](http://www.tech-thoughts-blog.com/2013/07/writing-closure-in-python.html)而不进行赋值。注意我们如何修改上面的例子来从内部函数的封闭范围中读取“name”参数并返回新函数。
```
def compose_greet_func(name):
def get_message():
return "Hello there "+name+"!"
return get_message
greet = compose_greet_func("John")
print(greet())
```
> 输出:你好约翰!
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHI)
## 装饰的组成
函数装饰器只是现有函数的包装器。将上面提到的想法放在一起我们可以建立一个装饰器。在这个例子中让我们考虑一个用p标签包装另一个函数的字符串输出的函数。
```
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"))
```
> 输出: `<p>` lorem ipsumJohn dolor sit amet `</p>`
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHL)
那是我们的第一个装饰师。将另一个函数作为参数的函数,生成一个新函数,扩充原始函数的工作,并返回生成的函数,以便我们可以在任何地方使用它。要让`get_text`本身由`p_decorate` 我们只需要将get _text_分配给_p_ decorate _的结果_
```
get_text = p_decorate(get_text)
print (get_text("John"))
```
> 输出lorem ipsumJohn dolor坐下来
另一件需要注意的事情是我们的装饰函数采用了名称参数。我们在装饰器中所做的就是让get\_text的包装器传递该参数。
> ### Python的装饰器语法
Python通过一些[语法糖](http://en.wikipedia.org/wiki/Syntactic_sugar)使程序员创建和使用装饰器更清洁和更好。要装饰获取_文本我们不必得到_ text = p _装饰器获取_文本有一个简洁的快捷方式这就是提到要装饰的函数之前的装饰函数的名称。装饰器的名称应该用@符号进行附加
```
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")
```
> 输出: `<p>` lorem ipsumJohn dolor sit amet `</p>`
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHN)
现在让我们考虑我们想用2个其他函数来装饰我们的get\_text函数以在字符串输出周围包装div和strong标签。
```
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将符合
```
get_text = div_decorate(p_decorate(strong_decorate(get_text)))
```
使用Python的装饰器语法可以通过更具表现力的功能实现同样的功能。
```
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print (get_text("John"))
```
> 输出: `<div><p><strong>` lorem ipsumJohn dolor sit amet `</strong></p></div>`
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHQ)
这里需要注意的一件重要事情是设置装饰器的顺序很重要。如果上面的示例中的顺序不同,则输出会有所不同。 ##装饰方法在Python中,方法是期望它们的第一个参数是对当前对象的引用的函数。我们可以以相同的方式为方法构建装饰器,同时在包装器函数中考虑自我。
```
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())
```
> 输出: `<p>` John Doe `</p>`
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXH2)
一个更好的方法是使我们的装饰器对函数和方法都很有用。这可以通过将[\* args和\*\* kwargs](http://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists)作为包装器的参数来完成,然后它可以接受任意数量的参数和关键字参数。
```
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())
```
> 输出: `<p>` John Doe `</p>`
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXH5)
### 将参数传递给装饰器回顾上面的示例之前的示例,您可以注意到示例中装饰器的冗余程度。 3个装饰器div _decoratep_ decoratestrong\_decorate每个装饰具有相同的功能但用不同的标签包装字符串。我们绝对可以做得更好。为什么没有一个更通用的实现以使标记作为字符串包装是的
```
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"))
```
> 输出: `<p>` Hello John `</p>`
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXH6)
在这种情况下需要做更多的工作。装饰器期望接收函数作为参数,这就是为什么我们必须构建一个函数来获取那些额外的参数并动态生成装饰器。在上面的示例标签中,是我们的装饰器生成器。调试修饰函数在一天结束时,装饰器只是包装我们的函数,如果调试可能会有问题,因为包装函数不包含原始函数的名称,模块和文档字符串。基于上面的例子,如果我们这样做:
```
print (get_text.__name__)
```
> 输出func _包装器输出应该是获取_文本 _get_文件的属性**名称** **doc**和**模块** _被包装器func_包装器 _覆盖_ 。显然我们可以在func\_wrapper中重新设置它们但是Python提供了很多更好的方式。### Functools救援
```
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__
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CXHb)
您可以从输出中注意到get\_text的属性现在是正确的。

View File

@ -0,0 +1,137 @@
---
title: Python defaultdict
localeTitle: Python defaultdict
---
## Python defaultdict
Dictionary是Python中最常用的数据结构之一。 字典是无序的项集合,我们通常将字符和值存储在字典中。 让我们看一下通常如何使用字典的几个例子。
```python
# dictionary declaration 1
dict1 = dict()
# dictionary declaration 2
dict2 = {}
# Add items to the dictionary
# The syntax to add and retrieve items is same for either of the two objects we defined above.
key = "X"
value = "Y"
dict1[key] = value
# The dictionary doesn't have any specific data-type.
# So, the values can be pretty diverse.
dict1[key] = dict2
```
现在让我们看一些检索方法。
```python
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]
# This key doesn't exist in the dictionary.
# So, we will get a `KeyError`
value = dict1["random"]
```
### 避免KeyError使用.get函数
如果字典中不存在给定的键Python将抛出`KeyError` 。 有一个简单的解决方法。让我们看一下如何使用the来避免`KeyError` 用于字典的内置`.get`函数。
```python
dict_ = {}
# Some random key
random_key = "random"
# The most basic way of doing this is to check if the key
# exists in the dictionary or not and only retrieve if the
# key exists. Otherwise not.
if random_key in dict_:
print(dict_[random_key])
else:
print("Key = {} doesn't exist in the dictionary".format(dict_))
```
很多时候,当密钥不存在时,我们可以获得默认值。例如,何时 建立一个柜台。有一种更好的方法可以从字典中获取默认值 丢失密钥而不是依赖标准的`if-else`
```python
# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]
freq = {}
for item in arr:
# Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
freq[item] = freq.get(item, 0) + 1
```
因此, `get(<key>, <defaultval>)`是一个方便的操作,用于从字典中检索任何给定键的默认值。 当我们想要将可变数据结构作为值(例如`list``set`处理时,会出现此方法的问题。
```python
dict_ = {}
# Some random key
random_key = "random"
dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}
dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
```
你看到了问题吗?
新的`set``list`不会被分配到字典的密钥。我们应该分配一个新的`list`或一`set` 在缺少值的情况下键,然后分别`append``add` 。莱伊看了一个例子。
```python
dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
```
### 避免KeyError使用defaultdict
这在大多数时候都适用。但是,有一种更好的方法可以做到这一点。一种更加`pythonic`方式。 `defaultdict`是内置dict类的子类。 `defaultdict`只是分配我们在缺少键时指定的默认值。那么,这两个步骤:
```python
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
```
现在可以合并为一个步骤。例如
```python
from collections import defaultdict
# Yet another random key
random_key = "random_key"
# list defaultdict
list_dict_ = defaultdict(list)
# set defaultdict
set_dict_ = defaultdict(set)
# integer defaultdict
int_dict_ = defaultdict(int)
list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1
"""
defaultdict(<class 'list'>, {'random_key': ['Hello World!']})
defaultdict(<class 'set'>, {'random_key': {'Hello World!'}})
defaultdict(<class 'int'>, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)
```
* * *
[官方文件](https://docs.python.org/2/library/collections.html)

View File

@ -0,0 +1,24 @@
---
title: Python Defining Functions
localeTitle: Python定义函数
---
[Python文档](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)
我们可以创建一个将Fibonacci系列写入任意边界的函数
```
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
```
[`def`](https://docs.python.org/3/reference/compound_stmts.html#def)关键字引入了函数定义。它必须后跟函数名称和带括号的形式参数列表。构成函数体的语句从下一行开始,必须缩进。
函数体的第一个语句可以选择是字符串文字;此字符串文字是函数的文档字符串或[docstring](https://www.python.org/dev/peps/pep-0257/) (有关文档[字符串的](https://www.python.org/dev/peps/pep-0257/)更多信息请参阅文档字符串部分。有些工具使用文档字符串自动生成在线或印刷文档或让用户以交互方式浏览代码。在你编写的代码中包含docstrings是一种很好的做法所以尽量养成习惯。

View File

@ -0,0 +1,27 @@
---
title: Difference between Python 'is' and '==' operators
localeTitle: Python'是'和'=='运算符之间的区别
---
`is`是检查对象标识 - 即检查两个或多个变量是否指向同一个对象。你不能超载`is`
如果变量引用的对象相等,则`==`计算结果为true。您可以通过`__eq__`运算符重载`==`
## 回报价值
两者的返回值可以是`True``False`
## 代码示例
```
a = 2.3
a is 2.3 # => False
a == 2.3 # => True
a = [234,123,321]
b = [234,123,321]
a == b # => True
a is b # => False
a = b
a == b # => True
a is b # => True, because if we change a, b changes too
```

View File

@ -0,0 +1,67 @@
---
title: Docstring
localeTitle: 文档字符串
---
## 文档字符串
Docstring是开发人员向其他开发人员传达Python中函数的用途参数要求和用法的一种方式。它允许简化代码维护和理解。
与传统的源代码注释不同docstring应该描述什么 功能,不是如何。
与Docstring类似的例子是Java中的@Javadoc
Docstring在Python中的声明标题之后写成多行注释。 docstring有4个不同的部分
1. 输入类型和输出类型
* 输入/输出可以是`obj, list, bool, int, str, float`
2. 功能说明
* 简要但详尽地描述了您的功能
3. 要求
* 这是由人类阅读的,因此不必是代码
4. 测试用例通常为2-3
一般格式如下。
## Docstring的格式
```python
def my_examplefunc(input_type1, input_type2):
'''(input_type1, input_type2) -> output_type # Your first line will be the input/output. Remember the space around the arrow!
Here is a description of my example function # Your second line will be the description
REQ: type(input_type1) == list # Your next line (or lines) will be the requirements for the input of your function
REQ: type(input_type2) == str
>>> my_example_func([2, 3], "Hello World!") # After the requirements come test cases
[2, 3] "Hello World"
>>> my_example_func([7, 2], "Another test case") # Your first line of the test case is an example of the usage, prefaced by >>>
[7, 2] "Another test case" # Your second line of the test case is the output
>>> my_example_func([5, 6], "Last test case")
[5, 6] "Last test case"
'''
# Your code goes here, underneath the Docstring
```
使用示例可以最好地理解Docstring因此请查看下面的示例程序如果数字小于5程序将输出True如果数字大于5则输出False。
## 例1
```python
def is_less_than_five(some_number):
'''(int) -> bool
Returns True if the given number is less than 5, and False is the given number is greater than 5.
REQ: some_number != 5
>>> is_less_than_five(4)
True
>>> is_less_than_five(6)
False
>>> is_less_than_five(100000)
False
'''
# Your code goes here
```
### 一些有用的链接:
Numpy和Google Docstrings是两种常用的方法
* Googlehttp//sphinxcontrib-napoleon.readthedocs.io/en/latest/example\_google.html
* Numpyhttp//sphinxcontrib-napoleon.readthedocs.io/en/latest/example\_numpy.html 另外请参阅一些旧的PEP评论https//www.python.org/dev/peps/pep-0257/

View File

@ -0,0 +1,36 @@
---
title: Python Escape Sequences
localeTitle: Python转义序列
---
可以在[此处](https://docs.python.org/3/reference/lexical_analysis.html#strings)找到转义序列列表
转义序列允许将特殊字符包含在字符串中。
```
>>> print('Single quote strings can have \'single\' quotes if they are escaped')
"Single quote strings can have 'single' quotes if they are escaped"
>>> print("Double quote strings can have \"double\" quotes if they are escaped")
'Double quote strings can have "double" quotes if they are escaped'
>>> print("Multiline strings\ncan be created\nusing escape sequences.")
Multiline strings
can be created
using escape sequences.
>>> print("Backslashes \\ need to be escaped.")
Backslashes \ need to be escaped.
```
可以通过在字符串前加上`r``R`来使用_原始_字符串这允许包含反斜杠而无需转义它们 -
```
>>> print(r"Backslashes \ don't need to be escaped in raw strings.")
Backslashes \ don't need to be escaped in raw strings.
>>> print(r"An odd number of backslashes at the end of a raw string will cause an error\")
File "<stdin>", line 1
print(r"An odd number of backslashes at the end of a raw string will cause an error\")
^
SyntaxError: EOL while scanning string literal.
```
#转义序列的一些例子。 逃脱序列
\\打印反斜杠
\`打印单引号
“打印双引号
\\ ASCII铃声响铃铃声例如xterm \\ b ASCII退格BS删除前一个字符 \\ n添加换行符。

View File

@ -0,0 +1,32 @@
---
title: Exceptions and Errors Handling
localeTitle: 异常和错误处理
---
## 异常和错误处理
在创建程序时,我们可能会犯错,最终会出现错误,而最糟糕的程序会停止运行, 如果我们在代码中找不到错误或错误,那会更烦人。 简单来说,错误是程序员在编写程序时避免的。 要在python中解决这个问题我们可以使用`try``except`
例:
```shell
>>> try:
>>> . . . print "this is not a string "+1
>>> except:
>>> . . . print "error"
error
```
如果您想从代码中更详细地获取错误消息,可以添加`except Exception as err`参数`except Exception as err`
```shell
>>> try:
>>> . . . print "this is not a string "+1
>>> except Exception as err:
>>> . . . print "error:\n"+str(err)
error:
cannot concatenate 'str' and 'int' objects
```
更多信息:
错误和例外[文档](https://docs.python.org/2/tutorial/errors.html) 。

View File

@ -0,0 +1,115 @@
---
title: Files and IO
localeTitle: 文件和IO
---
## 文件和IO
文件是磁盘上的命名位置用于存储相关信息。它用于将数据永久存储在非易失性存储器例如硬盘中。由于随机存取存储器RAM是易失性的当计算机关闭时会丢失其数据因此我们使用文件将来使用数据。
当我们想要读取或写入文件时,我们需要先打开它。完成后,需要关闭它,以便释放与文件绑定的资源。
因此在Python中文件操作按以下顺序进行 1打开一个文件 2读或写执行操作 3关闭文件
Python有许多输入和输出操作方式。某些输出操作可以是打印文本控制台日志甚至可以输出文本或电子表格文件。
### 输出到屏幕
Python提供了生成屏幕输出的最简单方法。
```python
print "Python is a powerful language.","It is easy to learn."
```
输出:
```
Python is a powerful language.It is easy to learn.
```
### 来自用户的输入
有两种方法可以从用户那里获取输入。
的raw\_input\[提示\]
用于从标准输入读取一行并将其作为字符串返回
```python
str = raw_input("Enter your name: ")
print "Welcome ", str
```
输出:
```
Enter your name: John Doe
Welcome John Doe
```
输入(提示)
与raw\_input类似的功能但假设输入是有效的Python表达式
```python
str = input("Enter input: ")
print "Input: ", str
```
输出:
```
Enter input: [x*5 for x in range(2,10,2)]
Input: [10,20,30,40]
```
### 在Python中与文件交互
使用Python可以轻松打开读取写入和关闭文件。有了可用的功能
1. `open()`
2. `read()`
3. `write()`
4. `close()`
例:
```python
file1 = open("foo.txt", "r+") # Opens the file with read permission.
file1.write("Python is a powerful language.It is easy to learn.") # Writes data into the file.
data = file1.read(15) # Reads first 15 characters in the file.
print "First 15 characters are:\n", data # Prints output
file1.close() # Closes the opened file.
```
输出:
```
First 15 characters are:
Python is a pow
```
#### 打开文件
python方法open可用于返回文件对象。它最常用于两个参数即文件名和访问模式。访问模式用于描述访问或使用文件的方式。
最常用的模式是'w',用于写入文件,'r'用于读取文件,'r +'用于读写文件。 'a'是用于将文本附加到文件中的模式。 mode参数也是可选的如果省略则将被假定为'r'。
在输入和输出操作完成后,必须关闭文件以释放任何资源。
打开文本文件的示例代码:
\`\`\`python file = open'hello\_world.txt''w' file.write'Hello World' file.close
```
##### Using with
An alternative to using the `open()` function in standalone is to make use of the `with` statement to open a file. This is considered best practice as it allows the Python framework to manage the context of opening the file, and will autmoatically perform any required resource cleanup.
This is adventageous in the fact that it takes the onus off the programmer to close every file that is opened, and that the file will still be closed even if an exception was encountered during an IO operation.
When using the `with` statement is important to note that access to the file will only available within the scope of the `with` block.
To open a file using the `with` statement the `with` keyword is entered, followed by the call to `open(file)`. Following this the variable used as a handle to the open file is declared after the `as` keyword. Once the programs execution returns from this block, the file will be closed automatically.
Sample code to open a text file using the `with` statement:
```
用open'hello\_world.txt''w'作为f f.write'Hello World' \`\`\`
#### 更多信息:
[Python文档 - IO](https://docs.python.org/2/tutorial/inputoutput.html) [自动化无聊的东西](https://automatetheboringstuff.com/chapter8/) [教程点 - Python IO](https://www.tutorialspoint.com/python/python_files_io.htm) [8 PEP 343'with'声明](https://docs.python.org/2.5/whatsnew/pep-343.html)

View File

@ -0,0 +1,184 @@
---
title: For Loop Statements
localeTitle: 对于循环语句
---
## 对于循环语句
Python利用for循环迭代元素列表。与C或Java不同后者使用for循环在步骤中更改值并使用该值访问诸如数组之类的内容。
For循环遍历基于集合的数据结构如列表元组和字典。
基本语法是:
```python
for value in list_of_values:
# use value inside this block
```
通常您可以使用任何内容作为迭代器值其中可以为iterable的条目赋值。例如您可以从元组列表中解压缩元组
```python
list_of_tuples = [(1,2), (3,4)]
for a, b in list_of_tuples:
print("a:", a, "b:", b)
```
另一方面,您可以遍历任何可迭代的东西。您可以调用函数或使用列表文字。
```python
for person in load_persons():
print("The name is:", person.name)
```
```python
for character in ["P", "y", "t", "h", "o", "n"]:
print("Give me a '{}'!".format(character))
```
使用For循环的一些方法
**迭代range函数**
```python
for i in range(10):
print(i)
```
范围实际上是一个不可变的序列类型,而不是一个函数。 输出将包含来自下限的结果即0到上限即10但不包括10.默认情况下,下限或起始索引设置为零。 输出:
```
>
0
1
2
3
4
5
6
7
8
9
>
```
另外,可以通过添加第二和第三参数来指定序列的下限甚至序列的步骤。
```python
for i in range(4,10,2): #From 4 to 9 using a step of two
print(i)
```
输出:
```
>
4
6
8
>
```
**xrange函数**
在大多数情况下xrange和range在功能方面完全相同。它们都提供了一种生成整数列表供您使用的方法但是您可以随意使用。唯一的区别是range返回一个Python列表对象xrange返回一个xrange对象。这意味着xrange实际上并不像运行时那样在运行时生成静态列表。它使用称为yielding的特殊技术根据需要创建值。该技术与一种称为生成器的对象一起使用。
还有一件事要补充。在Python 3.x中xrange函数不再存在。范围函数现在执行xrange在Python 2.x中的功能
**迭代列表或元组中的值**
```python
A = ["hello", 1, 65, "thank you", [2, 3]]
for value in A:
print(value)
```
输出:
```
>
hello
1
65
thank you
[2, 3]
>
```
**迭代字典中的键也称为hashmap**
```python
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
>
```
**使用zip函数在单个循环中迭代两个相同大小的列表**
\`\`\`蟒蛇 A = \[“a”“b”“c”\] B = \[“a”“d”“e”\]
对于ab为拉链AB 打印aba == b
```
Output:
```
\> 真的 bd错误 是的假 >
```
**Iterate over a list and get the corresponding index with the enumerate() function**
```
蟒蛇 A = \[“this”“is”“something”“fun”\]
对于索引枚举中的单词A 打印(索引,单词)
```
Output:
```
\> 0这个 1是 2件事 3有趣 >
```
A common use case is iterating over a dictionary:
```
蟒蛇 名称contacts.items中的phonenumber print名称“可以在”phonenumber下
```
If you absolutely need to access the current index of your iteration, do **NOT** use `range(len(iterable))`! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function `enumerate()` instead:
```
蟒蛇 对于index枚举项shopping\_basket print“Item”index“is a”item
```
**for/else statements**
Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of `break` statement so that we can break out of the loop on a satsfied condition.If we do not break out then the else part will be executed.
```
蟒蛇 周日_\= \['星期一''星期二''星期三''星期四''星期五'\] 今天='星期六' 对于天工作日_ if day == today 打印('今天是一周工作日' 打破 其他: 打印('今天不是一周工作日'
```
In the above case the output will be `today is not a week day` since the break within the loop will never be executed.
**Iterate over a list using inline loop function**
We could also iterate inline using python, for example if we need to uppercase all the words in a list from a list we could simply do the following:
```
蟒蛇 A = \[“this”“is”“awesome”“shinning”“star”\]
UPPERCASE = \[Word中的单词的\[word.upper\] 打印(大写)
```
Output:
```
\> \['这''是''太棒了''SHINNING''明星'\] > \`\`\`
#### 更多信息:
* [Python2 for循环文档](https://docs.python.org/2.7/tutorial/controlflow.html#for-statements)
* [Python3 for循环文档](https://docs.python.org/3/tutorial/controlflow.html#for-statements)

View File

@ -0,0 +1,35 @@
---
title: Python from X Import Y
localeTitle: 来自X Import Y的Python
---
如果您已经阅读了`import statements` wiki那么您已经看到我在其中一个示例中使用了此语句。今天我们将尝试了解它的作用
所以拿起同样的例子:
```
>>> from math import ceil, sqrt
>>> # here it would be
>>> sqrt(36)
<<< 6
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CS5t/1)
或者我们可以使用这个:
```
>>> import math
>>> # here it would be
>>> math.sqrt(36)
<<< 6
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CS5u)
然后我们的代码看起来像`math.sqrt(x)`而不是`sqrt(x)` 。发生这种情况是因为当我们使用`import x` ,创建名称空间`x`本身就是为了避免名称冲突。您必须以`x.<name>`访问模块的每个对象。但是当我们使用`from x import y`我们同意将`y`添加到主全局命名空间。因此,在使用它时,我们必须确保在程序中没有具有相同名称的对象。
> **如果名为`y`的对象已存在,则永远不要使用`from x import y`**
例如,在`os`模块中有一个方法`open` 。但我们甚至有一个名为`open`的内置函数。所以,这里我们应该避免使用`from os import open`
我们甚至可以使用`form x import *` ,这会将该模块的所有方法,类导入到程序的全局命名空间中。这是一个糟糕的编程习惯。请避免它。
一般来说,你应该避免`from x import y`因为它可能会导致大规模程序出现问题。例如你永远不知道同事程序员是否想要创建一个恰好是现有函数之一的新函数。您也不知道Python是否会更改要导入函数的库。虽然如前所述这些问题不会像单独项目那样经常存在但这是不好的编程实践应该避免。

View File

@ -0,0 +1,37 @@
---
title: Python Frozenset
localeTitle: Python Frozenset
---
**`frozenset`基本信息** `frozenset`类型是一个内置的集合类型,它是不可变的和可散列的 - 它的内容在创建后不能被改变;但是,它可以用作字典键或另一组的元素。 Frozensets就像套装一样只是它们不能改变即它们是不变的。
```
>>> cities = frozenset(["Frankfurt", "Basel", "Freiburg"])
>>> cities.add("Strasbourg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>
```
`frozenset`构造函数: `frozenset([iterable])` iterable包含用于初始化frozenset的元素。可以设置iterabledictionarytuple等。如果没有传递参数 `frozenset()`方法返回一个空的冻结集。
**例子**
```
>>> vowels = ('a', 'e', 'i', 'o', 'u')
>>> fSet = frozenset(vowels)
>>> print("The frozen set is: ", fSet)
The frozen set is: frozenset({'i', 'e', 'a', 'u', 'o'})
>>> print("The empty frozen set is: ", frozenset())
The empty frozen set is: frozenset()
>>>
```
**另一个例子**
```
>>> person = {"name": "John", "age": 23, "sex": "male"}
>>> fSet = frozenset(person)
>>> print("The frozen set is: ", fSet)
The frozen set is: frozenset({'sex', 'name', 'age'})
>>>
```
**附加信息** [Python Frozenset](https://www.programiz.com/python-programming/methods/built-in/frozenset) [设置类型 - 设置,冷冻设置](https://docs.python.org/2.4/lib/types-set.html) [Python教程集合和冻结集](https://www.python-course.eu/sets_frozensets.php)

View File

@ -0,0 +1,139 @@
---
title: Functions
localeTitle: 功能
---
## 功能
函数允许您定义可在程序中多次执行的可重用代码块。
功能允许您为复杂问题创建更多模块化和[DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)解决方案。
虽然Python已经提供了许多内置函数例如`print()``len()` ,但您也可以定义自己的函数以在项目中使用。
在代码中使用函数的一大优势是它减少了项目中代码行的总数。
### 句法
在Python中函数定义具有以下功能
1. 关键字`def`
2. 一个功能名称
3. paranthesis''并在paranthesis输入参数内尽管输入参数是可选的。
4. 冒号''
5. 一些要执行的代码块
6. 返回语句(可选)
```python
# a function with no parameters or returned values
def sayHello():
print("Hello!")
sayHello() # calls the function, 'Hello!' is printed to the console
# a function with a parameter
def helloWithName(name):
print("Hello " + name + "!")
helloWithName("Ada") # calls the function, 'Hello Ada!' is printed to the console
# a function with multiple parameters with a return statement
def multiply(val1, val2):
return val1 * val2
multiply(3, 5) # prints 15 to the console
```
函数是代码块,只需调用函数即可重用。这样可以实现简单,优雅的代码重用,而无需显式重写代码段。这使代码更易读,使调试更容易,并限制输入错误。
Python中的函数是使用`def`关键字创建的,后跟括号内的函数名和函数参数。
函数总是返回一个值,函数使用`return`关键字返回一个值,如果你不想返回任何值,则返回默认值`None`
函数名称用于调用函数,在括号内传递所需的参数。
```python
# this is a basic sum function
def sum(a, b):
return a + b
result = sum(1, 2)
# result = 3
```
您可以为参数定义默认值这样Python将解释该参数的值是默认值如果没有给出。
```python
def sum(a, b=3):
return a + b
result = sum(1)
# result = 4
```
您可以使用参数名称按所需顺序传递参数。
```python
result = sum(b=2, a=2)
# result = 4
```
但是,无法在非关键字参数之前传递关键字参数
```Python
result = sum(3, b=2)
#result = 5
result2 = sum(b=2, 3)
#Will raise SyntaxError
```
函数也是对象,因此您可以将它们分配给变量,并像函数一样使用该变量。
```python
s = sum
result = s(1, 2)
# result = 3
```
### 笔记
* 如果函数定义包含参数,则在调用函数时必须提供相同数量的参数。
```python
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
```
* 函数将运行的代码块包括函数内缩进的所有语句。
```python
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
```
* 函数中定义的变量仅存在于该函数的范围内。
```python
def double(num):
x = num * 2
return x
print(x) # error - x is not defined
print(double(4)) # prints 8
```
\-Python仅在调用函数时解释函数块而不是在定义函数时解释函数块。即使函数定义块包含某种错误python解释器也只会在函数被调用时指出。
### 更多信息:
* [Python 3 Docs定义函数](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)

View File

@ -0,0 +1,60 @@
---
title: Generators
localeTitle: 发电机
---
## 发电机
生成器是一种特殊类型的函数,它允许您在不结束函数的情况下返回值。它通过使用`yield`关键字来实现。与`return`类似, `yield`表达式将向调用者返回一个值。两者之间的关键区别在于`yield`将暂停该函数,允许将来返回更多值。
生成器是可迭代的因此它们可以与for循环或任何其他迭代一起使用。
```python
def my_generator():
yield 'hello'
yield 'world'
yield '!'
for item in my_generator():
print(item)
# output:
# hello
# world
# !
```
与其他迭代器一样,生成器可以传递给`next`函数以检索下一个项目。当生成器没有更多值可以生成时,会引发`StopIteration`错误。
```python
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
```
当您需要创建大量值但不需要将它们全部保存在内存中时,生成器特别有用。例如,如果您需要打印第一百万个斐波那契数字,通常会返回一百万个值的列表并迭代列表以打印每个值。但是使用生成器,您可以一次返回一个值:
```python
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)
```
### 更多信息
* [PEP 255](https://www.python.org/dev/peps/pep-0255/)
* [Python Wiki](https://wiki.python.org/moin/Generators)
* [收益表文件](https://docs.python.org/2/reference/simple_stmts.html#yield)

View File

@ -0,0 +1,24 @@
---
title: Python Hex Function
localeTitle: Python十六进制函数
---
`hex(x)`是Python 3中的内置函数用于将整数转换为带有前缀“0x”的小写[十六进制](https://www.mathsisfun.com/hexadecimals.html)字符串。
## 论据
此函数接受一个参数`x` ,该参数应为整数类型。
## 返回
此函数返回带有前缀“0x”的小写十六进制字符串。
## 例
```
print(hex(16)) # prints 0x10
print(hex(-298)) # prints -0x12a
print(hex(543)) # prints 0x21f
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CV0S)
[官方文件](https://docs.python.org/3/library/functions.html#hex)

View File

@ -0,0 +1,79 @@
---
title: How to Convert Strings into Integers in Python
localeTitle: 如何在Python中将字符串转换为整数
---
## 如何在Python中将字符串转换为整数
就像内置的`str()`一样Python也提供了一个方便的内置函数它将一个字符串对象作为参数并返回相应的整数对象。
#### 用法示例:
```py
# Here age is a string object
age = "18"
print(age)
# Converting string to integer
int_age = int(age)
print(int_age)
```
产量
```py
18
18
```
虽然输出在视觉上类似,但你应该记住,第一行打印一个字符串对象,而它旁边的行打印一个整数对象,这将在下一个例子中进一步说明:
```py
age = "18"
print(age+2)
```
输出:
```py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
```
`The error should make it clear to you that you need to convert the`向其添加内容之前 `The error should make it clear to you that you need to convert the` age\`对象 `The error should make it clear to you that you need to convert the`整数。
```py
age = "18"
age_int = int(age)
print(age_int+2)
```
输出:
```py
20
```
但是你应该记住一些特殊情况:
1. 浮点(带小数部分的整数)作为参数将返回向下舍入到最接近的整数的浮点数。 例如: `print(int(7.9))`将打印`7``print(int("7.9"))`也会导致错误,因为字符串是转换为整数的无效参数。
```py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '7.9'
```
2. 如果作为参数给出,任何单词中的任何整数都将返回与上面相同的错误: `print(int("one"))`将给出如下错误:
```py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'one'
```
#### 更多信息:
可在[此处](https://docs.python.org/3.6/library/functions.html#int)找到`int()`内置的官方文档

View File

@ -0,0 +1,43 @@
---
title: Python Idobject
localeTitle: Python Idobject
---
`id()`是Python 3中的内置函数它返回对象的_标识_ 。 _标识_是该对象在其生命周期内的唯一整数。这也是内存中对象的地址。
## 论据
#### 目的
`object`参数通常可以是`int` `float` `str` `list` `dict` `tuple`等。
## 代码示例
```
a = 2
print(id(a)) #=> 140454723286976 (Values returned by id() might be different for different users)
b = 3
print(id(b)) #=> 140454723287008
c = 2
print(id(c)) #=> 140454723286976 (This is same as id(a) since they both contain the same value and hence have same memory address)
print(id(a) == id(b)) #=> False (since a and b have different values stored in them)
print(id(a) == id(c)) #=> True (since a and c have same values stored in them)
d = 1.1
e = 1.1
print(id(d) == id(e)) #=> True (since d and e have same values stored in them)
str1 = 'hello'
str2 = 'hello'
print(id(str1) == id(str2)) #=> True (since str1 and str2 have same values stored in them)
# For complex objects like lists, tuples, dictionaries etc. id() would give a unique integer even if the content of those containers is same.
tup1 = (1,1)
tup2 = (1,1)
print(id(tup1) == id(tup2)) #=> False
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CQw7/1)
[官方文件](https://docs.python.org/3/library/functions.html#id)

View File

@ -0,0 +1,96 @@
---
title: If Elif Else Statements
localeTitle: 如果Elif Else声明
---
## 如果Elif Else声明
`if` / `elif` / `else`结构是控制程序流的常用方法,允许您根据某些数据的值执行特定的代码块。如果关键字`if`后面的条件计算为`true` ,则代码块将执行: 请注意,在条件检查之前和之后不使用括号,如同其他语言一样。
```python
if True:
print('If block will execute!')
```
```python
x = 5
if x > 4:
print("The condition was true!") #this statement executes
```
如果条件为`false` ,您可以选择添加将执行的`else`响应:
```python
if not True:
print('If statement will execute!')
else:
print('Else statement will execute!')
```
或者你也可以看到这个例子
```python
y = 3
if y > 4:
print("I won't print!") #this statement does not execute
else:
print("The condition wasn't true!") #this statement executes
```
_请注意 `else`关键字后面没有条件 - 它捕获条件为`false`所有情况_
可以通过在初始`if`语句之后包含一个或多个`elif`检查来检查多个条件,但只执行一个条件:
```python
z = 7
if z > 8:
print("I won't print!") #this statement does not execute
elif z > 5:
print("I will!") #this statement will execute
elif z > 6:
print("I also won't print!") #this statement does not execute
else:
print("Neither will I!") #this statement does not execute
```
_请注意只有第一个计算为`true`条件才会执行。即使`z > 6`为`true` `if/elif/else`块`if/elif/else`在第一个真实条件之后终止。这意味着只有在没有条件`true`的情况下才会执行`else` 。_
我们还可以创建嵌套if用于决策。在此之前请参阅前面的href ='https//guide.freecodecamp.org/python/code-blocks-and-indentation'target ='\_ blank'rel ='nofollow'>缩进指南。
让我们举个例子来找一个偶数也大于'10'的数字
```
python
x = 34
if x % 2 == 0: # this is how you create a comment and now, checking for even.
if x > 10:
print("This number is even and is greater than 10")
else:
print("This number is even, but not greater 10")
else:
print ("The number is not even. So point checking further.")
```
这只是嵌套if的一个简单示例。请随时在线浏览更多内容。
虽然上面的示例很简单,但您可以使用[布尔比较](https://guide.freecodecamp.org/python/comparisons)和[布尔运算符](https://guide.freecodecamp.org/python/boolean-operations)创建复杂条件。
**_内联python if-else语句_**
我们也可以使用if-else语句内联python函数 以下示例应检查数字是否大于或等于50如果是则返回True
```
python
x = 89
is_greater = True if x >= 50 else False
print(is_greater)
```
产量
```
>
True
>
```

View File

@ -0,0 +1,97 @@
---
title: Python Import Statements
localeTitle: Python导入语句
---
在学习编程和阅读一些资源时,您会遇到“抽象”这个词,它只是意味着尽可能地减少和重用代码。
函数和模块有助于抽象。如果要在文件中重复执行某些操作,可以创建函数。
当您想要在不同的源文件中重用一组函数时,模块会出现。模块在构建程序时也很有用。
* 使用标准库和其他第三方模块:
* 构建程序
## 使用标准库
示例您可以在官方Python文档中详细了解所有标准库的方法/功能。
```
import time
for i in range(100):
time.sleep(1) # Waits for 1 second and then executes the next command
print(str(i) + ' seconds have passed') # prints the number of seconds passed after the program was started
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CS6C)
```
# To calculate the execution time of a part of program
import time
start = time.time()
# code here
end = time.time()
print('Execution time:' , end-start)
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CS6C/1)
```
# Using math Module
import math
print(math.sqrt(100)) # prints 10
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CS6C/2)
## 使用第三方模块
第三方模块没有与python捆绑在一起但我们必须使用包管理器如[`pip`](https://bootstrap.pypa.io/get-pip.py)和[`easy install`](https://bootstrap.pypa.io/ez_setup.py)在外部安装它
```
# To make http requests
import requests
rq = requests.get(target_url)
print(rq.status_code)
```
[在此处](http://docs.python-requests.org/en/master/)了解有关python-requests模块的更多信息
## 构建程序
我们想要制作一个具有关于素数的各种函数的程序。让我们开始吧。我们将在`prime_functions.py`定义所有函数
```
# prime_functions.py
from math import ceil, sqrt
def isPrime(a):
if a == 2:
return True
elif a % 2 == 0:
return False
else:
for i in range(3,ceil(sqrt(a)) + 1,2):
if a % i == 0:
return False
return True
def print_n_primes(a):
i = 0
m = 2
while True:
if isPrime(m) ==True:
print(m)
i += 1
m += 1
if i == a:
break
```
现在我们想要使用我们刚刚在`prime_functions.py`创建的函数,因此我们创建了一个新文件`playground.py`来使用这些函数。
> _请注意这个程序太简单了不能制作两个单独的文件只是为了演示。但是当有大型复杂程序时制作不同的文件确实非常有用。_
```
# playground.py
import prime_functions
print(prime_functions.isPrime(29)) # returns True
```
## 排序进口
好的做法是将`import`模块分为三组 - 标准库导入,相关的第三方导入和本地导入。在每个组中,按模块名称按字母顺序排序是明智的。您可以[在PEP8中](https://www.python.org/dev/peps/pep-0008/?#imports)找到[更多信息](https://www.python.org/dev/peps/pep-0008/?#imports) 。
Python语言最重要的一点是易读性按字母顺序排序的模块可以更快地读取和搜索。此外更容易验证某些内容是否已导入并避免重复导入。

View File

@ -0,0 +1,175 @@
---
title: Python
localeTitle: 蟒蛇
---
## 什么是Python
[Python](https://www.python.org)是一种通用编程语言,它具有动态类型,解释和着名的易读性,并具有出色的设计原则。
要了解有关Python的更多信息请查看python.org上的这些页面
[什么是Python](https://www.python.org/doc/essays/blurb/)
[Python FAQ](https://docs.python.org/3/faq/general.html) 。
## Python 2或Python 3
* 这两个版本是相似的,知道一个切换为另一个编写代码很容易。
* [Python 2或Python 3](https://wiki.python.org/moin/Python2orPython3)
* [Python 2.x将不会维持到2020年。](https://www.python.org/dev/peps/pep-0373/)
* 3.x正在积极发展中。这意味着例如所有最近的标准库改进仅在Python 3.x中默认可用。
* 多年来Python生态系统积累了大量优质软件。在3.x中打破向后兼容性的缺点是某些软件特别是公司内部的软件仍然无法在3.x上运行。
## 安装
大多数基于\* nix的操作系统都安装了Python通常是Python 2最近的Python 3。建议不要更换系统Python否则可能会导致问题。但是可以与系统Python一起安全地安装不同版本的Python。请参阅[Python设置和使用](https://docs.python.org/3/using/index.html) 。
Windows没有附带Python可以在[此处](https://docs.python.org/3/using/windows.html)找到安装程序和说明
## Python解释器
Python解释器是用于运行Python脚本的。
如果它可用并且在Unix shell的搜索路径中可以通过键入命令`python`启动它,然后脚本名称将调用解释器并运行脚本。
`hello_campers.py`
```python
print('Hello campers!')
```
从终端:
```
$ python hello_campers.py
Hello campers!
```
“当安装多个版本的Python时可以根据安装配置调用它们。在Cloud9 ide自定义环境中可以调用它们
```
$ python --version
Python 2.7.6
$ python3 --version
Python 3.4.3
$ python3.5 --version
Python 3.5.1
$ python3.6 --version
Python 3.6.2
$ python3.7 --version
Python 3.7.1
```
## Python解释器交互模式
可以通过使用`-i`标志或不带任何参数调用Python解释器来启动交互模式。
交互模式有一个提示可以输入和运行Python命令
```
$ python3.5
Python 3.5.1 (default, Dec 18 2015, 00:00:00)
GCC 4.8.4 on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello campers!")
Hello campers!
>>> 1 + 2
3
>>> exit()
$
```
## Python的禅宗
影响Python设计的一些原则包含在复活节彩蛋中可以使用Python解释器交互模式中的命令来读取
```
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
```
## Python的优点和缺点
### 优点
1. 交互式语言,模块支持几乎所有功能。
2. 开源:因此,您可以为社区做出贡献,为将来使用而开发的功能以及帮助他人
3. 许多优秀的口译员和笔记本电脑可以提供更好的体验例如jupyter笔记本电脑。
#### 缺点
1. 作为开源,一年中开发了许多不同的方式来实现相同的功能。这有时会给其他人创造混乱,让他人阅读别人的代码。
2. 这是一种缓慢的语言。因此,用于开发通用算法的语言非常糟糕。
## 文档
[Python有很好的文档记录](https://docs.python.org/3/) 。这些文档包括语言的教程,指南,参考和元信息。
另一个重要的参考是Python增强提议 [PEP](https://www.python.org/dev/peps/) )。 PEP中包含用于编写Python代码的样式指南 [`PEP 8`](https://www.python.org/dev/peps/pep-0008/) 。
## 调试
内联`print`语句可用于简单调试:
> **...通常,调试程序的最快方法是向源添加一些打印语句:快速编辑 - 测试 - 调试周期使这种简单方法非常有效。**
>
> \- [执行摘要](https://www.python.org/doc/essays/blurb/)
Python还包含更强大的调试工具例如
* 记录模块, [_记录_](https://docs.python.org/3/library/logging.html)
* 调试模块, [_pdb_](https://docs.python.org/3/library/pdb.html)
请注意,这些目前存在。
## 你好,世界!
回到文档,我们可以阅读[`print`](https://docs.python.org/3/library/functions.html#print)函数,这是[Python标准库](https://docs.python.org/3/library/index.html)的[_内置函数_](https://docs.python.org/3/library/functions.html) 。
```
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
```
内置函数按字母顺序列出。该名称后跟带括号的形式参数列表,其中包含可选的默认值。在此之下,给出了函数及其参数的简短描述,并偶尔给出一个例子。
Python 3中的[`print`](https://docs.python.org/3/library/functions.html#print)函数替换了Python 2中的[`print`](https://docs.python.org/2/reference/simple_stmts.html#print)语句。
```
>>> print("Hello world!")
Hello world!
```
当函数名称后跟`()`将调用函数。对于Hello世界例如使用字符串作为第一个参数的参数调用print函数。对于其余参数使用默认值。
我们称之为`print`函数的参数是`str`对象或_字符串_ 它是Python的[_内置类型之一_](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str) 。 关于python最重要的是你在声明变量时不必指定数据类型python的编译器 将根据分配的值类型自行完成。
`objects`参数以`*`为前缀,表示该函数将为该参数采用任意数量的参数。
## 想了解更多?
免费代码营有一些很好的资源。网络是一个很大的地方,还有很多值得探索的地方:
* Python练习册http//anandology.com/python-practice-book/index.html
* 想想Pythonhttp//greenteapress.com/thinkpython/html/index.html
* 实用商务Pythonhttp//pbpython.com/
* 另一门课程https _//realpython.com/utm source = fsputm_ medium = promoutm\_campaign = bestresources
* 一般https//www.fullstackpython.com/
* 学习基础知识https//www.codecademy.com/learn/learn-python
* 使用Python的计算机科学https//www.edx.org/course/introduction-computer-science-mitx-6-00-1x-11?ref=hackernoon#
* 学习python的更多资源列表https//github.com/vinta/awesome-python
* Interactive Pythonhttp//interactivepython.org/runestone/static/thinkcspy/index.html
* 开发人员Python指南https//devguide.python.org/

View File

@ -0,0 +1,51 @@
---
title: Python Input Function
localeTitle: Python输入函数
---
很多时候在程序中我们需要来自用户的一些输入。从用户那里获取输入使程序感觉互动。在Python 3中为了从用户那里获取输入我们有一个函数`input()` 。如果调用输入函数,程序流将停止,直到用户给出输入并用返回键结束输入。我们来看一些例子:
1. 当我们想要输入时:
# 这只会给出一个没有任何消息的提示
inp = input
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CUqX/0)
1. 要给出带有消息的提示:
_具有_消息输入=提示(” “)
# \_
# 输出中的“\_”是提示符
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CUqX/1)
3.当我们想要一个整数输入时:
```
number = int(input('Please enter a number: '))
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CUqX/2)
如果输入非整数值则Python将抛出错误`ValueError` 。 **所以每当你使用它时,请确保你也能抓住它。**否则,您的程序将在提示后意外停止。
```
number = int(input('Please enter a number: '))
# Please enter a number: as
# Enter a string and it will throw this error
# ValueError: invalid literal for int() with base 10 'as'
```
4.当我们想要一个字符串输入时:
```
string = str(input('Please enter a string: '))
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CUqX/3)
但是,输入默认存储为字符串。使用`str()`函数使代码阅读器清楚输入将是一个'字符串'。提及将事先采用何种类型的输入是一种很好的做法。
[官方文件](https://docs.python.org/3/library/functions.html#input)

View File

@ -0,0 +1,77 @@
---
title: Installing and Using Python 3
localeTitle: 安装和使用Python 3
---
## 安装Python 3
您可以从此官方[链接](https://www.python.org/downloads/)下载Python。根据您的操作系统Windows或Linux或OSX您可能希望按照[这些说明](http://docs.python-guide.org/en/latest/starting/installation/)安装Python 3。
## 使用虚拟环境
[沙盒](https://en.wikipedia.org/wiki/Sandbox_(computer_security)) Python安装总是一个好主意;并将它与您的_System Python_分开。 _System Python_是Python解释器的路径它与您的操作系统一起安装的其他模块一起使用。
使用_System Python_直接安装Python Web框架或库是**不安全的** 。相反您可以在开发Python应用程序时使用[Virtualenv](https://virtualenv.readthedocs.org/en/latest/)创建和生成单独的Python进程。
### Virtualenvwrapper
[Virtualenvwrapper模块](https://virtualenvwrapper.readthedocs.org/en/latest/)使您可以轻松地在一台计算机上管理和沙箱化多个Python沙盒环境;不破坏用Python编写并由您的机器使用的任何模块或服务。
当然,大多数云托管开发环境,如[Nitrous](https://www.nitrous.io/)或[Cloud9](https://c9.io/)也预装了这些并为您准备好编码您可以从仪表板中快速选择一个框并在激活Python 3环境后开始编码。
在[Cloud9中](https://c9.io/) 您需要在创建新的开发环境时选择Django框。
接下来会有一些shell命令示例。如果你想复制粘贴请注意`$`符号是终端提示的简写,它不是命令的一部分。我的终端提示符如下所示:
```
alayek:~/workspace (master) $
```
并且, `ls`看起来像
```
alayek:~/workspace (master) $ ls
```
但是,在本文档中编写相同的内容时,我会将其编写为
```
$ ls
```
回到我们的讨论您可以通过在云终端上运行在Cloud9上创建包含Python 3解释器的沙箱
```
$ mkvirtualenv py3 --python=/usr/bin/python3
```
在为项目创建新框后您只需运行一次。一旦执行该命令将创建一个新的沙盒virtualenv供您使用名为`py3`
要查看可用的虚拟环境,您可以使用
```
$ workon
```
要激活`py3` ,可以使用带有环境名称的`workon`命令:
```
$ workon py3
```
上面的所有三个终端命令也适用于本地Linux机器或OSX机器。这些是[virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/#introduction)命令;因此,如果您计划使用它们,请确保已安装此模块并将其添加到`PATH`变量中。
如果你在虚拟环境中;您可以通过检查终端提示轻松找到它。环境名称将在终端提示中清晰显示。
例如,当我在`py3`环境中时;我会看到这是我的终端提示:
```
(py3)alayek:~/workspace (master) $
```
注意括号中的`(py3)` !如果由于某种原因,你没有看到这个,即使你在虚拟的环境中;你可以尝试做[一下这里提到](http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv)的事情。
走出虚拟环境;或者取消激活 - 使用命令
```
$ deactivate
```
同样这仅适用于virtualenvwrapper模块。
### Pipenv
使用virtualenvwrapper的另一种方法是[Pipenv](https://docs.pipenv.org/) 。它会自动为您的项目创建虚拟环境,并维护包含依赖项的`Pipfile`文件。使用Pipenv意味着您不再需要单独使用pip和virtualenv或管理您自己的`requirements.txt`文件。对于熟悉JavaScript的人来说Pipenv类似于使用像`npm`这样的打包工具。
要开始使用Pipenv您可以按照这个非常详细的[指南进行操作](https://docs.pipenv.org/install.html#installing-pipenv) 。 Pipenv可以轻松[指定](https://docs.pipenv.org/basics.html#specifying-versions-of-python)您希望为每个项目使用[哪个版本的Python](https://docs.pipenv.org/basics.html#specifying-versions-of-python) ,从现有的`requirements.txt`文件[导入](https://docs.pipenv.org/basics.html#importing-from-requirements-txt)并[绘制](https://docs.pipenv.org/#pipenv-graph)依赖关系[](https://docs.pipenv.org/#pipenv-graph) 。

View File

@ -0,0 +1,125 @@
---
title: Is There a Way to Substring a String in Python
localeTitle: 有没有办法在Python中子串字符串
---
## 有没有办法在Python中子串字符串
Python提供了许多方法来对字符串进行子串。它通常被称为“切片”。
它遵循以下模板:
```python
string[start: end: step]
```
哪里,
`start` 子字符串的起始索引。此索引处的字符包含在子字符串中。如果不包括_start_ 则假定它等于0。
`end` 子字符串的终止索引。此索引处的字符_不_包含在子字符串中。如果未包括_end_ ,或者指定的值超出字符串长度,则默认情况下假定它等于字符串的长度。
`step` 包含当前字符后的每个“step”字符。默认值为1.如果省略_步长_值则假定它等于1。
#### 模板
`string[start:end]` 获取从index _start_到_end-1的_所有字符
`string[:end]` 获取从字符串开头到_end-1的_所有字符
`string[start:]` 获取索引_start_到字符串末尾的所有字符
`string[start:end:step]` 从_开始_到_结束-1_获取每个_步骤_字符的所有字符
#### 例子
* **获取字符串的前5个字符**
```python
string = "freeCodeCamp"
print(string[0:5])
```
输出:
```shell
> freeC
```
注意: `print(string[:5])`返回与`print(string[0:5])`相同的结果`print(string[0:5])`
* **从字符串的第3个字符获取长度为4的子字符串**
```python
string = "freeCodeCamp"
print(string[2:6])
```
输出:
```shell
> eeCo
```
请注意,开始或结束索引可能是负数。负索引意味着您从字符串的末尾开始计数而不是从开头(即从右到左)开始计数。索引-1表示字符串的最后一个字符-2表示倒数第二个字符依此类推......
* **获取字符串的最后一个字符**
```python
string = "freeCodeCamp"
print(string[-1])
```
输出:
```shell
> p
```
* **获取字符串的最后5个字符**
```python
string = "freeCodeCamp"
print(string[-5:])
```
输出:
```shell
> eCamp
```
* **获取包含除最后4个字符和第1个字符之外的所有字符的子字符串**
```python
string = "freeCodeCamp"
print(string[1:-4])
```
输出:
```shell
> reeCode
```
#### 更多例子
```py
str = freeCodeCamp
print str[-5:-2] # prints 'eCa'
print str[-1:-2] # prints '' (empty string)
```
* **从字符串中获取每个其他字符**
```python
string = "freeCodeCamp"
print(string[::2])
```
输出:
```shell
> feCdCm
```

View File

@ -0,0 +1,40 @@
---
title: Python Iterators
localeTitle: Python迭代器
---
Python支持迭代容器的概念。这是使用两种不同的方法实现的;这些用于允许用户定义的类支持迭代。
[Python文档 - 迭代器类型](https://docs.python.org/3/library/stdtypes.html#iterator-types)
迭代是以编程方式重复步骤给定次数的过程。程序员可以利用迭代对数据集合中的每个项目执行相同的操作,例如打印出列表中的每个项目。
* 对象可以实现`__iter__()`方法,该方法返回迭代器对象以支持迭代。
* 迭代器对象必须实现:
* `__iter__()` :返回迭代器对象。
* `__next__()` :返回容器的下一个对象。
iterator _object ='abc'。 **iter** print迭代器_对象 printid迭代器_对象 printiditerator_ **object。iter** ()))#返回迭代器本身。 打印迭代器_对象。 **下一个** ())#返回第一对象和前进迭代器。 打印迭代器_对象。 **下一个** ())#返回第二对象和前进迭代器。 打印迭代器_对象。 **下一个** ())#返回第三对象和前进迭代器。 打印迭代器_对象。 **下一个** 引发StopIteration异常。
输出:
```
<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:
```

View File

@ -0,0 +1,51 @@
---
title: Itertools
localeTitle: Itertools
---
Itertools是一个函数的python模块它返回生成器只在迭代时才起作用的对象。 itertool函数的一些示例包括但不限于chainimapproduct和compress
### 链()
chain函数将几个迭代器作为参数并返回一个迭代器它生成所有这些迭代器的内容就像它们来自一个序列一样。
```py
import itertools
list(itertools.chain([1, 2], [3, 4]))
# Output
# [1, 2, 3, 4]
```
### islice
islice函数返回一个迭代器它通过索引从输入迭代器返回所选项。它采用与列表的切片运算符相同的参数startstop和step。启动和停止是可选的。
```py
import itertools
list(itertools.islice(count(), 5))
# Output
# [0,1, 2, 3, 4]
```
### izip
izip返回一个迭代器它将几个迭代器的元素组合成元组。它的工作方式类似于内置函数zip除了它返回迭代器而不是列表。
```py
import itertools
list(izip([1, 2, 3], ['a', 'b', 'c']))
# Output
# [(1, 'a'),(2, 'b'),(3, 'c')]
```
组合迭代器:
迭代器参数结果 productpq... \[repeat = 1\]笛卡尔积相当于嵌套的for循环 permutationsp \[r\] r-length元组所有可能的排序没有重复的元素 组合pr r-length元组按排序顺序没有重复元素 _与_ replacementpr r-length元组的组合按排序顺序具有重复元素 产品('ABCD',重复= 2AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD 排列('ABCD'2AB AC AD BA BC BD CA CB CD DA DB DC
组合('ABCD'2AB AC AD BC BD CD
_与_替换组合'ABCD'2AA AB AC AD BB BC BD CC CD DD
来源HTTPS//docs.python.org/3/library/itertools.html

View File

@ -0,0 +1,22 @@
---
title: Python Keywords
localeTitle: Python关键字
---
## Python关键字
Python有一个不能用作标识符变量名的[关键字](https://docs.python.org/3/reference/lexical_analysis.html#keywords)列表。尝试将这些关键字中的任何一个用作变量将创建**语法错误,**并且不会运行您的Python脚本
```
>>> False = "Hello campers!"
File "<stdin>"
SyntaxError: can't assign to keyword
>>> break = "Hello campers!"
File "<stdin>", line 1
break = "Hello campers!"
^
SyntaxError: invalid syntax
```
#### 关键字列表
关键字| - | - | - | - --- | --- | --- | --- | --- `False` | `class` | `finally` | `is` | `return` `None` | `continue` | `for` | `lambda` | `try` `True` `def` | `from` | `nonlocal` `while` `and` | `del` | `global` | `not` | `with` `as` | `elif` | `if` | `or` `yield` `assert` | `else` | `import` | `pass` `break` | `except` | `in` | `raise`

View File

@ -0,0 +1,94 @@
---
title: Lambda Expressions
localeTitle: Lambda表达式
---
## Lambda表达式
Lambda表达式理想地用于我们有一些简单的事情要做我们对快速完成工作更感兴趣而不是正式命名函数。 Lambda表达式也称为匿名函数。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/python/lambda-expressions/index.md) 。
Python中的Lambda表达式是声明小型和匿名函数的简短方法没有必要为lambda函数提供名称。 Lambda函数的行为与使用`def`关键字声明的常规函数一样。当您想要以简洁的方式定义一个小函数时它们会派上用场。它们只能包含一个表达式因此它们不适合具有control-flow语句的函数。 主
#### Lambda函数的语法
`lambda arguments: expression`
Lambda函数可以包含任意数量的参数但只能包含一个表达式
#### 示例代码
```py
# Lambda function to calculate square of a number
square = lambda x: x ** 2
print(square(3)) # Output: 9
# Traditional function to calculate square of a number
def square1(num):
return num ** 2
print(square(5)) # Output: 25
```
在上面的lambda示例中 `lambda x: x ** 2`产生一个匿名函数对象,该对象可以与任何名称相关联。 因此,我们将函数对象与`square`相关联,因此从现在开始,我们可以像任何传统函数一样调用`square`对象。例如`square(10)`
## 例子
### 初学者
```py
lambda_func = lambda x: x**2 # Function that takes an integer and returns its square
lambda_func(3) # Returns 9
```
### 中间
```py
lambda_func = lambda x: True if x**2 >= 10 else False
lambda_func(3) # Returns False
lambda_func(4) # Returns True
```
### 复杂
```py
my_dict = {"A": 1, "B": 2, "C": 3}
sorted(my_dict, key=lambda x: my_dict[x]%3) # Returns ['C', 'A', 'B']
```
### 用例
假设您要从`list`过滤掉奇数。你可以使用`for`循环:
```python
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = []
for num in my_list:
if num % 2 != 0:
filtered.append(num)
print(filtered) # Python 2: print filtered
# [1, 3, 5, 7, 9]
```
You could write this as a one liner with list-comprehensions
```
蟒蛇 如果x2= 0则过滤= \[x代表\[1,2,3,4,5,6,7,8,9,10\]中的x\] \`\`\`
但是你可能会想要使用内置的`filter`功能。为什么?第一个例子有点冗长,单线程可能更难理解,因为`filter`提供两个单词中最好的。更重要的是,内置函数通常更快。
\`\`\`蟒蛇 my\_list = \[1,2,3,4,5,6,7,8,9,10\]
filtered = filterlambda xx2= 0my\_list
列表(过滤)
# \[1,3,5,7,9\]
` `` NOTE: in Python 3 built in function return generator objects, so you have to call` list `, while in Python 2 they return a` list `,` tuple `or` string\`。
发生了什么?你告诉`filter`使用`my_list`每个元素并应用lambda表达式。返回`False`的值将被过滤掉。
#### 更多信息:
* [官方文件](https://docs.python.org/3/reference/expressions.html#lambda)
* [进一步阅读](https://dbader.org/blog/python-lambda-functions)

View File

@ -0,0 +1,35 @@
---
title: Learn About Python Sets
localeTitle: 了解Python集
---
Python中的`Set`是一种可变但无序的数据结构它只能包含_唯一的_元素。
**创建:**
`set`文字:
圆括号`{}` _不能_用于创建空集
```python
>>> not_set = {} # set constructor must be used to make empty sets.
>>> type(not_set) # Empty curly brackets create empty dictionaries.
<class 'dict'>
```
您只能使用`set()`方法创建一个空集。
```python
>>> example_set = set()
>>> type(example_set)
<class 'set'>
```
但是,如果元素包含在大括号内,那么创建集合的语法是可以接受的。
```python
>>> example_set_2 = {1, 2, 3}
>>> type(example_set_2)
<class 'set'>
```
\`

View File

@ -0,0 +1,32 @@
---
title: Python Len Function
localeTitle: Python Len函数
---
`len()`是Python 3中的内置函数。此方法返回对象的长度项数。它需要一个参数`x`
## 参数
它需要一个参数, `x` 。此参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集)。
## 回报价值
此函数返回传递给`len()`函数的参数中的元素数。
## 代码示例
```
list1 = [123, 'xyz', 'zara'] # list
print(len(list1)) # prints 3 as there are 3 elements in the list1
str1 = 'basketball' # string
print(len(str1)) # prints 10 as the str1 is made of 10 characters
tuple1 = (2, 3, 4, 5) # tuple
print(len(tuple1)) # prints 4 as there are 4 elements in the tuple1
dict1 = {'name': 'John', 'age': 4, 'score': 45} # dictionary
print(len(dict1)) # prints 3 as there are 3 key and value pairs in the dict1
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CUmt/15)
[官方文件](https://docs.python.org/3/library/functions.html#len)

View File

@ -0,0 +1,32 @@
---
title: Deque
localeTitle: 和
---
## 使用列表作为队列
还可以使用列表作为队列其中需要FIFO“先进先出”操作。列表效率不高 使用追加和弹出时的队列,因为它可能会变慢,因为每个追加/弹出都必须将所有元素移动一个。
要实现队列请使用collections.deque它设计为具有快速追加和两端弹出。
#### 示例用法
```py
from collections import deque
queue = deque(["January", "February", "March", "April"] )
queue.append("May")
queue.popleft()
queue.popleft()
print "Spring months in the list: ", queue
```
#### 产量
```
Spring months in the list: deque(['March', 'April', 'May'])
```
#### 更多信息:
`collections.deque`的官方文档可以在[这里](https://docs.python.org/3/library/collections.html#collections.deque)找到

View File

@ -0,0 +1,124 @@
---
title: Lists
localeTitle: 清单
---
**TODO `list`基本信息**
[Python文档 - 列表](https://docs.python.org/3/library/stdtypes.html#lists)
**创建:**
使用一对方括号创建一个空`list`
```shell
>>> empty_list = []
>>> type(empty_list)
<class 'list'>
>>> len(empty_list)
0
```
通过用逗号分隔的带有方括号的元素`list`可以使用元素创建列表。列表允许元素具有不同类型(异构),但最常见的是单一类型(同类):
```shell
>>> homogeneous_list = [1, 1, 2, 3, 5, 8]
>>> type(homogeneous_list)
<class 'list'>
>>> print(homogeneous_list)
[1, 1, 2, 3, 5, 8]
>>> len(homogeneous_list)
6
>>> heterogeneous_list = [1, "Hello Campers!"]
>>> print(heterogeneous_list)
[1, "Hello Campers!"]
>>> len(heterogeneous_list)
2
```
`list`构造函数也可用于创建`list`
```shell
>>> empty_list = list() # Creates an empty list
>>> print(empty_list)
[]
>>> list_from_iterable = list("Hello campers!") # Creates a list from an iterable.
>>> print(list_from_iterable)
['H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!']
```
**访问`list`元素:**
```shell
>>> my_list = [1, 2, 9, 16, 25]
>>> print(my_list)
[1, 2, 9, 16, 25]
```
_零索引_
```shell
>>> my_list[0]
1
>>> my_list[1]
2
>>> my_list[2]
9
```
_包裹索引_
```shell
>>> my_list[-1]
25
>>> my_list[-2]
16
```
_解压缩python-3的列表_
```shell
>>> print(*my_list)
1 2 9 16 25
```
**易变的:**
`lists`是可变容器。可变容器是容器,允许更改容器包含的对象。 **TODO加入更多**
_重新排列列表中的元素_
可以使用另一`list`作为索引来提取和重新排列`list`元素。
```shell
>>> my_list = [1, 2, 9, 16, 25, 34, 53, 21]
>>> my_index = [5, 2, 0]
>>> my_new_list = [my_list[i] for i in my_index]
>>> print(my_new_list)
[34, 9, 1]
```
**TODO这里应讨论以下哪些方面**
[Python文档 - 有关列表的更多信息](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
* `list.append(x)`将项添加到列表的末尾。相当于\[lena\] = \[x\]。
* `list.extend(L)`通过附加给定列表中的所有项来扩展列表。相当于\[lena\] = L.
* `list.insert(i, x)`在给定位置插入一个项目。第一个参数是要插入的元素的索引因此a.insert0x插入列表的前面而a.insertlenax等同于a.append X
* `list.remove(x)`从列表中删除值为x的第一个项目。如果没有这样的项目则是错误的。
* `list.pop([i])`删除列表中给定位置的项目然后将其返回。如果未指定索引则a.pop将删除并返回列表中的最后一项。 方法签名中i周围的方括号表示该参数是可选的而不是您应该在该位置键入方括号。您将在Python Library Reference中经常看到这种表示法。
* `list.clear()`从列表中删除所有项目。相当于del a \[\]。
* `list.index(x)`返回值为x的第一个项的列表中的索引。如果没有这样的项目则是错误的。
* `list.count(x)`返回x在列表中出现的次数。
* `list.sort(key=None, reverse=False)`对列表中的项进行排序参数可用于排序自定义请参阅sorted以获取解释
* `list.reverse()`在适当的位置反转列表的元素。
* `list.copy()`返回列表的浅表副本。相当于\[\]。

View File

@ -0,0 +1,26 @@
---
title: List Append Method
localeTitle: 列出追加方法
---
## 列出追加方法
列表有很多方法您可以通过在python控制台中键入`help(list)`来探索所有这些方法。 其中之一是append函数正如名称所示附加给定列表的参数。
#### 示例用法
```py
words = ["I", "love", "Python"]
words.append("very much")
print(words)
```
#### 产量
```
["I", "love", "Python", "very much"]
```
您可能已经注意到, `"very much"`的元素会附加到列表中。
#### 更多信息:
`append()`的官方文档可以在[这里](https://docs.python.org/3.6/tutorial/datastructures.html)找到

View File

@ -0,0 +1,116 @@
---
title: List Comprehension
localeTitle: 列表理解
---
## 列表理解
List Comprehension是一种循环遍历列表以基于某些条件生成新列表的方法。它起初可能令人困惑但一旦你适应了语法它就会非常强大和快速。
学习如何使用列表理解的第一步是查看循环遍历列表的传统方式。以下是一个返回偶数数字新列表的简单示例。
```python
# Example list for demonstration
some_list = [1, 2, 5, 7, 8, 10]
# Empty list that will be populate with a loop
even_list = []
for number in some_list:
if number % 2 == 0:
even_list.append(number)
# even_list now equals [2, 8, 10]
```
首先使用一些数字创建一个列表。然后创建一个空列表用于保存循环中的结果。在循环中检查每个数字是否可被2整除如果是则将其添加到even\_list。这需要5行代码不包括注释和空格在这个例子中并不多。
现在为列表理解示例。
```python
# Example list for demonstration
some_list = [1, 2, 5, 7, 8, 10]
# List Comprehension
even_list = [number for number in some_list if number % 2 == 0]
# even_list now equals [2, 8, 10]
```
另一个例子,有两个相同的步骤: 以下将创建一个与`my_starting_list`的数字相乘的数字`my_starting_list`乘以7。
```py
my_starting_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_new_list = []
for item in my_starting_list:
my_new_list.append(item * 7)
```
运行此代码时, `my_new_list`的最终值为: `[7, 14, 21, 28, 35, 42, 49, 56]`
使用列表`my_new_list`的开发人员可以使用以下列表`my_new_list`实现相同的结果,这导致相同的`my_new_list`
```py
my_starting_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_new_list = [item * 7 for item in my_starting_list]
```
以列表理解方式编写的简单公式是:
`my_list = [{operation with input n} for n in {python iterable}]`
但是如果要更改从iterable返回的项请将`{operation with input n}`替换为。上面的例子使用`n * 7`但操作可以根据需要简单或复杂。
用任何iterable替换`{python iterable}` 。 [序列类型](https://guide.freecodecamp.org/python/sequence-types)将是最常见的。在上面的示例中使用了一个列表,但元组和范围也很常见。
如果满足某些条件,列表理解会将现有列表中的元素添加到新列表中。它更整洁,但在大多数情况下也快得多。在某些情况下,列表理解可能会妨碍可读性,因此在选择使用列表理解时,开发人员必须权衡他们的选项。
## 带条件的列表理解的例子
可以使用条件来控制列表推导中的控制流。例如:
```py
only_even_list = [i for i in range(13) if i%2==0]
```
这相当于以下循环:
```py
only_even_list = list()
for i in range(13):
if i%2 == 0:
only_even_list.append(i)
```
列表推导还可以包含嵌套的if条件。考虑以下循环
```py
divisible = list()
for i in range(50):
if i%2 == 0:
if i%3 == 0:
divisible.append(i)
```
使用列表理解,这可以写成:
```py
divisible = [i for i in range(50) if i%2==0 if i%3==0]
```
If-Else语句也可以与列表理解一起使用。
```py
list_1 = [i if i%2==0 else i*-1 for i in range(10)]
```
#### 更多信息:
[Python数据结构 - 列表](https://docs.python.org/2.7/tutorial/datastructures.html)
[Python for Loops](https://guide.freecodecamp.org/python/for-loop-statements)
[Python列表](https://guide.freecodecamp.org/python/learn-about-python-lists)
[Python初学者 - 列表理解](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python)

View File

@ -0,0 +1,25 @@
---
title: List Extend Method
localeTitle: 列表扩展方法
---
## 列表扩展方法
列表有很多方法您可以通过在python控制台中键入`help(list)`来探索所有这些方法。 其中之一是扩展函数,正如名称所示,通过将列表的所有项(作为参数传递)添加到结尾来扩展列表。
#### 示例用法
```py
cities = ["San Francisco", "Los Angeles", "New York"]
cities_in_texas = ["San Antonio", "Austin", "Dallas"]
cities.extend(cities_in_texas)
print(cities)
```
#### 产量
```
["San Francisco", "Los Angeles", "New York", "San Antonio", "Austin", "Dallas"]
```
#### 更多信息:
可以在[此处](https://docs.python.org/3.6/tutorial/datastructures.html)找到`extend()`的官方文档

View File

@ -0,0 +1,59 @@
---
title: List Index Method
localeTitle: 列表索引方法
---
## 列表索引方法
在列表数据结构附带的许多函数中, `index()`返回列表中元素的第一个出现/索引,该列表作为函数的参数给出。
列表是最基本的Python数据结构并按顺序存储值列表与字典相比哪个顺序无关紧要。我们通过数字索引检索项目。
请记住索引从0开始或者第一个元素被视为0索引让我们看看一些例子。
#### 用法示例:
```py
numbers = [1, 2, 2, 3, 9, 5, 6, 10]
words = ["I", "love", "Python", "I", "love"]
print(numbers.index(9))
print(numbers.index(2))
print(words.index("I"))
print(words.index("am"))
```
##### 输出:
```py
4
1
0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'am' is not in list
```
这里第一个输出非常明显,但第二个和第三个输出最初可能看起来很混乱。但是请记住`index()`返回元素的第一次出现,因此在这种情况下, `1``0`是索引,其中`2``"I"`首先出现分别在列表中。
此外,如果在列表中找不到元素,则返回`ValueError` ,就像在`words`列表中索引`"am"`的情况一样。
#### 可选参数:
您还可以使用可选参数将搜索限制为列表的特定子序列,如下例所示:
```py
words = ["I","am", "a", "I", "am", "Pythonista"]
print(words.index("am",2,5))
```
##### 输出:
```
4
```
这里虽然在索引2包括和5不包括之间搜索元素但返回的索引是相对于完整列表的开头而不是start参数计算的。
#### 更多信息:
`index()`的官方文档可以在[这里](https://docs.python.org/3.6/tutorial/datastructures.html)找到

View File

@ -0,0 +1,88 @@
---
title: Map, Reduce, Filter
localeTitle: 地图,减少,过滤
---
# 地图,缩小和过滤
大多数工程师使用列表来处理订单/用户列表等。如果使用多个for循环和嵌套循环分析列表会变得复杂和混乱。因此上述方法可以简化列表操作的使用。
## 地图
如果您的任务是将特定方法应用于列表的每个元素那么map将派上用场。比如您有一个度数值列表并且您希望将所有这些值转换为华氏度单位的值列表。
#### 示例用法
```py
inputs = [10,32,5,40,25]
def degreesToFahren(deg):
fahrenheit = (9.0/5)*deg +32
return fahrenheit
# The most common way of doing this
result=[]
for i in inputs:
iTofahren = degreesToFahren(i)
result.append(iTofahren)
print(result) # [50.0, 89.6, 41.0, 104.0, 77.0]
```
```py
# Using Map
result = list(map(degreesToFahren,inputs))
print(result) # [50.0, 89.6, 41.0, 104.0, 77.0]
```
您可能已经注意到使用map只是一个单行操作。通常如果你有data = `[a1,a2,...,an]`和函数`f()` ,那么`map(f,data):`返回一个迭代器而不是`f(a1),f(a2)...f(an).`使用`list()`将迭代器对象转换为python列表。
## 过滤
过滤功能会删除您需要/不需要的列表中的数据因此会删除名称。比如您希望根据不需要的值过滤列表例如高于2的值。
#### 示例用法
```py
data = [1.2,2.5,5.8,0.4,4.7,9.9]
result = list(filter(lambda x:x > 2,data))
print(result)
```
#### 产量
```
[2.5, 5.8, 4.7, 9.9]
```
这也是一个简单的1线程类似于上面的map函数。如果您发现此术语不熟悉请参阅有关lambda函数的教程。
## 减少
来自Python的创造者Guido van Rossum `"Use functools.reduce if you really need it; however, 99% of the time an explicit for loop is more readable"`
它通常做的是将函数`f()`应用于列表中的数据元素,并将该结果用于列表中的下一个值。 在视觉上,
数据= \[a 1 a 2 ...a n \] function = fxy
减少F数据 第1步val 1 = fa 1 a 2 第2步val 2 = fval 1 a 3 第3步val 3 = fval 2 a 4 。 。 。 步骤n-1val n-1 = fval n-2 a n
例如,您希望将列表中的所有数字相乘。
#### 示例用法
```py
from functools import reduce
input = [1,2,3,4,5,6]
multiplier = lambda x,y:x*y
answer = reduce(multiplier,input)
print(answer)
```
#### 产量
```
720
```
但是可以使用简单的for循环来计算上述内容并且优选使用这些方法。
#### 更多信息:

View File

@ -0,0 +1,31 @@
---
title: List Pop Method
localeTitle: 列出弹出方法
---
# 流行功能
pop方法从列表中删除并返回最后一个元素。有一个可选参数即要从列表中删除的元素的索引。 如果未指定索引则a.pop将删除并返回列表中的最后一项。 如果传递给pop方法的索引不在范围内则抛出IndexErrorpop index超出范围异常。
#### 示例用法
\`\`\`PY 城市= \[''纽约''达拉斯''圣安东尼奥''休斯顿''旧金山'\];
print“City popped iscities.pop 打印“索引2处的城市是cities.pop2 \`\`\`
####输出 `City popped is : San Francisco City at index 2 is : San Antonio`
#### 基本堆栈功能
`pop()`方法通常与`append()`一起使用以在Python应用程序中实现基本的堆栈功能。
```py
stack = []
for i in range(5):
stack.append(i)
while len(stack):
print(stack.pop())
```
更多信息: `pop()`的官方文档可以在[这里](https://docs.python.org/3.6/tutorial/datastructures.html)找到

View File

@ -0,0 +1,40 @@
---
title: List Remove Method
localeTitle: 列表删除方法
---
## 列表删除方法
`remove()`方法从列表中删除给定的参数。
#### 示例用法
```py
words = ["I", "love", "Python"]
words.remove("I")
print(words)
```
#### 产量
```py
["love","Python"]
```
请注意,如果在列表中找不到要删除的元素,则会返回错误,如下例所示。
```py
kiss = ["keep", "it", "simple", "stupid"]
kiss.remove("complex")
print(kiss)
```
#### 产量
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
```
#### 更多信息:
有关`remove()`更多信息,请[访问此处](https://docs.python.org/3.6/tutorial/datastructures.html)

View File

@ -0,0 +1,109 @@
---
title: List Sort Method
localeTitle: 列表排序方法
---
## 列表排序方法
Python列表有一个内置的`sort()`方法,它可以就地修改列表,以及一个`sorted()`内置函数,它可以从一个可迭代构建一个新的排序列表。
list.sortkey = ...reverse = \[True / False\]
### 参数
此方法有两个可选参数 _key_ - key参数的输入值应该是一个函数它接受一个参数并返回一个用于比较的值来对列表中的项进行排序 _反向= \[值\]_ _value = True_ :按降序对列表中的项目进行排序 _value = False_ :按升序对列表中的项目进行排序。这被视为默认值。 请注意, `sort()`方法不返回任何值。它修改原始列表。
### 示例用法
```py
a = [4, 2, 5, 3, 1]
a.sort()
print a # prints [1, 2, 3, 4, 5]
b = ['free', 'code', 'camp']
b.sort()
print b # prints ['camp', 'code', 'free']
```
考虑一个带**反向**参数的例子
```py
a = [4, 2, 5, 3, 1]
#Sorts the list in descending order
a.sort(reverse=True)
print a # prints [5, 4, 3, 2, 1]
```
如果要根据自己的函数对列表进行排序,请使用**key**参数。 下面是按长度按升序对列表中的字符串进行排序的示例
```py
a = ["hello", "hi", "hey"]
#The built-in len() function is given as an input to key parameter to sort the strings by length
a.sort(key = len)
print a # prints ['hi', 'hey', 'hello']
```
这是另一个示例,其中列表包含元组(名称,年龄)。 以下用法显示了如何按年龄按升序对列表进行排序。
```py
#Consider the second element in the tuple for sorting
>>> def compareByAge(element):
... return element[1]
b = [('Adam', 20), ('Rahman', 30), ('Rahul', 25)]
#Sort the list by age
b.sort(key = compareByAge)
#Output
print b # prints [('Adam', 20), ('Rahul', 25), ('Rahman', 30)]
```
### 排序基础知识
简单的升序排序非常简单 - 只需调用sorted函数即可。它返回一个新的排序列表
```python
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
```
您还可以使用列表的list.sort方法。它就地修改列表并返回None以避免混淆。通常它不如sorted方便 - 但如果你不需要原始列表,它会更有效率。
```python
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
```
另一个区别是list.sort方法仅为列表定义。相反sorted函数接受任何iterable。
```python
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
```
#### 实施细节
如果想知道有关sort函数算法和时间复杂度等的实现的详细信息请参阅[此处](http://svn.python.org/projects/python/trunk/Objects/listsort.txt) 。简而言之sort函数使用TimSort算法根据Python Developers它是 -
> 一种适应性,稳定,自然的融合,适度称呼 蒂姆索特(嘿,我赚了它 )。它在很多方面都有超自然的表现 各种部分有序的数组需要少于lgN的比较和 与N-1一样少但速度与Python之前高度调整的样本一样快 混合随机阵列。
#### sort参数
默认情况下sort不需要任何额外的参数。但是它有两个可选参数
* reverse - 如果为true则排序列表或按降序排序
* key - 用作排序比较的键的函数
#### 更多信息:
有关`sort()`更多信息,请[访问此处](https://docs.python.org/3/library/functions.html#sorted)
有关sort和sorted的更多信息请参见[此处](https://docs.python.org/3.6/tutorial/datastructures.html)
有关sort和sorted的更多信息请参见[此处](https://docs.python.org/3.6/tutorial/datastructures.html) 。

View File

@ -0,0 +1,51 @@
---
title: Python Max Function
localeTitle: Python Max函数
---
`max()`是Python 3中的内置函数。它返回可迭代中的最大项或两个或多个参数中的最大项。
## 参数
此函数将两个或多个数字或任何类型的iterable作为参数。在给出一个iterable作为参数时我们必须确保iterable中的所有元素都是相同的类型。这意味着我们无法传递一个包含字符串和整数值的列表。 句法: maxiterable\* iterables \[keydefault\] maxarg1arg2\* args \[key\]
有效参数:
```
max(2, 3)
max([1, 2, 3])
max('a', 'b', 'c')
```
参数无效:
```
max(2, 'a')
max([1, 2, 3, 'a'])
max([])
```
## 回报价值
返回iterable中的最大项。如果提供了两个或多个位置参数则返回最大的位置参数。如果iterable为空并且未提供default则引发`ValueError`
## 代码示例
```
print(max(2, 3)) # Returns 3 as 3 is the largest of the two values
print(max(2, 3, 23)) # Returns 23 as 23 is the largest of all the values
list1 = [1, 2, 4, 5, 54]
print(max(list1)) # Returns 54 as 54 is the largest value in the list
list2 = ['a', 'b', 'c' ]
print(max(list2)) # Returns 'c' as 'c' is the largest in the list because c has ascii value larger then 'a' ,'b'.
list3 = [1, 2, 'abc', 'xyz']
print(max(list3)) # Gives TypeError as values in the list are of different type
#Fix the TypeError mentioned above first before moving on to next step
list4 = []
print(max(list4)) # Gives ValueError as the argument is empty
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CVok)
[官方文件](https://docs.python.org/3/library/functions.html#max)

View File

@ -0,0 +1,52 @@
---
title: Python Min Function
localeTitle: Python Min函数
---
`min()`是Python 3中的内置函数。它返回可迭代中的最小项或两个或多个参数中的最小项。
## 参数
此函数将两个或多个数字或任何类型的iterable作为参数。在给出一个iterable作为参数时我们必须确保iterable中的所有元素都是相同的类型。这意味着我们无法传递一个包含字符串和整数值的列表。
有效参数:
```
min(2, 3)
min([1, 2, 3])
min('a', 'b', 'c')
```
参数无效:
```
min(2, 'a')
min([1, 2, 3, 'a'])
min([])
```
## 回报价值
返回iterable中的最小项。如果提供了两个或多个位置参数则最小的位置参数
被退回。如果iterable为空并且未提供default则引发ValueError。
## 代码示例
```
print(min(2, 3)) # Returns 2 as 2 is the smallest of the two values
print(min(2, 3, -1)) # Returns -1 as -1 is the smallest of the two values
list1 = [1, 2, 4, 5, -54]
print(min(list1)) # Returns -54 as -54 is the smallest value in the list
list2 = ['a', 'b', 'c' ]
print(min(list2)) # Returns 'a' as 'a' is the smallest in the list in alphabetical order
list3 = [1, 2, 'abc', 'xyz']
print(min(list3)) # Gives TypeError as values in the list are of different type
#Fix the TypeError mentioned above first before moving on to next step
list4 = []
print(min(list4)) # Gives ValueError as the argument is empty
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CVir/4)
[官方文件](https://docs.python.org/3/library/functions.html#min)

View File

@ -0,0 +1,9 @@
---
title: Python More Built in Types
localeTitle: Python更多内置类型
---
以下部分描述了解释器中内置的标准类型。
主要的内置类型是数字,序列,映射,类,实例和异常。
一些集合类是可变的。在适当的位置添加减去或重新排列其成员但不返回特定项的方法永远不会返回集合实例本身而是返回None。

View File

@ -0,0 +1,68 @@
---
title: Python Mutability and Variable Assignments
localeTitle: Python可变性和变量赋值
---
> 每个对象都有一个标识,一个类型和一个值。对象的标识一旦创建就永远不会改变;你可以把它想象成对象在内存中的地址。 [资源](https://docs.python.org/3/reference/datamodel.html#data-model)
创建`object` ,无法更改类型和标识。对象的值是否可以在创建后更改,确定对象是可变的(可以更改)还是不可变的(不能更改)。
到目前为止,我们已经了解了几种类型的对象及其子类: `string` s和数字整数浮点复数和布尔对象。所有这些都是**不可变**对象。
这个概念最初可能会让人感到困惑,因为如果你不能修改它,对象有什么好处。使这些对象可用的是分配和重新分配变量的能力。函数和运算符可以返回可以分配给变量的新对象。
使用返回对象标识的内置[id函数](https://docs.python.org/3/library/functions.html#id) ,我们可以看到它是如何工作的。
以下是一些要记住的事项:
* 分配变量并不意味着_变量_是_对象_ 。我们使用了非常具体的语言指出_赋值语句_ **将** **名称** (标识符) **绑定**到_对象_ 。可以重新分配变量:
\`蟒蛇
> > > a = 1将a绑定到对象。
> > > ID
> > > 140355241530152
> > > a = 2将a重新绑定到另一个对象。
> > > ID
> > > 140355241530128
> > > \`
* 将两个不同的变量分配给具有相同值的_不可变对象_可能会导致不保证它们绑定到同一个_对象_
\`蟒蛇
> > > a = 1
> > > b = 1
> > > ID
> > > 140355241530152
> > > idb在这种情况下a和b绑定到同一个对象。
> > > 140355241530152
> > > \`
* 将两个不同的变量分配给具有不同值的可变_对象_将始终导致它们绑定到不同的_对象_
\`蟒蛇
> > > a = 1
> > > b = 2
> > > ID
> > > 140355241530152
> > > idb#a和b绑定到不同的对象。
> > > 140355241530128
> > > \`
* 重新分配变量不会更改原始对象,而是将它们绑定到不同的对象。
\`蟒蛇
> > > a = 1
> > > b = 1
> > > ID
> > > 140355241530152
> > > IDb
> > > 140355241530152
> > > a = 2
> > > ida#a被反弹到另一个对象。
> > > 140355241530128
> > > idb#b仍然绑定到原始对象。
> > > 140355241530152
> > > \`

View File

@ -0,0 +1,28 @@
---
title: Python Name Binding and Aliasing Functions
localeTitle: Python名称绑定和别名函数
---
函数定义在当前符号表中引入函数名称。函数名称的值具有解释器将其识别为用户定义函数的类型。
```
>>> something = 1
>>> type(something)
<type 'int'>
>>> def something():
... pass
...
>>> type(something)
<type 'function'>
>>> something = []
>>> type(something)
<type 'list'>
```
此值可以分配给另一个名称,该名称也可以用作函数。这是一般的重命名机制:
```
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
```

View File

@ -0,0 +1,105 @@
---
title: Nested Functions in Python
localeTitle: Python中的嵌套函数
---
### 命名空间
函数的参数以及函数体中绑定的任何变量通过赋值或其他绑定语句如def构成函数的本地名称空间也称为本地作用域。这些变量中的每一个都被称为函数的局部变量。
非本地变量称为全局变量在没有嵌套函数定义的情况下我们将在稍后讨论。全局变量是模块对象的属性如第140页的“模块对象的属性”中所述。每当函数的局部变量与全局变量具有相同的名称时该函数体内的名称引用局部变量不是全球性的。我们通过说局部变量在整个函数体中隐藏同名的全局变量来表达这一点。
### 全球声明
默认情况下,函数体中绑定的任何变量都是函数的局部变量。如果一个函数需要重新绑定一些全局变量,那么第一个 功能声明必须是:
全局标识符
其中identifier是由逗号分隔的一个或多个标识符。全局语句中列出的标识符指的是函数需要重新绑定的全局变量即模块对象的属性。例如我们在第73页的“函数对象的其他属性”中看到的函数计数器可以使用全局变量和全局变量来实现而不是函数对象的属性
\_count = 0 def counter 全局\_count \_count + = 1 return \_count
如果没有全局语句计数器函数将引发UnboundLocal-Error异常因为\_count将是未初始化未绑定的局部变量。虽然全局声明支持这种编程但这种风格通常不够优雅且不可取。正如我之前提到的当你想将一些状态和某些行为组合在一起时第5章中介绍的面向对象机制通常是最好的。
如果函数体只使用全局变量,则不要使用全局变量(如果对象是可变的,则包括变量绑定到该变量的对象)。仅当函数体重新绑定全局变量时(通常通过分配变量的名称),才使用全局语句。作为一种风格问题,不要使用全局,除非它是绝对必要的,因为它的存在将使你的程序的读者认为该声明是出于某些有用的目的。特别是,除了作为函数体中的第一个语句之外,永远不要使用全局。
{mospagebreak title =嵌套函数和嵌套作用域}
函数体内的def语句定义嵌套函数其体包含def的函数称为嵌套函数的外部函数。嵌套函数体中的代码可以访问但不重新绑定外部函数的局部变量也称为嵌套函数的自由变量。
让嵌套函数访问值的最简单方法通常不依赖于嵌套作用域,而是显式地将该值作为函数参数之一传递。如果需要,可以在使用值作为可选参数的缺省值定义嵌套函数时绑定参数的值。例如:
def percent1abc def pcxtotal = a + b + creturnx \* 100.0/ total print“百分比是pcapcbpcc
以下是使用嵌套作用域的相同功能:
def percent2abc def pcxreturnx \* 100.0/a + b + c print“百分比是pcapcbpcc
在这种特定情况下percent1有一个很小的优势a + b + c的计算只发生一次而percent2的内部函数pc重复计算三次。但是如果外部函数在对嵌套函数的调用之间重新绑定其局部变量则可能需要重复计算。因此建议您了解这两种方法并根据具体情况选择最合适的方法。
从外部局部变量访问值的嵌套函数也称为闭包。以下示例显示了如何构建闭包:
def make\_adderaugend def addaddend 返回addend + augend 返回添加
闭包是一般规则的一个例外第5章中介绍的面向对象机制是将数据和代码捆绑在一起的最佳方法。当你需要专门构造可调用对象时在对象构造时固定一些参数闭包可以比类更简单更有效。例如make\_adder7的结果是一个接受单个参数并向该参数添加7的函数。返回闭包的外部函数是由一些参数区分的函数族成员的“工厂”例如前一个示例中参数augend的值并且通常可以帮助您避免代码重复。
### lambda表达式
如果函数体是单个返回表达式语句则可以选择使用特殊的lambda表达式替换该函数
lambda参数表达式
lambda表达式是正常函数的匿名等价物其正文是单个return语句。请注意lambda语法不使用return关键字。您可以在任何可以使用函数引用的地方使用lambda表达式。当你想使用一个简单的函数作为参数或返回值时lambda有时会很方便。这是一个使用lambda表达式作为内置过滤器函数的参数的示例在过滤器中介绍第161页
aList = \[1,2,3,4,5,6,7,8,9\] 低= 3 高= 7 过滤器lambda xl =低, h =高h> x> laList返回\[4,5,6\]
作为替代方法您始终可以使用本地def语句为函数对象提供名称。然后您可以使用此名称作为参数或返回值。这是使用本地def语句的相同过滤器示例
aList = \[1,2,3,4,5,6,7,8,9\] 低= 3 高= 7 def在_界限内l =低h =高): 返回h> value> l filter在_ boundsaList中#return\[4,5,6\]
虽然lambda偶尔会有用但许多Python用户更喜欢def这更通用如果为函数选择合理的名称可能会使代码更具可读性。
{mospagebreak title = Generators}
当函数体包含一个或多个关键字yield时该函数称为生成器。当您调用生成器时函数体不会执行。相反调用生成器返回一个特殊的迭代器对象它包装函数体其局部变量包括其参数和当前执行点最初是函数的开始。
当调用此迭代器对象的下一个方法时函数体将执行下一个yield语句该语句采用以下形式
屈服表达
当yield语句执行时函数执行被“冻结”当前执行点和局部变量保持不变并且作为下一个方法的结果返回yield之后的表达式。当再次调用next时函数体的执行将从中断处继续执行再次执行下一个yield语句。如果函数体结束或执行return语句迭代器会引发StopIteration异常以指示迭代已完成。生成器中的return语句不能包含表达式。
生成器是构建迭代器的一种非常方便的方法。因为使用迭代器的最常见方法是使用for语句循环它所以通常调用这样的生成器
对于somegenerator参数中的可变
例如假设您想要一系列数字从1到N再次计数然后再次减少到1。发电机可以帮助
def updownN for x in xrange1Nyield x for x in xrangeN0-1yield x 对于我在updown3 print iprints1 2 3 2 1
这是一个有点像内置xrange函数的生成器但返回一系列浮点值而不是整数序列
def frangestartstopstep = 1.0 而开始<停止 产量开始 开始+ =步骤
这个frange示例有点像xrange因为为简单起见它使参数开始和停止是强制性的并且默认地假设步骤是正的
生成器比返回列表的函数更灵活生成器可以构建无界迭代器意味着返回无限结果流仅在通过其他方式终止的循环中使用例如通过break语句)。此外生成器构建的迭代器执行延迟评估迭代器仅在需要时及时地计算每个连续项而等效函数提前完成所有计算并且可能需要大量内存来保存结果列表因此如果您只需要迭代计算序列则通常最好在生成器中而不是在返回列表的函数中计算序列如果调用者需要一些有界生成器G参数生成的所有项的列表则调用者可以简单地使用以下代码
resul\_list = listGarguments
### 生成器表达式
Python 2.4引入了一种更简单的方法来编写特别简单的生成器生成器表达式通常称为genexps genexp的语法就像列表推导的语法如第67页的列表推导中所述除了genexp括在括号而不是括号\[\]; genexp的语义与相应列表理解的语义相同只是genexp产生迭代器一次产生一个项目而列表理解产生内存中所有结果的列表因此使用genexp当适当节省记忆)。例如要对所有单位数整数的平方求和在任何现代Python中您都可以进行编码 sum\[x _x for x in xrange10\];在Python 2.4中您可以更好地表达此功能将其编码为sumx_ x表示xrange10中的x只是相同但省略括号并获得完全相同的结果同时消耗更少的内存请注意表示函数调用的括号也执行双重任务并包含genexp不需要额外的括号)。
{mospagebreak title = Python 2.5中的生成器}
在Python 2.5中生成器得到进一步增强可以在每个yield执行时从调用者接收值或异常)。这些高级功能允许2.5中的生成器实现完整的协同例程如http://www.python.org/peps/pep-0342.html中所述主要的变化是在2.5中yield不是一个语句而是一个表达式因此它有一个值通过下一步调用其方法恢复生成器时相应的yield的值为None要将值x传递给某个生成器g以便g接收x作为其挂起的yield的值而不是调用g.next调用者调用g.sendx调用g.send 就像调用g.next())。此外在Python 2.5中没有参数的裸产率变得合法并且相当于产生None
生成器的其他Python 2.5增强功能与异常有关并在第126页的生成器增强功能中介绍
### 递归
Python支持递归即Python函数可以调用自身但递归的深度有限默认情况下Python会在检测到递归调用堆栈的深度超过1,000时中断递归并引发RecursionLimitExceeded异常标准异常类”(第130页中介绍)。您可以使用模块sys的函数setrecursionlimit更改递归限制请参阅第171页的setrecursionlimit
但是更改递归限制并不能为您提供无限递归;绝对最大限制取决于运行程序的平台特别是底层操作系统和C运行时库但通常只有几千个级别如果递归调用太深程序崩溃在调用超出平台功能的setrecursionlimit之后这种失控的递归是Python程序崩溃的极少数方式之一 - 真正崩溃很难没有通常的Python异常机制的安全网因此要小心尝试使用setrecursionlimit通过将递归限制提高得太高来修复正在获取RecursionLimitExceeded异常的程序通常建议您更好地寻找删除递归的方法或者更具体地说限制程序所需的递归深度
熟悉LispScheme或函数式编程语言的读者必须特别注意Python不实现尾部调用消除的优化这在这些语言中非常重要在Python中任何调用递归与否在时间和内存空间方面都有相同的成本仅取决于参数的数量成本不会改变调用是否是尾调用”(意思是该调用是调用者执行的最后一个操作或任何其他非尾调用

View File

@ -0,0 +1,45 @@
---
title: Python Numeric Operations
localeTitle: Python数值运算
---
[Python文档 - 数字操作](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex)
Python完全支持混合算术当二进制算术运算符具有不同数值类型的操作数时具有“较窄”类型的操作数被扩展为另一个的操作数其中整数比浮点更窄这比复数更窄。混合类型数字之间的比较使用相同的规则。 [2\]构造函数intfloat和complex可用于生成特定类型的数字。](https://docs.python.org/3/library/functions.html#abs)
所有数字类型(复杂除外)都支持以下操作,按升序优先级排序(所有数字操作的优先级都高于比较操作):
操作|结果|备注|完整的文档
\----------------- | -------------------------------------------------- ------------------------- | ------ | -------------------------------------------------- ---------------------
`x + y` | x和y的总和| |
`x - y` | x和y的差异| |
`x * y` | x和y的乘积| |
`x / y` | x和y |的商|
`x // y` | x和y |的平均商1|
`x % y` |剩余的x / y | 2
`-x` | x否定| |
`+x` | x不变| |
`abs(x)` | x |的绝对值或大小| \[ `abs()`
`int(x)` | x转换为整数| 36| [`int()`](https://docs.python.org/3/library/functions.html#int)
`float(x)` | x转换为浮点| 46| [`float()`](https://docs.python.org/3/library/functions.html#float)
`complex(re, im)` |一个带有实部re的复数虚部im。我默认为零。 | 6| [`complex()`](https://docs.python.org/3/library/functions.html#complex)
`c.conjugate()` |复数c的共轭|
`divmod(x, y)` |对x // yxy| 2| [`divmod()`](https://docs.python.org/3/library/functions.html#divmod)
`pow(x, y)` | x到幂y | 5| [`pow()`](https://docs.python.org/3/library/functions.html#pow)
`x ** y` | x到幂y | 5
**笔记:**
1. 也称为整数除法。结果值是整数但结果的类型不一定是int。结果始终舍入为负无穷大 `1//2``0` `(-1)//2``-1` `1//(-2)``-1` `(-1)//(-2)``0`
2. 不是复杂的数字。而是在适当的情况下使用`abs()`转换为浮点数。
3. 从浮点到整数的转换可以像C中那样舍入或截断;请参阅函数[`math.floor()`](https://docs.python.org/3/library/math.html#math.floor)和[`math.ceil()`](https://docs.python.org/3/library/math.html#math.ceil)以获得明确定义的转换。
4. `float`也接受字符串`“nan”``“inf”` ,带有可选前缀`“+”``“-”`表示非数字NaN和正或负无穷大。
5. Python将`pow(0, 0)``0 ** 0``1` ,这在编程语言中很常见。
6. 接受的数字文字包括数字0到9或任何Unicode等效项具有`Nd`属性的代码点)。
> 有关具有`Nd`属性的代码点的完整列表,请参阅[Unicode派生数字类型](http://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedNumericType.txt) 。

View File

@ -0,0 +1,36 @@
---
title: Python Numeric Types
localeTitle: Python数字类型
---
Python的[数字类型](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex)是:
* 整数( `int`
#### 例子:
```py
print(1)
print(100)
print(8435367)
```
* 浮点数( `float`
* [构造函数](https://docs.python.org/3/library/functions.html#float)
#### 例子:
```py
print(1.5)
print(46.84)
print(84357.435)
```
* 复数
* [构造函数](https://docs.python.org/3/library/functions.html#complex)
标准库为数据类型添加
* [馏分](https://docs.python.org/3/library/fractions.html#module-fractions)
* [小数点](https://docs.python.org/3/library/decimal.html#module-decimal)
数字对象是从文字或函数和运算符的结果创建的。数字文字的语法已有详细[记载](https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals) 。

View File

@ -0,0 +1,17 @@
---
title: Classes
localeTitle: 类
---
## 类
类是创建对象的“蓝图”:编写类允许描述属性和行为公共到该类的每个实例。
## 创建一个类
要定义类,请使用关键字**类** ,后跟定义类的名称和冒号。以下所有行(描述属性和行为/方法的代码) - 在Python函数中缩进。例如要创建一个名为Person的类我们可以编写
`class Person: <code describing attributes and behaviors/methods>`
类定义必须在它们产生任何影响之前执行。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Constructors
localeTitle: 构造函数
---
## 构造函数
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,16 @@
---
title: Python Object Oriented Programming
localeTitle: 面向对象的Python编程
---
## 面向对象的Python编程
Python是一种支持不同编程方法的多范式编程语言。一种优秀的编程范例是面向对象编程或简称OOP通过创建对象。
在OOP中属性和行为被捆绑到单个对象中其特征如下
* 属性
* 行为
例如,一个对象可以代表具有属性的人,如姓名,年龄,地址,行走,说话,呼吸和跑步等行为。
OOP将现实世界的实体建模为软件对象它们具有与之相关的一些数据并且可以执行某些功能。对象被建模为**类** 这是一种_蓝图_ 。

View File

@ -0,0 +1,11 @@
---
title: Inheritance
localeTitle: 遗产
---
## 遗产
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Methods
localeTitle: 方法
---
## 方法
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Operator Overloading
localeTitle: 运算符重载
---
## 运算符重载
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Special Comparison Methods
localeTitle: 特殊比较方法
---
## 特殊比较方法
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Special Formatting Methods
localeTitle: 特殊格式化方法
---
## 特殊格式化方法
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Special Iteration Methods
localeTitle: 特殊迭代方法
---
## 特殊迭代方法
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: Static Variables
localeTitle: 静态变量
---
## 静态变量
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,35 @@
---
title: Python Ord Function
localeTitle: Python Ord函数
---
## Ord功能
`ord()`是Python 3中的内置函数用于将表示一个Unicode字符的字符串转换为整数 表示字符的Unicode代码。
#### 例子:
```
>>> ord('d')
100
>>> ord('1')
49
```
## chr功能
`chr()`是Python 3中的内置函数用于转换整数 将Unicode代码表示为表示相应字符的字符串。
#### 例子:
```
>>> chr(49)
'1'
```
有一点需要注意,如果传递给`chr()`的整数值超出范围则会引发ValueError。
```
>>> chr(-10)
'Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
chr(-1)
ValueError: chr() arg not in range(0x110000)'
```

View File

@ -0,0 +1,17 @@
---
title: Python Parenthesis for Boolean Operations
localeTitle: 布尔运算的Python括号
---
就像在数学中一样,括号可用于覆盖操作的顺序:
```
>>> not True or True
True
>>> not (True or True)
False
>>> True or False and False
True
>>> (True or False) and False
False
```

View File

@ -0,0 +1,25 @@
---
title: Python Powxy
localeTitle: Python Powxy
---
`pow(x, y, z)`是Python 3中的内置函数用于计算`x`到幂`y` ,如果`z`存在,则将`x`返回到幂`y` [modulo](https://processing.org/reference/modulo.html) `z`
## 参数
参数必须具有数字类型。 该函数有两个参数, `x``y` ,以及三个, `x` `y``z` 。 如果存在`z` ,则`x``y`必须是整数类型y必须是非负的。
## 返回
如果`z`存在,它返回`x`的电源`y``z` 。如果仅存在`x``y` ,则将`x`返回到幂`y` (与`x**y`相同)。
## 例
```python
print(pow(2,4)) # prints 16
print(pow(10,-2)) # prints 0.01
print(pow(4,3,5)) # prints 4
```
[🚀运行代码](https://repl.it/CTGi)
[官方文件](https://docs.python.org/3/library/functions.html#pow)

View File

@ -0,0 +1,65 @@
---
title: Python 2 vs Python 3
localeTitle: Python 2与Python 3
---
我们不参与辩论。如果您有兴趣了解更多关于它的学术目的,也许[这篇文章比较Python 2和Python 3](https://wiki.python.org/moin/Python2orPython3)会引起您的兴趣。
但是我们也不能不知道有两种主要的Python风格。你问为什么要关心你呢因为为一个版本的Python编写的代码可能会导致另一个版本的Python出现语法错误。
以下是Python 2中的有效`print`语句但不适用于Python 3
```py
print "Hello World"
```
在Python 3中同一语句会抛出这样的错误
```
>>> print "hello"
File "<stdin>", line 1
print "hello"
^
SyntaxError: Missing parentheses in call to 'print'
```
在Python 2中“print”被视为语句而不是函数。尽管您可以但您无需将要打印的文本包装在括号中。 Python 3明确将“print”视为一个函数这意味着您必须以标准方式将需要打印的项目传递给括号中的函数否则您将收到语法错误
在Python 2和3中使用`print()`函数是“安全的”:
```python
print("Hello World")
```
Python 2和Python 3之间的另一个区别是它们在调用`map()`函数时返回的数据结构。
在Python 2中 `map()`返回一个列表:
```
>>> result = map(int,['10','20','30','40'])
>>> print result
>>> [10,20,30,40]
```
在Python 3中 `map()`返回一个迭代器:
```
>>> result = map(int,['10','20','30','40'])
>>> print (result)
>>> <map object at 0x7f40896b4630>
```
要在Python 3中获取列表您需要转换它
```
>>> result = list(map(int,['10','20','30','40']))
>>> print (result)
>>> [10,20,30,40]
```
所以,你现在唯一需要关注的问题是什么;你要选哪一个如果你是Python的新手你应该选择Python 3.Python 2目前[的生命终止](https://www.python.org/dev/peps/pep-0373/#update)日期设置为2020.意味着常规错误修正不能保证前进,是的,甚至需要时间来熟悉大多数常见方面蟒蛇;而你的时间很重要。所以,明智地投入时间和精力!
虽然Python 2受到良好支持和欢迎但Python中最常见的库和框架更喜欢Python 3. Django正式[推荐](https://docs.djangoproject.com/en/1.9/faq/install/#faq-python-version-support) Python 3. Flask及其所有依赖项也[支持](http://flask.pocoo.org/docs/0.10/python3/#python3-support) Python 3。
Python 2和Python 3都很棒。大多数Linux和macOS发行版预装了Python 2作为Python的默认版本。 Python 3源于对更可读和更美丽的语言结构的永不满足的追求。
本文使用Python 3在您的开发环境中设置Web框架。但在此之前您需要确保拥有Python 3并知道如何使用它
#### 更多信息:
* [Python 2或3文章](https://wiki.python.org/moin/Python2orPython3)

View File

@ -0,0 +1,30 @@
---
title: Coding standards
localeTitle: 编码标准
---
### 大纲
* 为什么编码标准?
* PEP 8简介
* 命令
### 为什么编码标准?
全球python社区正在快速增长几乎每个人都使用python。这是代码和统一标准的可读性很重要的地方。地球上的任何人都应该能够阅读您的代码并了解它的作用。理解其他代码有很多方面例如关于函数功能的评论逻辑上在模块和函数之间划分任务良好的变量名称等。
### PEP 8简介
我们喜欢坚持惯例。 python用户社区已经提出了一套标准现在这些标准被视为惯例。您编写的任何行业级代码都通过PEP 8检查程序运行。因此开始为您的类和函数编写文档字符串并使用approrpiate下划线以小写字母命名变量是一种很好的做法。在开始编码之前看看这些标准可能是值得的。
[这是详尽的链接](https://www.python.org/dev/peps/pep-0008/ "PEP 8标准")
### 命令
这是你如何检查你的python代码是否符合他的标准。
```console
:~$ pip install pep8
:~$ pep8 --first myCode.py
```
这将提供违反标准的所有行,以及修复的简短描述。

View File

@ -0,0 +1,53 @@
---
title: Python f-strings
localeTitle: Python f字符串
---
# Python中的f字符串
在Python 3.6版中实现了一种格式化字符串的新方法。新方法称为文字字符串插值通常称为f字符串
f-string的使用允许程序员以干净简洁的方式动态地将变量插入到字符串中。除了将变量插入字符串之外此功能还为程序员提供了计算表达式连接集合内容甚至调用f字符串中的函数的能力。
要在f字符串中执行这些动态行为我们将它们包装在字符串中的大括号内并将小写字母f前置到字符串的开头在开头引号之前
### 例子
1. 在运行时动态地将变量插入到字符串中:
```python
name = 'Jon Snow'
greeting = f'Hello! {name}'
print(greeting)
```
2. 评估字符串中的表达式: `python val1 = 2 val2 = 3 expr = f'The sum of {val1} + {val2} is {val1 + val2}' print(expr)`
3. 调用函数并在字符串中插入输出:
```python
def sum(*args):
result = 0
for arg in args:
result += arg
return result
func = f'The sum of 3 + 5 is {sum(3, 5)}'
print(func)
```
4. 在字符串中连接集合的内容:
```python
fruits = ['Apple', 'Banana', 'Pear']
list_str = f'List of fruits: {", ".join(fruits)}'
print(list_str)
```
### 来源
https://www.python.org/dev/peps/pep-0498/

View File

@ -0,0 +1,69 @@
---
title: Python Resources
localeTitle: Python资源
---
## 教程
* [Python官方教程](https://docs.python.org/3/tutorial/)
* [Hitchhiker的Python指南](https://python-guide.readthedocs.org/en/latest/)
* [谷歌Python类](https://developers.google.com/edu/python/)
* [以艰难的方式学习Python](http://learnpythonthehardway.org/book/)
* [想想Python](http://www.greenteapress.com/thinkpython/html/index.html)
* [在X分钟内学习Python](https://learnxinyminutes.com/docs/python/)
* [在X分钟内学习Python 3](https://learnxinyminutes.com/docs/python3/)
* [深入Python 3](http://www.diveintopython3.net/)
* [全栈Python](http://www.fullstackpython.com/)
* [使用Python自动化无聊的东西](https://automatetheboringstuff.com/)
* [浏览器中的Python REPL](https://repl.it/languages/python3)
* [Visual Python代码演练](http://pythontutor.com/)
* [Codecademy Python](https://www.codecademy.com/learn/python)
* [如何像计算机科学家一样思考](http://interactivepython.org/runestone/static/thinkcspy/index.html) - 用Python教授编程的交互式教科书
* [计算机科学与Python编程简介](https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-8) MIT
* [CS for All计算机科学与Python编程入门](https://www.edx.org/course/cs-all-introduction-computer-science-harveymuddx-cs005x-0)
* [学习Python](https://www.packtpub.com/packt/free-ebook/learning-python) - 免费电子书
* [新编码器](http://newcoder.io/) - 从新手到实际编码器的教程/挑战。
* [使用Python进行发明](https://inventwithpython.com/) 另外两本书由Automate the Boring Stuff提供
* [使用Python解决算法和数据结构问题](http://interactivepython.org/runestone/static/pythonds/index.html)
* [Python设计模式](https://github.com/faif/python-patterns)
* [Django入门教程](https://www.djangoproject.com/start/)
* [使用Python进行测试驱动开发](http://chimera.labs.oreilly.com/books/1234000000754/index.html)
* [探戈与Django](http://www.tangowithdjango.com/)
* [Django Girls'Tutorial](http://tutorial.djangogirls.org/en/) - 建立一个博客
* [TaskBuster Django教程](http://www.marinamele.com/taskbuster-django-tutorial) - 从头开始构建Django项目
* [Derek Banas在一个视频中学习Python](https://www.youtube.com/watch?v=N4mEzFDjqtA)
* [pythonprogramming.net Python Baics](https://pythonprogramming.net/introduction-to-python-programming/)
* [thenewboston Python 3.4编程教程](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_)
* [教程点 - Python](http://www.tutorialspoint.com/python/)
* [一套带有视频的入门项目](https://pythonprogramming.net) - 从基础开始。
* [Flask Mega教程Miguel Grinberg](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world)
## 挑战
* [Python Koans](https://github.com/gregmalcolm/python_koans)
* [练习Python挑战](http://exercism.io/languages/python)
* [CodingBat Python挑战](http://codingbat.com/python)
* [交互式学习Python](http://www.learnpython.org/)
* [项目欧拉](http://projecteuler.net/)
* [Rosalind Python生物信息学问题](http://rosalind.info/problems/locations/)
* [Python电梯挑战赛](https://github.com/mshang/python-elevator-challenge)
* [CoderByte挑战](https://coderbyte.com/)
* [CheckiO](https://checkio.org) - 编码员的游戏
* [CodeAbbey](http://www.codeabbey.com/)
* [HackerRank - Python面临的挑战](https://hackerrank.com/domains/python/py-introduction)
* [CodeSignal - 准备面试并进一步提高您的编程技巧](https://codesignal.com/)
* [CodeWars](https://www.codewars.com/)
* [CodeChef](https://www.codechef.com/)
## 社区
* [真棒Python](https://github.com/vinta/awesome-python)
* [/ R / Python的](https://www.reddit.com/r/python)
* [/ R / LearnPython](https://www.reddit.com/r/learnpython)
* [行星Python](http://planetpython.org/)
* [PyLadies](http://www.pyladies.com/)
* [DjangoGirls](https://djangogirls.org/)
* [Python-forum.io](https://python-forum.io/)
## 工具:
* [PyCharm Edu](https://www.jetbrains.com/pycharm-edu/) - [PyCharm](https://www.jetbrains.com/pycharm-edu/)的免费教育版本附带教程教你Python和下载更多的能力。

View File

@ -0,0 +1,13 @@
---
title: Range Method
localeTitle: 范围方法
---
# 范围功能
如果你需要迭代一系列数字内置函数range就派上用场了。它生成算术进度
#### 示例用法
`py for i in range(5): print(i)`
####输出 `0 1 2 3 4`

View File

@ -0,0 +1,91 @@
---
title: REST APIs with Falcon
localeTitle: 使用Falcon的REST API
---
## 介绍
RESTful API是任何架构良好的堆栈的主要组件而Python恰好有一些很好的框架可用于快速编写API。其中一个框架被称为[Falcon](https://falconframework.org) - 它很棒!基本上是一个微框架,它具有相当多的优点:
1. 它很快。真的很快查看[这里](https://falconframework.org/#sectionBenchmarks)的基准。
2. HTTP资源被定义为类其中类方法用于对这些资源的不同REST操作。这有助于维护干净的代码库。
3. 这是相当可扩展的 - 请查看他们的维基上的[这一部分](https://github.com/falconry/falcon/wiki/Complementary-Packages) ,以了解它。
4. 它基于WSGI - Web应用程序的Pythonic标准 - 因此它适用于Python 2.6,2.7和3.3+。如果您需要更高的性能请使用PyPy运行它
## 入门
首先,让我们为环境做好准备。就个人而言,在虚拟环境中工作总是很棒 - 你可以使用`virtualenv` `virtualenvwrapper``venv` 。接下来,使用`pip` `pip install falcon`安装Falcon。
我们将开发一个小样本API为我们进行非常基本的时区操作。它将以UTC显示当前时间以及相应的纪元时间。为此我们将获得一个名为`arrow`的漂亮库: `pip install arrow`
您可以在[https://github.com/rudimk/freecodecamp-guides-rest-api-falcon](https://github.com/rudimk/freecodecamp-guides-rest-api-falcon)找到完成的样本。
## 资源
将资源视为API需要操作的实体。在我们的例子中最好的资源是`Timestamp` 。我们的路由通常是这样的:
```
GET /timestamp
```
这里, `GET`是用于调用此端点的HTTP动词 `/timestamp`是URL本身。现在我们已经把这一点放开了让我们创建一个模块
`$ touch timestamp.py`
是时候导入Falcon库了
```python
import json
import falcon
import arrow
```
注意我们还导入了`json`包和`arrow`库。现在,让我们为我们的资源定义一个类:
```python
class Timestamp(object):
def on_get(self, req, resp):
payload = {}
payload['utc'] = arrow.utcnow().format('YYYY-MM-DD HH:mm:SS')
payload['unix'] = arrow.utcnow().timestamp
resp.body = json.dumps(payload)
resp.status = falcon.HTTP_200
```
我们来看看这个片段。我们定义了一个`Timestamp`类,并定义了一个名为`on_get`的类方法 - 该函数告诉Falcon当向该资源的端点发出`GET`请求时,运行`on_get`函数并提供请求和响应对象作为参数。之后,它一帆风顺 - 我们创建一个空字典用当前的UTC和UNIX时间戳填充它将其转换为JSON并将其附加到响应对象。
很简单吧但遗憾的是并非全部。我们现在需要创建一个Falcon服务器并将我们刚刚定义的资源类连接到实际端点。
`$ touch app.py`
现在,添加以下代码:
```python
import falcon
from timestamp import Timestamp
api = application = falcon.API()
timestamp = Timestamp()
api.add_route('/timestamp', timestamp)
```
在这里我们定义了一个Falcon API并初始化了我们之前创建的资源类的实例。然后我们将`/timestamp`端点与类实例连接起来 - 现在我们很高兴要测试这个API安装`gunicorn` `pip install gunicorn` ),并运行`gunicorn app` 。使用Postman或简单的`cURL`来测试这个:
```
$ curl http://localhost:8000/timestamp
{"utc": "2017-10-20 06:03:14", "unix": 1508479437}
```
就是这样!
## 继续
一旦掌握了Falcon构建与数据库或消息队列交互的强大RESTful API非常容易。查看[Falcon文档](https://falcon.readthedocs.io/en/stable/index.html) 以及有趣的Falcon模块的PyPI这些模块不断涌现。

View File

@ -0,0 +1,91 @@
---
title: Python Return Statement
localeTitle: Python返回声明
---
[Python文档](https://docs.python.org/3/reference/simple_stmts.html#the-return-statement)
调用时,所有函数都返回一个值。
如果返回语句后跟表达式列表,则计算该表达式列表并返回值:
```
>>> def greater_than_1(n):
... return n > 1
...
>>> print(greater_than_1(1))
False
>>> print(greater_than_1(2))
True
```
如果未指定表达式列表,则返回`None`
```
>>> def no_expression_list():
... return # No return expression list.
...
>>> print(no_expression_list())
None
```
如果在执行函数期间达到return语句则当前函数调用将保留在该点
```
>>> def return_middle():
... a = 1
... return a
... a = 2 # This assignment is never reached.
...
>>> print(return_middle())
1
```
如果没有return语句则函数到达结尾时返回None
```
>>> def no_return():
... pass # No return statement.
...
>>> print(no_return())
None
```
单个函数可以有多个`return`语句。当达到以下`return`语句之一时,函数的执行结束:
```
>>> def multiple_returns(n):
... if(n):
... return "First Return Statement"
... else:
... return "Second Return Statement"
...
>>> print(multiple_returns(True))
First Return Statement
>>> print(multiple_returns(False))
Second Return Statement
```
单个函数可以返回各种类型:
```
>>> def various_return_types(n):
... if(n==1):
... return "Hello World." # Return a string
... elif(n==2):
... return 42 # Return a value
... else:
... return True # Return a boolean
...
>>> print(various_return_types(1))
Hello World.
>>> print(various_return_types(2))
42
>>> print(various_return_types(3))
True
```
甚至可以让单个函数返回多个值,只返回一个:
```
>>> def return_two_values():
... a = 40
... b = 2
... return a,b
...
>>> print("First value = %d, Second value = %d" %(return_two_values()))
First value = 40, Second value = 2
```

View File

@ -0,0 +1,27 @@
---
title: Python Sequence Types
localeTitle: Python序列类型
---
这些表示由非负数索引的有限有序集。内置函数`len()`返回序列的项数。当序列的长度为`n` ,索引集包含数字`0, 1, ..., n-1` 。序列a的项目`i``a<a href='https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy' target='_blank' rel='nofollow'>i]`
\[Python文档 - 标准类型层次结构
## 更多
* 内置序列类型是:
* `list`
* `tuple`
* `range`
* 内置序列类型是可迭代类型(实现所需的`__iter__()`方法)。
* 操作:
* [常用序列操作](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations)
* [可变序列类型](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types)
* [不可变序列类型](https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types)

View File

@ -0,0 +1,22 @@
---
title: Python Set Types
localeTitle: Python集类型
---
set对象是不同的可哈希对象的无序集合。常见用途包括成员资格测试从序列中删除重复项以及计算数学运算如交集并集差异和对称差异。
[Python文档 - 设置类型设置Frozenset](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)
**TODO解释哈希/哈希** 哈希表是一个连续的记录向量,其槽位有三个 口味:
1. 带键+值对的插槽。打电话给这些公民
2. 尚未使用的插槽。称这些处女为人。
3. 插槽曾经是公民,但其密钥被删除,以及在哪里 另一个键+值对尚未覆盖插槽。叫这些 粪便(这是技术术语<0.9眨眼>)。
当处女数量低于三分之一时Python会调整表格的大小 插槽总数。在通常情况下Python将表大小加倍 最多可达1,073,741,824个插槽。但是如果很多 删除留下许多粪便,处女的数量是可能的 尽管很少有公民留下来,但要变得非常低;在那种情况下Python 实际上缩小了表格下降到目前最小的4个插槽
当混合添加和删除时,避免颠簸 table接近调整大小阈值Python实际上没有检查of 删除后的处女(实际上,它假设你很快就会取代 再与公民争吵)。所以,奇怪的是, _永远不会_删除密钥 收缩表。删除后跟添加的长序列可能会缩小 但是,它。在不添加密钥的情况下强制收缩的方法是:
```
dict = dict.copy()
```
dict.copy总是返回最小的无turd字典 2次幂的大小至少留下三分之一的处女。

View File

@ -0,0 +1,43 @@
---
title: Setting Up Python Web Framework Django and Flask
localeTitle: 设置Python Web框架Django和Flask
---
在本文中,我们将讨论如何安装[Django](https://www.djangoproject.com/)和[Flask--](http://flask.pocoo.org/)两个用Python编写的流行Web框架。
也许您已经熟悉Python的广泛使用和社区支持;在网络开发中。您可能也知道Web框架是什么;以及Python可用的选项。
如果这些假设不真实您可能需要查看此Wiki文章 。如果你们都赶上了那就让我们在本地开发机器上设置Python Web框架了。
但如果我们完全忽略[Python 2与Python 3的](http://docs.python-guide.org/en/latest/starting/which-python/#the-state-of-python-2-vs-3)争论,那将是不公平的。
## 虚拟环境
在我们安装Django之前我们将帮助您安装一个非常有用的工具以帮助您的编码环境保持整洁。可以跳过此步骤但强烈建议。从最好的设置开始将为您节省很多麻烦
所以让我们创建一个虚拟环境也称为virtualenv。 Virtualenv将基于每个项目隔离您的Python / Django设置。这意味着您对一个网站所做的任何更改都不会影响您正在开发的任何其他网站。干净吧
有关虚拟环境的更多信息,请参阅[此处](https://guide.freecodecamp.org/python/virtual-environments/)的相关部分。
## 包起来
如果您已经安装了`pip`那么只需:
```
$ pip install django
```
安装完成后我们可以创建一个新项目:
```
$ django-admin startproject myproject
$ cd myproject
$ python manage.py runserver
```
转到`http://localhost:8000` :火箭:
我们已成功安装了我们需要的Web框架。但是它尚未完成。大多数Web应用程序都是内容和数据驱动的 - 因此我们需要数据存储。或者,数据库,如果你愿意的话。
在下一篇文章中我们将讨论如何安装PostgreSQL并将其与我们的Python Web应用程序一起使用。
需要思考的一点 - 我们一直在大力使用`pip` ,但我们几乎没有说过任何关于它的信息。好吧,就目前而言,它只是像`npm`这样的包管理器。它与`npm`有一些差异;但是,你现在不需要担心。如果您有兴趣,请查看[官方`pip`文档](http://pip-python3.readthedocs.org/en/latest/index.html) 。
_如果您有任何建议或问题请加入我们的[gitter](https://gitter.im/FreeCodeCamp/FreeCodeCamp)_

View File

@ -0,0 +1,20 @@
---
title: Share File Using Python SimpleHTTPserver
localeTitle: 使用Python SimpleHTTPserver共享文件
---
## 发送文件需要遵循的步骤。
1. 确保两台计算机通过LAN或WIFI通过同一网络连接。
2. 在Ubuntu中打开终端并确保在PC中安装了python。
3. 如果没有安装则通过键入没有引号的终端“sudo apt-get install python”来安装它。
4. 使用cd更改目录命令转到要共享其文件的目录。
5. 键入此命令“python -m simpleHTTPserver”不带引号。
6. 打开新终端并输入ifconfig并找到您的IP地址。
## 现在在第二台电脑
1. 打开浏览器并输入第一个的IP地址。
2. 不要忘记在IP地址末尾添加端口号。默认情况下为8000
将打开一个页面显示目录类型结构它将显示源PC中的所有文件。
现在您可以访问所有文件。

View File

@ -0,0 +1,22 @@
---
title: Sleep How Can I Make a Time Delay in Python
localeTitle: 睡眠如何在Python中延迟时间
---
## 睡眠如何在Python中延迟时间
Python标准库中的`time`模块包含函数`sleep()` ,该函数将程序暂停给定的秒数。
例:
```
import time
for letter in 'hello, world!':
print(letter)
time.sleep(2) # sleep 2 seconds between each print
```
浮点数可以作为`sleep()`的参数给出,以获得更精确的睡眠时间。
#### 更多信息:
关于睡眠功能的时间模块[文档](https://docs.python.org/3/library/time.html#time.sleep) 。

View File

@ -0,0 +1,51 @@
---
title: Python Slicestartstopstep
localeTitle: Python Slicestartstopstep
---
`slice(start:stop[:step])`是一个通常包含序列一部分的对象。使用下标符号创建切片,\[\]在给定多个数字时使用数字之间的冒号例如在variable\_name \[135\]中。
## 参数
此函数可用于切片元组,数组和列表。
`start`参数的值如果未提供则为None
`stop`参数的值(或序列的最后一个索引)
`step`参数的值如果未提供则为None。它不能是0。
这三个必须是整数类型。
## 返回
如果仅提供`stop` ,则它生成从索引`0``stop`的序列的一部分。
如果仅提供`start` ,则在索引`start`之后生成序列的一部分直到最后一个元素。
如果同时提供了`start``stop` ,它会在索引`start`直到`stop`生成一部分序列。
如果提供了全部三个`start` `stop``step` ,则在索引`start`之后生成序列的一部分,直到`stop`并增加索引`step`
## 例
```
a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[:5]) # prints [1, 2, 3, 4, 5]
print(a[2:]) # prints [3, 4, 5, 6, 7, 8]
print(a[2:5]) # prints [3, 4, 5]
print(a[2:7:2]) # prints [3, 5, 7]
```
您可以使用`-1`索引序列的最后一个索引:
```
a = [1, 2, 3, 4, 5, 6]
print(a[-1]) # prints 6
print(a[2:-1]) # prints [3, 4, 5]
```
您可以使用`[::-1]`切片表示法来翻转序列:
```
a = [1, 2, 3, 4, 5, 6]
print(a[::-1]) # prints [6, 5, 4, 3, 2, 1]
```
[官方文件](https://docs.python.org/3/library/functions.html#slice) ![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/CT5h)

View File

@ -0,0 +1,31 @@
---
title: String Methods
localeTitle: 字符串方法
---
**TODO `string`基本信息**
[Python文档 - 字符串](https://docs.python.org/3/library/stdtypes.html#strings)
**创建:**
使用一对引号或撇号创建空`string`
```shell
>>> new_string = ''
>>> type(new_string)
<class 'string'>
>>> len(new_string)
0
```
[Python文档 - 有关字符串的更多信息](https://docs.python.org/3/tutorial/datastructures.html#more-on-strings)
* `string.find('you')`返回找到子字符串的最低位置。
* `str.join(iterable)`使用指定的字符串连接`iterable`所有元素。
* `str.replace(old, new, max)`方法用于将字符串`old`替换为字符串`new` ,总计`max`次数。此方法返回带有替换的字符串的新副本,并且原始`str`不变。
* `string.split(separator, maxsplit)`返回由分隔字符串的列表`separator` ,可选`maxsplit`的次数,如果没有指定,该字符串将在所有情况下被分裂`separator`
* `string.strip(to_strip)`返回从字符串的开头和结尾删除`to_strip`的字符串。如果未指定`to_strip` ,则将删除所有空白字符。

Some files were not shown because too many files have changed in this diff Show More