Professional Documents
Culture Documents
Python Introduction
Python Introduction
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 中打印字符串,只需编写:
缩进
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)
要定义浮点数,可以使⽤以下符号之⼀:
7.0
7.0
字符串
字符串⽤单引号或双引号定义。
hello
hello
两者之间的区别在于,使⽤双引号可以很容易地包含撇号(⽽如果使⽤单引号,这些将终⽌字符串)。
可以对数字和字符串执⾏简单的运算符:
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
不⽀持在数字和字符串之间混合运算符:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-fa035bb013ee> in <module>
4 hello = "hello"
5
----> 6 print(one + two + hello)
List
list 与数组⾮常相似。 它们可以包含任何类型的变量,并且可以包含任意数量的变量。 list 也可以以⾮常简单的⽅式进⾏迭代。
for i in range(len(mylist)):
print(mylist[i])
访问不存在的索引会产⽣异常(错误)。
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-ac9eeac6db06> in <module>
1 mylist = [1,2,3]
----> 2 print(mylist[10])
基本运算符
本节介绍如何在 Python 中使⽤基本运算符。
算术运算符
就像任何其他编程语⾔⼀样,加法、减法、乘法和除法运算符可以与数字⼀起使⽤。
2.5
In [13]: remainder = 11 % 3
print(remainder)
使⽤两个乘法符号可以建⽴幂关系。
In [14]: squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)
49
8
对字符串使⽤运算符
Python ⽀持使⽤加法运算符连接字符串:
hello world
Python 还⽀持将字符串相乘以形成具有重复序列的字符串:
hellohellohellohellohellohellohellohellohellohello
将运算符与列表⼀起使⽤
列表可以与加法运算符连接:
[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 。
Hello, John!
任何不是字符串的对象也可以使⽤ %s 运算符进⾏格式化。例如:
A list: [1, 2, 3]
以下是应该知道的⼀些基本参数说明符:
%s - 字符串(或任何具有字符串表示的对象,如数字
%d - 整数
%f - 浮点数
%x/%X - ⼗六进制表示的整数(⼩写/⼤写)
基本字符串操作
字符串是⼀些⽂本。 它们可以定义为引号之间的任何内容:
print(len(astring))
lo w
lo w
lo w
请注意,它们都产⽣相同的输出
!dlrow olleH
HELLO WORLD!
hello world!
这些创建了⼀个新字符串,其中所有字⺟分别转换为⼤写和⼩写。
True
False
这会将字符串拆分为⼀组字符串,这些字符串在列表中组合在⼀起。 由于此示例在空格处拆分,因此列表中的第⼀项将是“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”运算符
“in”运算符可⽤于检查指定对象是否存在于可迭代对象容器中,例如列表:
例如:
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
“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”:
True
False
循环
Python中有两种循环,for和while。
“for”循环
For 循环遍历给定的序列。 这是⼀个例⼦:
2
3
5
7
0
1
2
3
4
3
4
5
3
5
7
“while”循环
只要满⾜某个布尔条件,while 循环就会重复。 例如:
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”语句。 ⼏个例⼦:
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
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))
0
1
2
3
4
count value reached 5
1
2
3
4
函数
什么是函数?
函数是⼀种将代码划分为有⽤块的便捷⽅式,允许我们对代码进⾏排序、使其更具可读性、重⽤并节省⼀些时间。 此外,函数是定义接⼝的关键⽅式,因此程序员可以共享他们的
代码。
块是⼀个代码区域,格式为:
block_head:
1st block line
2nd block line
...
函数也可以接收参数(从调⽤者传递给函数的变量)。 例如:
函数可以使⽤关键字“return”向调⽤者返回⼀个值。 例如:
#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")
练习
请完成以下练习中的四个函数
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 joint_entropy(pxy):
# return the joint entropy of the random variable 'x' and 'y' with joint p.d. 'pxy'
return -1
px = [1/2, 1/2, 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")
In [ ]: