Python
是一种通用编程语言,它具有很好的设计原则,因其易于阅读而动态地输入,解释和着名。
freeCodeCamp是Python上最受欢迎的课程之一。它是完全免费的(甚至没有任何广告)。您可以watch it on YouTube here
。
可以找到有关浮点数以及它们如何在Python中工作的一些常规信息here
。
几乎所有Python的实现都遵循IEEE 754规范:二进制浮点运算标准。更多信息发现于IEEE site
。
可以使用创建浮动对象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
constructor
是另一种创造方式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
bool()
是Python 3中的内置函数。此函数返回一个布尔值,即True或False。这需要一个论点,x
。
Arguments {#arguments}
这需要一个论点,x
。x
使用标准转换Truth Testing Procedure
。
Return Value {#return-value}
如果x
是false或省略,返回False
;否则它会返回True
。
Code Sample {#code-sample}
print(bool(4 > 2)) # Returns True as 4 is greater than 2
print(bool(4 < 2)) # Returns False as 4 is not less than 2
print(bool(4 == 4)) # Returns True as 4 is equal to 4
print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds
print(bool(4)) # Returns True as 4 is a non-zero value
print(bool(-4)) # Returns True as -4 is a non-zero value
print(bool(0)) # Returns False as it is a zero value
print(bool('dskl')) # Returns True as the string is a non-zero value
print(bool([1, 2, 3])) # Returns True as the list is a non-zero value
print(bool((2,3,4))) # Returns True as tuple is a non-zero value
print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing
Python Docs - Boolean Operations
这些是布尔运算,按升序排序:
OperationResultNotes x或y如果x为假,则为y,否则x(1)x和y如果x为假,则为x,否则y(2)不为x如果x为假,则为True,否则为False(3)。
Notes:
- This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
- This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
- not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.
Examples: {#examples-}
not
: {#not-}
>>> not True
False
>>> not False
True
and
: {#and-}
>>> True and False # Short-circuited at first argument.
False
>>> False and True # Second argument is evaluated.
False
>>> True and True # Second argument is evaluated.
True
or
: {#or-}
>>> True or False # Short-circuited at first argument.
True
>>> False or True # Second argument is evaluated.
True
>>> False or False # Second argument is evaluated.
False
三种常用的内置常量:
True
: The true value of the bool type. Assignments toTrue
raise a SyntaxError .False
: The false value of the bool type. Assignments toFalse
raise a SyntaxError .None
: The sole value of the type NoneType . None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments toNone
raise a SyntaxError .
其他内置常量:
NotImplemented
: Special value which should be returned by the binary special methods, such as__eg__()
,__add__()
,__rsub__()
, etc.) to indicate that the operation is not implemented with respect to the other type.Ellipsis
: Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.__debug__
: True if Python was not started with an -o option.
站点模块添加的常量。站点模块(在启动期间自动导入,除非给出-S命令行选项)将向内置命名空间添加几个常量。它们对交互式解释器shell很有用,不应在程序中使用。
打印时打印消息,如"使用退出()或Ctrl-D(即EOF)退出",并在调用时,使用指定的退出代码引发SystemExit:
- quit(code=None)
- exit(code=None)
打印时打印"类型许可证()以查看完整许可证文本"的消息,并在调用时以类似寻呼机的方式显示相应的文本(一次一个屏幕):
- copyright
- license
- credits
函数定义语句不执行该函数。执行(调用)函数是通过使用函数的名称,后跟括起所需参数(如果有)的括号来完成的。
>>> def say_hello():
... print('Hello')
...
>>> say_hello()
Hello
函数的执行引入了用于函数局部变量的新符号表。更准确地说,函数中的所有变量赋值都将值存储在本地符号表中。
另一方面,变量引用首先在本地符号表中查找,然后在封闭函数的本地符号表中查找,然后在全局符号表中查找,最后在内置名称表中查找。因此,全局变量不能直接在函数内赋值(除非在全局语句中命名),尽管可以引用它们。
>>> a = 1
>>> b = 10
>>> def fn():
... print(a) # local a is not assigned, no enclosing function, global a referenced.
... b = 20 # local b is assigned in the local symbol table for the function.
... print(b) # local b is referenced.
...
>>> fn()
1
20
>>> b # global b is not changed by the function call.
10
调用函数调用的实际参数(参数)在被调用函数的本地符号表中引入。通过这种方式,使用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]
类提供了将数据和功能捆绑在一起的方法。创建新类会创建一种新类型的对象,从而允许创建该类型的新实例。每个类实例都可以附加属性以保持其状态。类实例还可以具有用于修改其状态的方法(由其类定义)。
与其他编程语言相比,Python的类机制添加了具有最少新语法和语义的类。它是C ++中的类机制的混合体。
Python类提供面向对象编程的所有标准功能:类继承机制允许多个基类,派生类可以覆盖其基类或类的任何方法,并且方法可以调用具有相同名称的基类的方法。
对象可以包含任意数量和种类的数据。与模块一样,类也参与Python的动态特性:它们是在运行时创建的,可以在创建后进一步修改。
Class Definition Syntax : {#class-definition-syntax-}
最简单的类定义形式如下所示:
class ClassName:
<statement-1>
...
...
...
<statement-N>
Class Objects: {#class-objects-}
类对象支持两种操作:属性引用和实例化。
属性引用使用Python中所有属性引用使用的标准语法:obj.name
。有效的属性名称是创建类对象时类的命名空间中的所有名称。所以,如果类定义看起来像这样:
class MyClass:
""" A simple example class """
i = 12345
def f(self):
return 'hello world'
然后MyClass.i
和MyClass.f
是有效的属性引用,分别返回一个整数和一个函数对象。也可以将类属性赋值给,因此可以更改其值MyClass.i
通过转让。__doc__
也是一个有效的属性,返回属于该类的docstring:"A simple example class"
。
类实例化使用函数表示法。只是假装类对象是一个无参数函数,它返回一个新的类实例。例如(假设上述类):
x = MyClass()
创建类的新实例,并将此对象分配给局部变量x。
实例化操作("调用"类对象)创建一个空对象。许多类喜欢创建具有针对特定初始状态定制的实例的对象。因此,类可以定义一个名为的特殊方法 init
(), 像这样:
def __init__(self):
self.data = []
当一个类定义一个__init__()
方法,类实例化自动调用__init__()
对于新创建的类实例。因此,在此示例中,可以通过以下方式获取新的初始化实例:
x = MyClass()
当然,__init__()
方法可能具有更大灵活性的论据。在这种情况下,将赋予类实例化运算符的参数传递给__init__()
。例如,
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
...
x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
在Python中编码时,通常不要混合制表符和空格。这样做可能会导致TabError
,你的程序将崩溃。在编码时保持一致 - 选择使用制表符或空格缩进,并在整个程序中遵循您选择的约定。
Code Blocks and Indentation {#code-blocks-and-indentation}
Python最显着的特点之一是使用缩进来标记代码块。考虑我们简单的密码检查程序中的if语句:
if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')
行打印('登录...')和打印('密码错误。')是两个独立的代码块。这些恰好只有一行,但Python允许您编写由任意数量的语句组成的代码块。
要在Python中指示代码块,必须将块的每一行缩进相同的量。我们的示例if-statement中的两个代码块都缩进了四个空格,这是Python的典型缩进量。
在大多数其他编程语言中,缩进仅用于帮助使代码看起来很漂亮。但是在Python中,需要指出语句所属的代码块。例如,最终的打印('All done!')没有缩进,因此不是else块的一部分。
熟悉其他语言的程序员常常因为缩进很重要而感到愤怒:许多程序员喜欢自由地格式化他们的代码。但是,Python缩进规则非常简单,大多数程序员已经使用缩进来使代码可读。 Python只是将这个想法更进一步,并为缩进赋予了意义。
If/elif-statements {#if-elif-statements}
if / elif语句是具有多个条件的通用if语句。它用于制定复杂的决策。例如,假设航空公司有以下"儿童"机票价格:2岁或以下的儿童免费飞行,2岁以上但13岁以下的儿童支付打折的儿童票价,13岁或以上的任何人支付正常的成人票价。以下计划确定乘客应支付的费用:
# airfare.py
age = int(input('How old are you? '))
if age <= 2:
print(' free')
elif 2 < age < 13:
print(' child fare)
else:
print('adult fare')
在Python从用户开始老化之后,它进入if / elif语句并按照给定的顺序依次检查每个条件。
因此,首先检查年龄是否小于2,如果是,则表明飞行是自由的并且跳出了elif条件。如果age不小于2,则检查下一个elif条件以查看age是否介于2和13之间。如果是,则打印相应的消息并跳出if / elif语句。如果if条件和elif条件都不为True,则它执行else块中的代码。
Conditional expressions {#conditional-expressions}
Python有一个逻辑运算符,一些程序员喜欢(有些不喜欢!)。它本质上是可以直接在表达式中使用的if语句的简写符号。考虑以下代码:
food = input("What's your favorite food? ")
reply = 'yuck' if food == 'lamb' else 'yum'
第二行中=右侧的表达式称为条件表达式,它的计算结果为'yuck'或'yum'。它相当于以下内容:
food = input("What's your favorite food? ")
if food == 'lamb':
reply = 'yuck'
else:
reply = 'yum'
条件表达式通常比相应的if / else语句短,但不够灵活或易于阅读。通常,您应该在使代码更简单时使用它们。
Python中有八个比较操作。它们都具有相同的优先级(高于布尔操作的优先级)。比较可以任意链接;例如,x < y <= z
相当于x < y and y <= z
, 除了那个y
仅评估一次(但在两种情况下z
完全没有评估x < y
被发现是假的)。
以下总结了比较操作:
OperationMeaning<
严格不到<=
小于或等于>
严格大于>=
大于或等于==
等于!=
不等于is
对象身份is not
否定了对象的身份
除了不同的数字类型之外,不同类型的对象永远不会相等。此外,某些类型(例如,函数对象)仅支持简并比较概念,其中该类型的任何两个对象都是不相等的。该<
,<=
,>
和>=
运营商将提出一个TypeError
将复数与另一个内置数值类型进行比较时的异常,当对象具有无法比较的不同类型时,或者在没有定义排序的其他情况下。
除非类定义了类,否则类的非相同实例通常会比较为不相等__eq__()
方法。
除非类定义了足够多的方法,否则无法针对同一类的其他实例或其他类型的对象对类的实例进行排序。__lt__()
,__le__()
,__gt__()
,和__ge__()
(一般来说,__lt__()
和__eq__()
如果你想要比较运算符的常规含义,那就足够了。
的行为is
和is not
运营商无法定制;它们也可以应用于任何两个对象,并且永远不会引发异常。
我们也可以连锁<
和>
运营商在一起例如,3 < 4 < 5
将返回True
但是3 < 4 > 5
将不会。我们也可以链接相等运算符。例如,3 == 3 < 5
将返回True
但3 == 5 < 5
将不会。
Equality Comparisons - "is" vs "==" {#equality-comparisons-is-vs-}
在Python中,有两个比较运算符允许我们检查两个对象是否相等。该is
操作员和==
运营商。但是,他们之间有一个关键的区别!
'是'和'=='之间的关键区别可以概括为:
is
is used to compare identity==
is used to compare equality
Example {#example}
首先,在Python中创建一个列表。
myListA = [1,2,3]
接下来,创建该列表的副本。
myListB = myListA
如果我们使用'=='运算符或'is'运算符,两者都将导致a True
输出。
>>> myListA == myListB # both lists contains similar elements
True
>>> myListB is myListA # myListB contains the same elements
True
这是因为myListA和myListB都指向同一个列表变量,我在Python程序的开头定义了它。两个列表在身份和内容上完全相同。
但是,如果我现在创建一个新列表怎么办?
myListC = [1,2,3]
表演==
运算符仍然显示两个列表在内容方面是相同的。
>>> myListA == myListC
True
但是,表演了is
运营商现在将生产一个False
输出。这是因为myListA和myListC是两个不同的变量,尽管包含相同的数据。即使它们看起来一样,它们也是如此 different
。
>>> myListA is myListC
False # both lists have different reference
总结一下:
- An
is
expression outputsTrue
if both variables are pointing to the same reference - An
==
expression outputsTrue
if both variables contain the same data
python中的Dictionary(又名"dict")是一种可用于存储的内置数据类型 key-value
对。这可以让你治疗一个 dict
喜欢它是一个 database
存储和组织数据。
关于字典的特殊之处在于它们的实现方式。类似哈希表的结构使得检查存在变得容易 - 这意味着我们可以轻松确定字典中是否存在特定键,而无需检查每个元素。 Python解释器只需转到位置键并检查密钥是否存在。
字典几乎可以使用任意数据类型,如字符串,整数等,用于键。但是,不可清除的值,即包含列表,字典或其他可变类型(通过值而不是通过对象标识进行比较)的值可能不会用作键。用于键的数字类型遵循用于数字比较的常规规则:如果两个数字比较相等(例如1
和1.0
)然后它们可以互换使用来索引相同的字典条目。 (但请注意,由于计算机将浮点数存储为近似值,因此将它们用作字典键通常是不明智的。)
字典的一个最重要的要求是键 must
独一无二。
要创建一个空字典,只需使用一对大括号:
>>> teams = {}
>>> type(teams)
>>> <class 'dict'>
要创建包含一些初始值的非空字典,请放置以逗号分隔的键值对列表:
>>> teams = {'barcelona': 1875, 'chelsea': 1910}
>>> teams
{'barcelona': 1875, 'chelsea': 1910}
将键值对添加到现有字典很容易:
>>> teams['santos'] = 1787
>>> teams
{'chelsea': 1910, 'barcelona': 1875, 'santos': 1787} # Notice the order - Dictionaries are unordered !
>>> # extracting value - Just provide the key
...
>>> teams['barcelona']
1875
del
运算符用于从dict中删除键值对。在已经使用的密钥再次用于存储值的情况下,与该密钥关联的旧值完全丢失。另外,请记住,使用不存在的密钥提取值是错误的。
>>> del teams['santos']
>>> teams
{'chelsea': 1910, 'barcelona': 1875}
>>> teams['chelsea'] = 2017 # overwriting
>>> teams
{'chelsea': 2017, 'barcelona': 1875}
in
keyword可用于检查dict中是否存在密钥:
>>> 'sanots' in teams
False
>>> 'barcelona' in teams
True
>>> 'chelsea' not in teams
False
keys
是一个内置的 method
可以用来获取给定字典的键。要将dict中存在的键提取为列表:
>>> club_names = list(teams.keys())
>>> club_names
['chelsea', 'barcelona']
另一种创建字典的方法是使用 dict()
方法:
>>> 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理解来从任意键和值表达式创建字典:
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
Looping in Dictionary
简单地循环遍历字典中的键,而不是键和值:
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for key in d:
... print(key) # do something
...
x
y
z
要循环键和值,可以使用以下内容:
对于Python 2.x:
>>> for key, item in d.iteritems():
... print items
...
1
2
3
采用 items()
对于Python 3.x:
>>> for key, item in d.items():
... print(key, items)
...
x 1
y 2
z 3
在Python中,一切都是 object
。
Objects
表示属性的逻辑分组。属性是数据和/或功能。当用Python创建一个对象时,它是用一个 identity
, type
,和 value
。
在其他语言中, primitives
是 values
没有 properties
(属性)。例如,在javascript中undefined
,null
,boolean
,string
,number
,和symbol
(ECMAScript 2015中的新内容)是原始的。
在Python中,没有原语。None
, booleans
, strings
, numbers
, 乃至 functions
都是 objects
无论它们是如何创建的。
我们可以使用一些内置函数来演示这一点:
内置常量None
,True
,和False
是 objects
:
我们测试了None
对象在这里。
>>> 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
。
>>> 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
!
>>> id(False)
4550117584
>>> type(False)
<class 'bool'>
>>> dir(False)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(False), object)
True
Strings
即使是由字符串文字创建的,也是 objects
。
>>> 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
与...相同 numbers.
>>> id(42)
4550495728
>>> type(42)
<class 'int'>
>>> dir(42)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> issubclass(type(42), object)
True
Functions are Objects Too {#functions-are-objects-too}
在Python中,函数是第一类对象。
Functions
在Python中也是 objects
,用。创建 identity
, type
,和 value
。他们也可以传递给其他人 functions
:
>>> id(dir)
4568035688
>>> type(dir)
<class 'builtin_function_or_method'>
>>> dir(dir)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> issubclass(type(dir), object)
True
也可以将函数绑定到名称,并使用该名称调用绑定函数:
>>> a = dir
>>> print(a)
<built-in function dir>
>>> a(a)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
元组是一系列Python对象。元组是不可变的,这意味着它们在创建后不能被修改,这与列表不同。
Creation:
一个空的tuple
是使用一对圆括号创建的,()
:
>>> empty_tuple = ()
>>> print(empty_tuple)
()
>>> type(empty_tuple)
<class 'tuple'>
>>> len(empty_tuple)
0
一种tuple
通过用逗号分隔元素来创建元素(围绕圆括号,()
,是例外的可选项):
>>> 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
使用单个元素必须使用尾随逗号(带或不带圆括号):
>>> 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元组作为唯一参数。
>>> 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
构造函数:
>>> empty_tuple = tuple()
>>> print(empty_tuple)
()
>>> tuple_from_list = tuple([1,2,3,4])
>>> print(tuple_from_list)
(1, 2, 3, 4)
>>> tuple_from_string = tuple("Hello campers!")
>>> print(tuple_from_string)
('H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!')
>>> a_tuple = 1, 2, 3
>>> b_tuple = tuple(a_tuple) # If the constructor is called with a tuple for
the iterable,
>>> a_tuple is b_tuple # the tuple argument is returned.
True
Accessing elements of a tuple
:
要点tuples
以相同的方式访问和索引lists
是。
>>> my_tuple = 1, 2, 9, 16, 25
>>> print(my_tuple)
(1, 2, 9, 16, 25)
Zero indexed
>>> my_tuple[0]
1
>>> my_tuple[1]
2
>>> my_tuple[2]
9
Wrap around indexing
>>> my_tuple[-1]
25
>>> my_tuple[-2]
16
Packing and Unpacking:
该声明t = 12345, 54321, 'hello!'
是元组包装的一个例子:值12345
,54321
和'hello!'
在元组中包装在一起。反向操作也是可能的:
>>> x, y, z = t
这足够恰当地称为序列解包,适用于右侧的任何序列。序列解包需要在等号的左侧有尽可能多的变量,因为序列中有元素。请注意,多重赋值实际上只是元组打包和序列解包的组合。
>>> t = 1, 2, 3 # Tuple packing.
>>> print(t)
(1, 2, 3)
>>> a, b, c = t # Sequence unpacking.
>>> print(a)
1
>>> print(b)
2
>>> print(c)
3
>>> d, e, f = 4, 5, 6 # Multiple assignment combines packing and unpacking.
>>> print(d)
4
>>> print(e)
5
>>> print(f)
6
>>> a, b = 1, 2, 3 # Multiple assignment requires each variable (right)
have a matching element (left).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
Immutable:
tuples
是不可变的容器,保证 which
它们包含的对象不会改变。确实如此 not
保证它们包含的对象不会改变:
>>> a_list = []
>>> a_tuple = (a_list,) # A tuple (immutable) with a list (mutable) element.
>>> print(a_tuple)
([],)
>>> a_list.append("Hello campers!")
>>> print(a_tuple) # Element of the immutable is mutated.
(['Hello campers!'],)
Uses:
函数只能返回单个值,但是,它是异质的tuple
可用于从函数返回多个值。一个例子是内置的enumerate
返回异构的迭代函数tuples
:
>>> greeting = ["Hello", "campers!"]
>>> enumerator = enumerate(greeting)
>>> enumerator.next()
>>> enumerator.__next__()
(0, 'Hello')
>>> enumerator.__next__()
(1, 'campers!')
装饰器基本上用作包装器。它们在目标函数执行之前和之后修改代码的行为,而无需修改函数本身,增加原始功能,从而对其进行修饰。
在详细介绍装饰器之前,有一些概念应该是清楚的。在Python中,函数是对象,我们可以用它们做很多有用的东西。
Assigning funtions to a variables: {#assigning-funtions-to-a-variables-}
def greet(name):
return "Hello "+name
greet_someone = greet
print greet_someone("John")
输出:你好约翰
Defining functions inside other functions: {#defining-functions-inside-other-functions-}
def greet(name):
def get_message():
return "Hello "
result = get_message()+name
return result
print(greet("John"))
输出:你好约翰
Functions can also be passed as parameters to other functions: {#functions-can-also-be-passed-as-parameters-to-other-functions-}
def greet(name):
return "Hello " + name
def call_func(func):
other_name = "John"
return func(other_name)
print call_func(greet)
输出:你好约翰
Functions can return other functions: {#functions-can-return-other-functions-}
换句话说,函数生成其他函数。
def compose_greet_func():
def get_message():
return "Hello there!"
return get_message
greet = compose_greet_func()
print(greet())
输出:你好!
Inner functions have access to the enclosing scope {#inner-functions-have-access-to-the-enclosing-scope}
通常称为aclosure
。我们在构建装饰器时会遇到的一个非常强大的模式。另外需要注意的是,Python只允许read access to the outer scope
而不是分配。请注意我们如何修改上面的示例以从内部函数的封闭范围中读取"name"参数并返回新函数。
def compose_greet_func(name):
def get_message():
return "Hello there "+name+"!"
return get_message
greet = compose_greet_func("John")
print(greet())
输出:你好约翰!
Composition of Decorators {#composition-of-decorators}
函数装饰器只是现有函数的包装器。将上面提到的想法放在一起,我们可以建立一个装饰器。在这个例子中,让我们考虑一个用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 ipsum,John dolor坐下来</p>
那是我们的第一个装饰师。将另一个函数作为参数的函数,生成一个新函数,扩充原始函数的工作,并返回生成的函数,以便我们可以在任何地方使用它。拥有get_text
本身就是装饰的p_decorate
,我们只需要分配get text to the result of p
装饰。
get_text = p_decorate(get_text)
print (get_text("John"))
输出:lorem ipsum,John dolor坐下来
另一件需要注意的事情是我们的装饰函数采用了名称参数。我们在装饰器中要做的就是让get_text的包装器传递该参数。
Python's Decorator Syntax {#python-s-decorator-syntax}
Python使程序员通过一些创建和使用装饰器更清洁,更好syntactic sugar
。装饰得到 text we don't have to get
text = p decorator(get
文本)。有一个简洁的快捷方式,就是在要装饰的功能之前提到装饰功能的名称。装饰器的名称应该用@符号进行附加。
def p_decorate(func):
def func_wrapper(name):
return "`<p>`{0}`</p>`".format(func(name))
return func_wrapper
@p_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print get_text("John")
输出:<p>
lorem ipsum,John dolor坐下来</p>
现在让我们考虑我们想用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 ipsum,John dolor坐下来</strong></p></div>
这里要注意的一件重要事情是设置装饰器的顺序很重要。如果上面的示例中的顺序不同,则输出会有所不同。
Decorating Methods {#decorating-methods}
在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>
约翰·多伊</p>
一个更好的方法是让我们的装饰器对函数和方法都很有用。这可以通过推杆来完成*args and **kwargs
作为包装器的参数,它可以接受任意数量的参数和关键字参数。
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>
约翰·多伊</p>
Passing arguments to decorators {#passing-arguments-to-decorators}
回顾上面的示例之前的示例,您可以注意到示例中装饰器的冗余程度。 3个装饰器(divdecorate,pdecorate,strong_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>
你好约翰</p>
在这种情况下需要做更多的工作。装饰器期望接收函数作为参数,这就是为什么我们必须构建一个函数来获取那些额外的参数并动态生成装饰器。在上面的例子中,tags是我们的装饰生成器。
Debugging decorated functions {#debugging-decorated-functions}
在一天结束时,装饰者只是包装我们的功能。在调试的情况下,这可能是有问题的,因为包装器函数不携带原始函数的名称,模块和文档字符串。基于上面的例子,如果我们这样做:
print (get_text.__name__)
输出:func wrapper. The output was expected to be get
文字,属性 name
, doc
,和 module
获得 text got overridden by those of the wrapper(func
包装。
显然我们可以在func_wrapper中重新设置它们,但Python提供了更好的方法。
Functools to the rescue
from functools import wraps
def tags(tag_name):
def tags_decorator(func):
@wraps(func)
def func_wrapper(name):
return "`<{0}>`{1}`</{0}>`".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("p")
def get_text(name):
"""returns some text"""
return "Hello "+name
print (get_text.__name__) # get_text
print (get_text.__doc__) # returns some text
print (get_text.__module__) # __main__
您可以从输出中注意到get_text的属性现在是正确的。
Python利用for循环迭代元素列表。这与C或Java不同,它使用for循环来逐步更改值并使用该值访问诸如数组之类的内容。
For循环遍历基于集合的数据结构,如列表,元组和字典。
基本语法是:
for value in list_of_values:
# use value inside this block
通常,您可以使用任何内容作为迭代器值,其中可以为iterable的条目分配。例如,您可以从元组列表中解压缩元组:
list_of_tuples = [(1,2), (3,4)]
for a, b in list_of_tuples:
print("a:", a, "b:", b)
另一方面,您可以遍历任何可迭代的东西。您可以调用函数或使用列表文字。
for person in load_persons():
print("The name is:", person.name)
for character in ["P", "y", "t", "h", "o", "n"]:
print("Give me a '{}'!".format(character))
使用For循环的一些方法:
Iterate over the range() function
for i in range(10):
print(i)
范围实际上是一个不可变的序列类型,而不是一个函数。输出将包含来自下限的结果,即0到上限,即10,但不包括10.默认情况下,下限或起始索引设置为零。输出:
>
0
1
2
3
4
5
6
7
8
9
>
另外,可以通过添加第二和第三参数来指定序列的下限甚至序列的步骤。
for i in range(4,10,2): #From 4 to 9 using a step of two
print(i)
输出:
>
4
6
8
>
xrange() function
在大多数情况下,xrange和range在功能方面完全相同。它们都提供了一种生成整数列表供您使用的方法,但是请您随意使用。唯一的区别是range返回一个Python列表对象,xrange返回一个xrange对象。这意味着xrange实际上并不像运行时那样在运行时生成静态列表。它使用称为yielding的特殊技术根据需要创建值。该技术与一种称为生成器的对象一起使用。
还有一件事要补充。在Python 3.x中,xrange函数不再存在。范围函数现在执行xrange在Python 2.x中的功能
Iterate over values in a list or tuple
A = ["hello", 1, 65, "thank you", [2, 3]]
for value in A:
print(value)
输出:
>
hello
1
65
thank you
[2, 3]
>
Iterate over keys in a dictionary (aka hashmap)
fruits_to_colors = {"apple": "#ff0000",
"lemon": "#ffff00",
"orange": "#ffa500"}
for key in fruits_to_colors:
print(key, fruits_to_colors[key])
输出:
>
apple #ff0000
lemon #ffff00
orange #ffa500
>
Iterate over two lists of same size in a single loop with the zip() function
A = ["a", "b", "c"]
B = ["a", "d", "e"]
for a, b in zip(A, B):
print a, b, a == b
输出:
>
a a True
b d False
c e False
>
Iterate over a list and get the corresponding index with the enumerate() function
A = ["this", "is", "something", "fun"]
for index,word in enumerate(A):
print(index, word)
输出:
>
0 this
1 is
2 something
3 fun
>
一个常见的用例是迭代字典:
for name, phonenumber in contacts.items():
print(name, "is reachable under", phonenumber)
如果您绝对需要访问迭代的当前索引,请执行 NOT
采用range(len(iterable))
!这是一个非常糟糕的做法,会让你从高级Python开发人员那里得到很多笑声。使用内置功能enumerate()
代替:
for index, item in enumerate(shopping_basket):
print("Item", index, "is a", item)
for/else statements
Pyhton允许你在for循环中使用else,当循环体中没有条件满足时执行else case。要使用我们必须使用的其他break
声明,以便我们可以在满意的条件下突破循环。如果我们没有爆发,那么else部分将被执行。
week_days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
today = 'Saturday'
for day in week_days:
if day == today:
print('today is a week day')
break
else:
print('today is not a week day')
在上面的例子中,输出将是today is not a week day
因为循环中的中断永远不会被执行。
Iterate over a list using inline loop function
我们也可以使用python迭代内联。例如,如果我们需要从列表中大写列表中的所有单词,我们可以简单地执行以下操作:
A = ["this", "is", "awesome", "shinning", "star"]
UPPERCASE = [word.upper() for word in A]
print (UPPERCASE)
输出:
>
['THIS', 'IS', 'AWESOME', 'SHINNING', 'STAR']
函数允许您定义可在程序中多次执行的可重用代码块。
功能允许您创建更多模块化和DRY
解决复杂问题。
虽然Python已经提供了许多内置函数,例如print()
和len()
,您还可以定义自己的功能,以便在项目中使用。
在代码中使用函数的一大优势是它减少了项目中代码行的总数。
Syntax {#syntax}
在Python中,函数定义具有以下功能:
-
关键字
def
-
一个功能名称
-
括号'()',括号内的输入参数,尽管输入参数是可选的。
-
冒号':'
-
一些要执行的代码块
-
一个return语句(可选)
a function with no parameters or returned values
def sayHello():print("你好!")
sayHello()#调用函数,'你好!'打印到控制台
a function with a parameter
def helloWithName(name):print("Hello"+ name +"!")
helloWithName("Ada")#调用函数'Hello Ada!'打印到控制台
a function with multiple parameters with a return statement
def multiply(val1,val2):返回val1 * val2
乘以(3,5)#将15打印到控制台
函数是代码块,只需调用函数即可重用。这样可以实现简单,优雅的代码重用,而无需显式重写代码段。这使代码更易读,更容易调试,并限制了输入错误。
Python中的函数是使用def
关键字,后跟括号内的函数名和函数参数。
函数始终返回一个值。该return
函数使用关键字返回值。如果您不想返回任何值,则为默认值None
将被退回。
函数名称用于调用函数,在括号内传递所需的参数。
# this is a basic sum function
def sum(a, b):
return a + b
result = sum(1, 2)
# result = 3
您可以为参数定义默认值,这样Python将解释该参数的值是默认值,如果没有给出。
def sum(a, b=3):
return a + b
result = sum(1)
# result = 4
您可以使用参数名称按所需顺序传递参数。
result = sum(b=2, a=2)
# result = 4
但是,无法在非关键字参数之前传递关键字参数。
result = sum(3, b=2)
#result = 5
result2 = sum(b=2, 3)
#Will raise SyntaxError
函数也是对象,因此您可以将它们分配给变量,并像函数一样使用该变量。
s = sum
result = s(1, 2)
# result = 3
Notes {#notes}
如果函数定义包含参数,则在调用函数时必须提供相同数量的参数。
print(multiply(3)) # TypeError: multiply() takes exactly 2 arguments (0 given)
print(multiply('a', 5)) # 'aaaaa' printed to the console
print(multiply('a', 'b')) # TypeError: Python can't multiply two strings
函数将运行的代码块包括函数内缩进的所有语句。
def myFunc():
print('this will print')
print('so will this')
x = 7
# the assignment of x is not a part of the function since it is not indented
函数中定义的变量仅存在于该函数的范围内。
def double(num):
x = num * 2
return x
print(x) # error - x is not defined
print(double(4)) # prints 8
Python仅在调用函数时解释函数块,而不是在定义函数时解释。因此,即使函数定义块包含某种错误,python解释器也只会在调用函数时指出它。
生成器是一种特殊类型的函数,它允许您在不结束函数的情况下返回值。它通过使用yield
关键词。如同return
,yield
表达式将向调用者返回一个值。两者之间的关键区别在于yield
将暂停该功能,允许将来返回更多值。
生成器是可迭代的,因此它们可以与for循环或任何其他迭代一起使用。
def my_generator():
yield 'hello'
yield 'world'
yield '!'
for item in my_generator():
print(item)
# output:
# hello
# world
# !
像其他迭代器一样,生成器可以传递给next
函数检索下一个项目。当生成器没有更多的值可以产生时,aStopIteration
提出错误。
g = my_generator()
print(next(g))
# 'hello'
print(next(g))
# 'world'
print(next(g))
# '!'
print(next(g))
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# StopIteration
当您需要创建大量值但不需要将它们全部保存在内存中时,生成器特别有用。例如,如果您需要打印第一百万个斐波那契数字,通常会返回一百万个值的列表并迭代列表以打印每个值。但是使用生成器,您可以一次返回一个值:
def fib(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a + b
for x in fib(1000000):
print(x)
Python支持迭代容器的概念。这是使用两种不同的方法实现的;这些用于允许用户定义的类支持迭代。
迭代是以编程方式重复步骤给定次数的过程。程序员可以利用迭代对数据集合中的每个项目执行相同的操作,例如打印出列表中的每个项目。
- Objects can implement a
__iter__()
method that returns an iterator object to support iteration.
迭代器对象必须实现:
__iter__()
: returns the iterator object.__next__()
: returns the next object of the container.iterator object = 'abc'. iter () print(iterator object) print(id(iterator object)) print(id(iterator object. iter ())) # Returns the iterator itself. print(iterator object. next ()) # Returns 1st object and advances iterator. print(iterator object. next ()) # Returns 2nd object and advances iterator. print(iterator object. next ()) # Returns 3rd object and advances iterator. print(iterator object. next ()) # Raises StopIteration Exception.
输出:
<str_iterator object at 0x102e196a0>
4343305888
4343305888
a
b
c
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-1-d466eea8c1b0> in <module>()
6 print(iterator_object.__next__()) # Returns 2nd object and advances iterator.
7 print(iterator_object.__next__()) # Returns 3rd object and advances iterator.
----> 8 print(iterator_object.__next__()) # Raises StopIteration Exception.
StopIteration:
Python中的三元操作(通常也称为条件表达式)允许程序员执行评估并根据给定条件的真实性返回值。
三元运算符与标准不同if
,else
,elif
结构在某种意义上说它不是一个控制流结构,而且表现得更像其他运算符==
要么!=
在Python语言中。
Example {#example-1}
在这个例子中,字符串Even
如果是,则返回val
变量是偶数,否则是字符串Odd
退回。然后将返回的字符串分配给is_even
变量并打印到控制台。
Input {#input}
for val in range(1, 11):
is_even = "Even" if val % 2 == 0 else "Odd"
print(val, is_even, sep=' = ')
Output {#output}
1 = Odd
2 = Even
3 = Odd
4 = Even
5 = Odd
6 = Even
7 = Odd
8 = Even
9 = Odd
10 = Even
Python利用了while
循环类似于其他流行语言。该while
如果条件为真,循环计算条件然后执行代码块。代码块重复执行,直到条件变为false。
基本语法是:
counter = 0
while counter < 10:
# Execute the block of code here as
# long as counter is less than 10
一个例子如下所示:
days = 0
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
while days < 7:
print("Today is " + week[days])
days += 1
输出:
Today is Monday
Today is Tuesday
Today is Wednesday
Today is Thursday
Today is Friday
Today is Saturday
Today is Sunday
以上CODE的逐行说明:
- the variable 'days' is set to a value 0.
- a variable week is assigned to a list containing all the days of the week.
- while loop starts
- the block of code will be executed until the condition returns 'true'.
- the condition is 'days<7' which roughly says run the while loop until the point the variable days is less than 7
- So when the days=7 the while loop stops executing.
- the days variable gets updated on every iteration.
- When the while loop runs for the first time, the line 'Today is Monday' is printed onto the console and the variable days becomes equal to 1.
- Since the variable days is equal to 1 which is less than 7, the while loop is executed again.
- It goes on again and again and when the console prints 'Today is Sunday' the variable days is now equal to 7 and the while loop stops executing.
你可以从这个官方下载Pythonlink
。根据您的操作系统(Windows或Linux或OSX),您可能希望安装Python 3these instructions
。
Using Virtual Environments {#using-virtual-environments}
这总是一个好主意sandbox
您的Python安装并将其与您的安装分开 System Python
。该 System Python
是Python解释器的路径,它与您的操作系统一起安装的其他模块一起使用。
它的 not safe
直接使用安装Python Web框架或库 System Python
。相反,你可以使用Virtualenv
在开发Python应用程序时创建和生成单独的Python进程。
Virtualenvwrapper {#virtualenvwrapper}
该Virtualenvwrapper module
使您可以轻松地在一台计算机上管理和沙箱化多个Python沙盒环境,而不会破坏用Python编写并由您的计算机使用的任何模块或服务。
当然,大多数云托管开发环境如Nitrous
要么Cloud9
还附带这些预安装并准备好让您获得编码!您可以从仪表板中快速选择一个框,并在激活Python 3环境后开始编码。
在Cloud9
,您需要在创建新的开发环境时选择Django框。
下面是一些shell命令示例。如果你想复制粘贴,请注意$
sign是终端提示的简写,它不是命令的一部分。我的终端提示符如下所示:
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
命令;因此,如果您计划使用它们,请确保已安装并添加此模块PATH
变量。
如果你在虚拟环境中;您可以通过检查终端提示轻松找到它。环境名称将在终端提示中清晰显示。
例如,当我在里面的时候py3
环境,我将看到这作为我的终端提示:
(py3)alayek:~/workspace (master) $
请注意(py3)
在括号!如果由于某种原因你没有看到这个,即使你在虚拟的环境中;你可以尝试做其中的一件事mentioned here
。
要退出虚拟环境或停用虚拟环境 - 请使用以下命令:
$ deactivate
同样,这仅适用于virtualenvwrapper模块。
Pipenv {#pipenv}
使用virtualenvwrapper的另一种方法是Pipenv
。它会自动为您的项目创建虚拟环境,并维护一个Pipfile
其中包含依赖项。使用Pipenv意味着您不再需要单独使用pip和virtualenv,或管理自己的requirements.txt
文件。对于那些熟悉JavaScript的人来说,Pipenv类似于使用类似的包装工具npm
。
要开始使用Pipenv,您可以按照这个非常详细的方式进行操作guide
。皮彭夫很容易specify which version of Python
你希望用于每个项目,import
来自现有的requirements.txt
文件和graph
你的依赖。
公众号:银河系1号
联系邮箱:public@space-explore.com
(未经同意,请勿转载)