Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

熟悉Python

Hello, World!
Python 是⼀种⾮常简单的语⾔,并且具有⾮常简单的语法。 它⿎励程序员在没有样板(准备好的)代码的情况下进⾏编程。 Python 中最简单的指令是 print 指令,它只是打印出
⼀⾏,并且⾃动包括⼀个换⾏符,这与C++中是不同的。

有两个主要的 Python 版本,Python 2 和 Python 3。 Python 2 和 Python 3 完全不同。 我们使⽤ Python 3,因为它在语义上更正确并⽀持更新的功能。(Python 2 已经不再维护
了。) 例如,Python 2 和 3 之间的⼀个区别是 print 语句。 在 Python 2 中, print 语句不是函数,因此调⽤时不带括号。 但是,在 Python 3 中,它是⼀个函数,并且必须
⽤括号调⽤。

要在 Python 3 中打印字符串,只需编写:

In [1]: print("This line will be printed.")


print("This line will be printed in a new row.")

This line will be printed.


This line will be printed in a new row.

缩进
Python 使⽤缩进来区分程序块,⽽不是像C++那样使⽤花括号。 制表符和空格都受⽀持,但标准缩进要求标准 Python 代码使⽤四个空格。 例如:

In [2]: x = 5
if x > 1:
# indented four spaces
print("x is larger than 1.")

if x < 10:
# another four spaces indent
print("x is smaller than 10.")
else:
print("x is larger than 10.")

else:
print("x is smaller than 1.")

x is larger than 1.
x is smaller than 10.

变量和类型
Python 完全⾯向对象,⽽不是“静态类型”。 不需要在使⽤它们之前声明变量,也不需要声明它们的类型。 Python 中的每个变量都是⼀个对象。

我们将介绍⼀些基本类型的变量。

数字
Python ⽀持两种类型的数字⸺整数(整数)和浮点数(⼩数)。 (它也⽀持复数,但我们先不在这⾥讲解)。

要定义整数,请使⽤以下语法:

In [3]: myint = 7
print(myint)

要定义浮点数,可以使⽤以下符号之⼀:

In [4]: myfloat = 7.0


print(myfloat)
myfloat = float(7)
print(myfloat)

7.0
7.0

字符串
字符串⽤单引号或双引号定义。

In [5]: mystring = 'hello'


print(mystring)
mystring = "hello"
print(mystring)

hello
hello

两者之间的区别在于,使⽤双引号可以很容易地包含撇号(⽽如果使⽤单引号,这些将终⽌字符串)。

In [6]: mystring = "Don't worry about apostrophes"


print(mystring)

Don't worry about apostrophes

可以对数字和字符串执⾏简单的运算符:

In [7]: x = 1
y = 2
z = x + y
print(z)

first_name = "Johnny"
last_name = "Depp"
whole_name = first_name + " " + last_name
print(whole_name)

3
Johnny Depp

也可以像这样为多个变量进⾏赋值

In [8]: a, b = 3, 4
print(a, b)

3 4

不⽀持在数字和字符串之间混合运算符:

In [9]: # This will not work!


one = 1
two = 2
hello = "hello"

print(one + two + hello)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-fa035bb013ee> in <module>
4 hello = "hello"
5
----> 6 print(one + two + hello)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

List
list 与数组⾮常相似。 它们可以包含任何类型的变量,并且可以包含任意数量的变量。 list 也可以以⾮常简单的⽅式进⾏迭代。

In [10]: mylist = ['a', [5,6]] # initi


print(mylist)

# add element to the end of the list


mylist.append(1)
mylist.append(2)
mylist.append(3)

for i in range(len(mylist)):
print(mylist[i])

# prints out 1,2,3


for x in mylist:
print(x)

['a', [5, 6]]


a
[5, 6]
1
2
3
a
[5, 6]
1
2
3

访问不存在的索引会产⽣异常(错误)。

In [11]: mylist = [1,2,3]


print(mylist[10])

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-ac9eeac6db06> in <module>
1 mylist = [1,2,3]
----> 2 print(mylist[10])

IndexError: list index out of range

基本运算符
本节介绍如何在 Python 中使⽤基本运算符。

算术运算符
就像任何其他编程语⾔⼀样,加法、减法、乘法和除法运算符可以与数字⼀起使⽤。

In [12]: number = 1 + 2 * 3 / 4.0


print(number)

2.5

另⼀个可⽤的运算符是模 % 运算符,它返回除法的整数余数。 被除数 % 除数 = 余数 。

In [13]: remainder = 11 % 3
print(remainder)

使⽤两个乘法符号可以建⽴幂关系。

In [14]: squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)

49
8

对字符串使⽤运算符
Python ⽀持使⽤加法运算符连接字符串:

In [15]: helloworld = "hello" + " " + "world"


print(helloworld)

hello world

Python 还⽀持将字符串相乘以形成具有重复序列的字符串:

In [16]: lotsofhellos = "hello" * 10


print(lotsofhellos)

hellohellohellohellohellohellohellohellohellohello

将运算符与列表⼀起使⽤
列表可以与加法运算符连接:

In [17]: even_numbers = [2,4,6,8]


odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)

[1, 3, 5, 7, 2, 4, 6, 8]

就像在字符串中⼀样,Python ⽀持使⽤乘法运算符形成具有重复序列的新列表:

In [18]: print([1,2,3] * 3)

[1, 2, 3, 1, 2, 3, 1, 2, 3]

字符串格式
Python 使⽤ C ⻛格的字符串格式化来创建新的格式化字符串。 % 运算符⽤于格式化包含在 tuple (固定⼤⼩列表)中的⼀组变量,以及格式字符串, 其中包含普通⽂本和“参数
说明符”,特殊符号,如 %s 和 %d 。

假设有⼀个名为 name 的变量,其中包含你⽤户名,然后你想打印。

In [19]: # This prints out "Hello, John!"


name = "John"
print("Hello, %s!" % name)

Hello, John!

要使⽤两个或多个参数说明符,请使⽤ tuple (括号):

In [20]: # This prints out "John is 23 years old."


name = "John"
age = 23
print("%s is %d years old." % (name, age))

John is 23 years old.

任何不是字符串的对象也可以使⽤ %s 运算符进⾏格式化。例如:

In [21]: # This prints out: A list: [1, 2, 3]


mylist = [1,2,3]
print("A list: %s" % mylist)

A list: [1, 2, 3]

以下是应该知道的⼀些基本参数说明符:

%s - 字符串(或任何具有字符串表示的对象,如数字

%d - 整数

%f - 浮点数

%.<number of digits>f - 点右侧具有固定位数的浮点数。

%x/%X - ⼗六进制表示的整数(⼩写/⼤写)

基本字符串操作
字符串是⼀些⽂本。 它们可以定义为引号之间的任何内容:

In [22]: astring = "Hello world!"


astring2 = 'Hello world!'

你学到的第⼀件事是打印⼀个简单的句⼦。 这句话被 Python 存储为⼀个字符串。 但是,我们不会⽴即打印字符串,⽽是探索你可以对它们执⾏的各种操作。 你还可以使⽤单引号


来分配字符串。 但是,如果要分配的值本身包含单引号,你将⾯临问题。 例如,要在这些括号中分配字符串(单引号是 ' '),你只需要像这样使⽤双引号

In [23]: astring = "Hello world!"


print("single quotes are ' '")

print(len(astring))

single quotes are ' '


12

打印出 12,因为“Hello world!” ⻓度为 12 个字符,包括标点符号和空格。

In [24]: astring = "Hello world!"


print(astring.index("o"))

打印出 4,因为第⼀次出现字⺟“o”的位置距离第⼀个字符 4 个字符。 请注意短语中实际上有两个 o - 此⽅法仅识别第⼀个。

但是为什么没有打印出 5? “o”不是字符串中的第五个字符吗? 为了使事情更简单,Python(和⼤多数其他编程语⾔)从 0 ⽽不是 1 开始。所以“o”的索引是 4。

In [25]: astring = "Hello world!"


print(astring.count("l"))

这会计算字符串中 l 的数量。 因此,它应该打印 3。

In [26]: astring = "Hello world!"


print(astring[3:7])

lo w

这将打印字符串的⼀部分,从索引 3 开始,到索引 6 结束。 但是为什么是 6 ⽽不是 7? 同样,⼤多数编程语⾔都这样做 - 它使在这些括号内做数学变得更容易。

如果括号中只有⼀个数字,它将为您提供该索引处的单个字符。 如果你遗漏了第⼀个数字但保留了冒号,它会给你⼀个从开头到你留下的数字的切⽚。 如果你遗漏了第⼆个数字,


它会给你⼀个从第⼀个数字到结尾的切⽚。

你甚⾄可以将负数放在括号内。 它们是从字符串末尾⽽不是开头开始的简单⽅法。 这样,-3 表示“倒数第三个字符”。

In [27]: astring = "Hello world!"


print(astring[3:7:2])

这将跳过⼀个字符打印从 3 到 7 的字符串字符。 这是扩展切⽚语法。 ⼀般形式是[开始:停⽌:步⻓]。

In [28]: astring = "Hello world!"


print(astring[3:7])
print(astring[3:7:1])

lo w
lo w

请注意,它们都产⽣相同的输出

C 中没有像 strrev 这样的函数来反转字符串。 但是使⽤上⾯提到的切⽚语法类型,您可以轻松地反转这样的字符串

In [29]: astring = "Hello world!"


print(astring[::-1])

!dlrow olleH

In [30]: astring = "Hello world!"


print(astring.upper())
print(astring.lower())

HELLO WORLD!
hello world!

这些创建了⼀个新字符串,其中所有字⺟分别转换为⼤写和⼩写。

In [31]: astring = "Hello world!"


print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))

True
False

这⽤于确定字符串是分别以某物开头还是以某物结尾。 第⼀个将打印 True,因为字符串以“Hello”开头。 第⼆个将打印 False,因为字符串肯定不会以“asdfasdfasdf”结尾。

In [32]: astring = "Hello world!"


afewwords = astring.split(" ")

这会将字符串拆分为⼀组字符串,这些字符串在列表中组合在⼀起。 由于此示例在空格处拆分,因此列表中的第⼀项将是“Hello”,第⼆项将是“world!”。

条件
Python 使⽤布尔逻辑来评估条件。 ⽐较或评估表达式时返回布尔值 True 和 False。 例如:

In [33]: x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

True
False
True

请注意,变量赋值是使⽤单个等号运算符 = 完成的,⽽两个变量之间的⽐较是使⽤双等号运算符 == 完成的。 “不等于”运算符标记为 != 。

布尔运算符
and 和 or 布尔运算符允许构建复杂的布尔表达式,例如:

In [34]: name = "John"


age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")

if name == "John" or name == "Rick":


print("Your name is either John or Rick.")

Your name is John, and you are also 23 years old.


Your name is either John or Rick.

“in”运算符
“in”运算符可⽤于检查指定对象是否存在于可迭代对象容器中,例如列表:

In [35]: name = "John"


if name in ["John", "Rick"]:
print("Your name is either John or Rick.")

Your name is either John or Rick.

Python 使⽤缩进来定义代码块,⽽不是括号。 标准的 Python 缩进是 4 个空格,尽管制表符和任何其他空格⼤⼩都可以使⽤,只要它是⼀致的。 请注意,代码块不需要任何终⽌。

以下是使⽤代码块使⽤ Python 的“if”语句的示例:

In [36]: statement = False


another_statement = True
if statement is True:
# do something
pass
elif another_statement is True: # else if
# do something else
pass
else:
# do another thing
pass

例如:

In [37]: x = 2
if x == 2:
print("x equals two!")
else:
print("x does not equal to two.")

x equals two!

如果以下其中⼀项正确,则将语句评估为真:

1. 给出 True 布尔变量,或使⽤表达式计算,例如算术⽐较。

2.传递了⼀个不被认为是“空”的对象。

以下是⼀些被视为空的对象的示例:

1. 空字符串: “”

2. 空列表: []

3. 数字零: 0

4. false 布尔变量: False

“is”运算符
与双等号运算符 == 不同, is 运算符不匹配变量的值,⽽是匹配实例本身。 例如:

In [38]: x = [1,2,3]
y = [1,2,3]
z = x
print(x == y) # Prints out True
print(x is y) # Prints out False
print(x is z) # Prints out True

True
False
True

“not”运算符
在布尔表达式反转它之前使⽤“not”:

In [39]: print(not False) # Prints out True


print((not False) == (False)) # Prints out False

True
False

循环
Python中有两种循环,for和while。

“for”循环
For 循环遍历给定的序列。 这是⼀个例⼦:

In [40]: primes = [2, 3, 5, 7]


for prime in primes:
print(prime)

2
3
5
7

for 循环可以使⽤ range 函数迭代⼀系列数字。 请注意,范围函数是从零开始的。

In [41]: # Prints out the numbers 0,1,2,3,4


for x in range(5):
print(x)

# Prints out 3,4,5


for x in range(3, 6):
print(x)

# Prints out 3,5,7


for x in range(3, 8, 2):
print(x)

0
1
2
3
4
3
4
5
3
5
7

“while”循环
只要满⾜某个布尔条件,while 循环就会重复。 例如:

In [42]: # Prints out 0,1,2,3,4

count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1

0
1
2
3
4

“break”和“continue”语句
break ⽤于退出 for 循环或 while 循环,⽽ continue ⽤于跳过当前块,并返回“for”或“while”语句。 ⼏个例⼦:

In [43]: # Prints out 0,1,2,3,4

count = 0
while True:
print(count)
count += 1
if count >= 5:
break

# Prints out only odd numbers - 1,3,5,7,9


for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

0
1
2
3
4
1
3
5
7
9

我们可以对循环使⽤“else”⼦句吗?
与 C、CPP 等语⾔不同,我们可以使⽤ else 循环。 当“for”或“while”语句的循环条件失败时,将执⾏“else”中的代码部分。 如果在 for 循环内执⾏了 break 语句,则跳过“else”部
分。 请注意,即使有 continue 语句,也会执⾏“else”部分。

这⾥有⼀些例⼦:

In [44]: # Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))

# Prints out 1,2,3,4


for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition")

0
1
2
3
4
count value reached 5
1
2
3
4

函数
什么是函数?
函数是⼀种将代码划分为有⽤块的便捷⽅式,允许我们对代码进⾏排序、使其更具可读性、重⽤并节省⼀些时间。 此外,函数是定义接⼝的关键⽅式,因此程序员可以共享他们的
代码。

你如何在 Python 中编写函数?


正如我们在之前的教程中看到的,Python 使⽤了块。

块是⼀个代码区域,格式为:

block_head:
1st block line
2nd block line
...

python 中的函数是使⽤块关键字“def”定义的,后跟函数的名称作为块的名称。 例如:

In [45]: def my_function():


print("Hello From My Function!")

函数也可以接收参数(从调⽤者传递给函数的变量)。 例如:

In [46]: def my_function_with_args(username, greeting):


print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

函数可以使⽤关键字“return”向调⽤者返回⼀个值。 例如:

In [47]: def sum_two_numbers(a, b):


return a + b

如何在 Python 中调⽤函数? 只需在 () 后写函数名称,将任何所需的参数放在括号内。 例如,让我们调⽤上⾯写的函数(在前⾯的例⼦中):

In [48]: # Define our 3 functions


def my_function():
print("Hello From My Function!")

def my_function_with_args(username, greeting):


print("Hello, %s, From My Function!, I wish you %s"%(username, greeting))

def sum_two_numbers(a, b):


return a + b

# print(a simple greeting)


my_function()

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!


x = sum_two_numbers(1,2)

Hello From My Function!


Hello, John Doe, From My Function!, I wish you a great year!

练习
请完成以下练习中的四个函数

In [70]: import numpy as np


import math
import scipy

def log(x):
return math.log(x, 2)

def entropy(px):
# return the entropy of the random variable 'x' with probability distribution 'px'
return -1

def relative_entropy(px, qx):


# return the relative entropy of the random variable 'x' with probability distribution 'px' and 'qx'
return -1

def joint_entropy(pxy):
# return the joint entropy of the random variable 'x' and 'y' with joint p.d. 'pxy'
return -1

def mutual_infomation(px, py, pxy):


# return the mutual information of I(x;y)
return -1

px = [1/2, 1/2, 0]

qx = [5/36, 1/3, 19/36]


qy = [7/18, 11/18]
qxy = [[1/18, 1/12], [1/18, 5/18], [5/18, 1/4]]

u = [1/3, 1/3, 1/3]

print("An example of how to use the log function:")


print("The logarithmic of px[0] is %.3f" %log(px[0]))

# Test 1:
print("Test 1:")
print("The entropy of x with p.d. px is %.3f" % entropy(px))
print("The entropy of x with p.d. qx is %.3f" % entropy(qx))
print("The entropy of x with p.d. qy is %.3f" % entropy(qy))

# Test 2:
print("Test 2:")
print("The relative entropy of x with p.d. px and qx is %.3f" % relative_entropy(px, qx))

# Test 3:
print("Test 3:")
print("The joint entropy of x, y with p.d. qxy is %.3f" % joint_entropy(qxy))

# Test 4:
print("Test 4:")
print("The mutual information of x, y with p.d. qxy is %.3f" % mutual_infomation(qx, qy, qxy))

# Test 5:
print("Test 5:")
print(relative_entropy(px, u) - log(len(px)) + entropy(px), "should be zero")

# Test 6:
print("Test 6:")
print(joint_entropy(qxy) - entropy(qy) - entropy(qx), "should be negative")

# Test 7:
print("Test 7:")
print(mutual_infomation(qx, qy, qxy) + joint_entropy(qxy) - entropy(qx) - entropy(qy), "should be zero")

An example of how to use the log function:


The logarithmic of px[0] is -1.000
Test 1:
The entropy of x with p.d. px is -1.000
The entropy of x with p.d. qx is -1.000
The entropy of x with p.d. qy is -1.000
Test 2:
The relative entropy of x with p.d. px and qx is -1.000
Test 3:
The joint entropy of x, y with p.d. qxy is -1.000
Test 4:
The mutual information of x, y with p.d. qxy is -1.000
Test 5:
-3.584962500721156 should be zero
Test 6:
1 should be negative
Test 7:
0 should be zero

In [ ]:

You might also like