Rao's Blog

  • 首页

  • 标签

  • 分类

  • 归档

  • 搜索

Python · 输入与输出

发表于 2019-10-24 | 更新于 2019-10-28 | 分类于 Python

文件

实际开发中经常遇到对数据进行持久化操作的场景,而实现数据持久化最直接简单的方式就是将数据保存到文件中。Python 实现文件的读写操作其实非常简单,通过内置的 open 函数,可以指定文件名、操作模式、编码信息等来获得操作文件的对象,然后就可以对文件进行读写操作了。

对象方法 具体含义
read 读取
readline 读取文件每一行
write 写入
close 关闭文件
操作模式 具体含义
'r' 读取 (默认)
'w' 写入(会先截断之前的内容)
'x' 写入,如果文件已经存在会产生异常
'a' 追加,将内容写入到已有文件的末尾
'b' 二进制模式
't' 文本模式(默认)
'+' 更新(既可以读又可以写)

示例:io_using_file.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''

# 打开文件以编辑(writing)
f = open('poem.txt', 'w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close()

# 如果没有特别指定,将假定启用默认的阅读(read)模式
f = open('poem.txt')
while True:
line = f.readline()
# 零长度指示 EOF
if len(line) == 0:
break
# 每行的末尾都已经有了换行符,因为它是从一个文件中进行读取的
print(line, end='')

# 关闭文件
f.close()

输出:
$ python3 io_using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

读写文本文件

  • 使用 open 函数打开文件
  • 使用 encoding 参数指定编码
  • 使用 with 语句来自动调用 close() 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# encoding=utf-8
import time

def main():
# 一次性读取整个文件内容
with open('致橡树.txt', 'r', encoding='utf-8') as f:
print(f.read())

# 通过for-in循环逐行读取
with open('致橡树.txt', mode='r') as f:
for line in f:
print(line, end='')
time.sleep(0.5)
print()

# 读取文件按行读取到列表中
with open('致橡树.txt') as f:
lines = f.readlines()
print(lines)

if __name__ == '__main__':
main()

读写二进制文件

  • 使用 rb 读取二进制图片
  • 使用 wb 写入二进制图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def main():
try:
with open('python.jpg', 'rb') as fs1:
data = fs1.read()
print(type(data)) # <class 'bytes'>
with open('python_bak.jpg', 'wb') as fs2:
fs2.write(data)
except FileNotFoundError as e:
print('指定的文件无法打开.')
except IOError as e:
print('读写文件时出现错误.')
print('程序执行结束.')

if __name__ == '__main__':
main()

读写 JSON 文件

  • 序列化:把变量从内存中变成可存储或传输的过程称之为序列化。
  • 反序列化:把变量从序列化的对象重新读到内存里称之为反序列化。
  • json 库:可以实现 Python 对象和 JSON 格式的序列化和反序列化。
  • pickle 库:使用特有的序列化协议来序列化数据。
json 库方法 具体含义
dump 将 Python 对象按照 JSON 格式序列化到文件中
dumps 将 Python 对象处理成 JSON 格式的字符串
load 将文件中的 JSON 数据反序列化成对象
loads 将字符串的内容反序列化成 Python 对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import json

def main():
mydict = {
'name': '狄仁杰',
'age': 38,
'qq': 957658,
'friends': ['王大锤', '李元芳'],
'cars': [
{'brand': 'BYD', 'max_speed': 180},
{'brand': 'Audi', 'max_speed': 280},
{'brand': 'Benz', 'max_speed': 320}
]
}
try:
with open('data.json', 'w', encoding='utf-8') as fs:
json.dump(mydict, fs)
except IOError as e:
print(e)
print('保存数据完成!')

if __name__ == '__main__':
main()
JSON 类型 Python 类型
{} dict
[] list
“string” str
1234.56 int 或 float
true/false True / False
null None

示例:io_pickle.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import pickle

# 我们存储相关对象的文件的名称
shoplistfile = 'shoplist.data'

# 需要购买的物品清单
shoplist = ['apple', 'mango', 'carrot']

# 准备写入文件
f = open(shoplistfile, 'wb')

# 转储对象至文件
pickle.dump(shoplist, f)
f.close()

# 清除 shoplist 变量
del shoplist

# 重新打开存储文件
f = open(shoplistfile, 'rb')

# 从文件中载入对象
storedlist = pickle.load(f)
print(storedlist)

输出:
$ python io_pickle.py
['apple', 'mango', 'carrot']

Python · 代码规范

发表于 2019-10-24 | 更新于 2019-10-26 | 分类于 Python

格式规范

  • 缩进:统一使用 4 个空格进行缩进

  • 行宽:每行代码尽量不超过 80 个字符

  • 引号:自然语言使用双引号,机器标识使用单引号

  • 空行:模块级函数和类定义之间空两行,类成员函数之间空一行

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class A:

    def __init__(self):
    pass

    def hello(self):
    pass


    def main():
    pass
  • 编码:文件使用 UTF-8 编码,文件头部加入 #-*-conding:utf-8-*- 标识

  • import:import 语句 应该分行书写

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # 正确的写法
    import os
    import sys

    # 不推荐的写法
    import sys,os

    # 正确的写法
    from subprocess import Popen, PIPE
  • 空格:

    • 在二元运算符两边各空一格 [=, -, +=, ==, >, in, is not, and]
    • 函数的参数列表中,, 之后要有空格
    • 函数的参数列表中,默认值等号两边不要添加空格
    • 左括号之后,右括号之前不要加多余的空格
    • 字典对象的左括号之前不要多余的空格
    • 不要为对齐赋值语句而使用的额外空格
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    # 正确的写法
    i = i + 1
    submitted += 1
    x = x * 2 - 1
    hypot2 = x * x + y * y
    c = (a + b) * (a - b)

    # 不推荐的写法
    i=i+1
    submitted +=1
    x = x*2 - 1
    hypot2 = x*x + y*y
    c = (a+b) * (a-b)

    # 正确的写法
    def complex(real, imag):
    pass

    # 不推荐的写法
    def complex(real,imag):
    pass

    # 正确的写法
    def complex(real, imag=0.0):
    pass

    # 不推荐的写法
    def complex(real, imag = 0.0):
    pass

    # 正确的写法
    spam(ham[1], {eggs: 2})

    # 不推荐的写法
    spam( ham[1], { eggs : 2 } )

    # 正确的写法
    dict['key'] = list[index]

    # 不推荐的写法
    dict ['key'] = list [index]

    # 正确的写法
    x = 1
    y = 2
    long_variable = 3

    # 不推荐的写法
    x = 1
    y = 2
    long_variable = 3
  • 换行:

    • 第二行缩进到括号的起始处
    • 禁止复合语句,即一行中包含多个语句
    • if/for/while 一定要换行
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    foo = long_function_name(var_one, var_two,
    var_three, var_four)

    # 正确的写法
    do_first()
    do_second()
    do_third()

    # 不推荐的写法
    do_first();do_second();do_third();

    # 正确的写法
    if foo == 'blah':
    do_blah_thing()

    # 不推荐的写法
    if foo == 'blah': do_blash_thing()
  • docstring:所有的公共模块、函数、类、方法,都应该写 docstring

注释规范

  • 在代码的关键部分,能写注释的要尽量写注释
  • 比较重要的注释段,使用多个等号隔开,可以更加醒目,突出重要性
  • 文档注释以 “”” 开头和结尾,首行不换行,如有多行,末行必需换行
  • 要在文档注释复制函数定义原型,而是具体描述其具体内容,解释具体参数和返回值等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
app = create_app(name, options)


# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================


if __name__ == '__main__':
app.run()


# 不推荐的写法(不要写函数原型等废话)
def function(a, b):
"""function(a, b) -> list"""
... ...


# 正确的写法
def function(a, b):
"""计算并返回a到b范围内数据的平均值"""
... ...

命名规范

  • 模块:模块名尽量使用小写命名,首字母保持小写,尽量不要用下划线
  • 类:类名使用驼峰 (CamelCase) 命名风格,首字母大写,私有类可用一个下划线开头
  • 函数:函数名一律小写,如有多个单词,用下划线隔开,私有函数可用一个下划线开头
  • 变量:变量名尽量小写,如有多个单词,用下划线隔开
  • 常量:常量名采用全大写,如有多个单词,使用下划线隔开
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 模块命名
import decoder
import html_parser


# 类命名
class Farm():
pass

class AnimalFarm(Farm):
pass


# 私有类命名
class _PrivateFarm(Farm):
pass


# 函数命名
def run():
pass

def run_with_env():
pass


# 私有函数命名
class Person():

def _private_func():
pass


# 变量命名
if __name__ == '__main__':
count = 0
school_name = ''


# 常量命名
MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600

Python · 测试

发表于 2019-10-24 | 分类于 Python

单元测试:unittest、setUp()、tearDown()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import unittest

from mydict import Dict

class TestDict(unittest.TestCase):

def test_init(self):
d = Dict(a=1, b='test')
self.assertEqual(d.a, 1)
self.assertEqual(d.b, 'test')
self.assertTrue(isinstance(d, dict))

def test_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')

def test_attr(self):
d = Dict()
d.key = 'value'
self.assertTrue('key' in d)
self.assertEqual(d['key'], 'value')

def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError):
value = d['empty']

def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty

if __name__ == '__main__':
unittest.main()

virtualenv:为应用提供了隔离的 Python 运行环境,解决了不同应用间多版本的冲突问题。

Python · 错误与异常

发表于 2019-10-24 | 更新于 2019-10-28 | 分类于 Python

异常处理

  • try..except:一般来说我们会将所有可能引发异常或错误的语句放在 try 代码块中,将错误处理代码放置在 except 代码块中。
  • finally:总是会执行代码块,不论程序正常还是异常都会执行到。
  • raise:抛出异常,你能够引发的错误或异常必须是直接或间接从属于 Exception(异常) 类的派生类。
  • as:异常类别名。

示例:exceptions_finally.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import sys
import time

f = None
try:
f = open("poem.txt")
# 我们常用的文件阅读风格
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
print("Press ctrl+c now")
# 为了确保它能运行一段时间
time.sleep(2)
except IOError:
print("Could not find file poem.txt")
except KeyboardInterrupt as ki:
print("!! You cancelled the reading from the file.")
finally:
if f:
f.close()
print("(Cleaning up: Closed the file)")

输出:
$ python exceptions_finally.py
Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)

Python · 面向对象

发表于 2019-10-24 | 更新于 2019-10-28 | 分类于 Python

基本概念

一个类(Class)能够创建一种新的类型(Type),其中对象(Object)就是类的实例(Instance),这种从属于对象或类的变量叫作字段(Field),对象还可以使用属于类的函数来实现某些功能,这种函数叫作类的方法(Method),字段与方法通称类的属性(Attribute)。

self:类方法与普通函数只有一种特定的区别,前者必须多加一个 self 参数在参数列表开头。

示例:oop_method.py

1
2
3
4
5
6
7
8
9
10
11
12
class Person:
def say_hi(self):
print('Hello, how are you?')

p = Person()
p.say_hi()
# 前面两行同样可以写作
# Person().say_hi()

输出:
$ python oop_method.py
Hello, how are you?

__init__ :此方法会在类的对象被实例化(Instantiated)时立即运行,对目标对象进行初始化操作。

示例:oop_init.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Person:
def __init__(self, name):
self.name = name

def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Swaroop')
p.say_hi()
# 前面两行同时也能写作
# Person('Swaroop').say_hi()

输出:
$ python oop_init.py
Hello, my name is Swaroop
  • 类变量(Class Variable):共享的,可以被属于该类的所有实例访问。
  • 对象变量(Object variable):由类的每一个独立的对象或实例所拥有。

示例:oop_objvar.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# coding=UTF-8

class Robot:
"""表示有一个带有名字的机器人"""

# 一个类变量,用来计数机器人的数量
population = 0

def __init__(self, name):
"""初始化数据"""

# 一个对象变量
self.name = name
print("(Initializing {})".format(self.name))

# 当有人被创建时,机器人将会增加人口数量
Robot.population += 1

def die(self):
"""我挂了"""
print("{} is being destroyed!".format(self.name))

Robot.population -= 1

if Robot.population == 0:
print("{} was the last one.".format(self.name))
else:
print("There are still {:d} robots working.".format(
Robot.population))

def say_hi(self):
"""来自机器人的诚挚问候:没问题,你做得到!"""
print("Greetings, my masters call me {}.".format(self.name))

# 类方法
@classmethod
def how_many(cls):
"""打印出当前的人口数量"""
print("We have {:d} robots.".format(cls.population))


droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()

droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()

print("\nRobots can do some work here.\n")

print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()

Robot.how_many()

输出:
$ python oop_objvar.py
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.

Robots can do some work here.

Robots have finished their work. So let's destroy them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.

继承

面向对象编程的一大优点是对代码的重用(Reuse),重用的一种实现方法就是通过继承(Inheritance)机制,继承最好是想象成在类之间实现类型与子类型(Type and Subtype)关系的工具。

  • 多态性(Polymorphism):子类和父类存在相同的方法时,子类覆盖了父类的方法。
  • 基类(Base Class)/ 超类(Superclass):SchoolMember 类
  • 派生类(Derived Classes)/ 子类(Subclass):Teacher 和 Student 类
1
2
3
4
5
6
7
8
9
10
            ┌───────────────┐
│ SchoolMember │
└───────────────┘
│
┌────────────┴────────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Teacher │ │ Student │
└─────────────┘ └─────────────┘

示例:oop_subclass.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# coding=UTF-8

class SchoolMember:
'''代表任何学校里的成员。'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {})'.format(self.name))

def tell(self):
'''告诉我有关我的细节。'''
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")

class Teacher(SchoolMember):
'''代表一位老师。'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {})'.format(self.name))

def tell(self):
SchoolMember.tell(self)
print('Salary: "{:d}"'.format(self.salary))


class Student(SchoolMember):
'''代表一位学生。'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized Student: {})'.format(self.name))

def tell(self):
SchoolMember.tell(self)
print('Marks: "{:d}"'.format(self.marks))

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)

# 打印一行空白行
print()

members = [t, s]
for member in members:
# 对全体师生工作
member.tell()

输出:
$ python oop_subclass.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)

Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"25" Marks: "75"

Python · 模块和包

发表于 2019-10-24 | 更新于 2019-10-25 | 分类于 Python

模块

模块(Modules):重用代码是函数,重用函数是模块,以 .py 为扩展名就可以是一个模块,可以避免函数命名冲突。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# module1.py
def foo():
print('hello, world!')

# module2.py
def foo():
print('goodbye, world!')

# test.py
import module1 as m1
import module2 as m2

m1.foo() # 输出hello, world!
m2.foo() # 输出goodbye, world!

Warning:一般来说,你应该尽量避免使用 from...import 语句,而去使用 import 语句。这是为了避免在你的程序中出现名称冲突,同时也为了使程序更加易读。

__name__ :是 Python 中一个隐含的变量,它代表了模块的名字,只有被 Python 解释器直接执行的模块的名字才是 __main__。

示例:module_using_name.py

1
2
3
4
5
6
7
8
9
10
11
12
13
if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')

输出:
$ python module_using_name.py
This program is being run by itself

$ python
>>> import module_using_name
I am being imported from another module
>>>

包

包(Packages):是指一个包含模块与一个特殊的 __init__.py 文件的文件夹,能够方便地组织模块的层次结构。

1
2
3
4
5
6
7
8
mycompany
├─ web
│ ├─ __init__.py
│ ├─ utils.py
│ └─ www.py
├─ __init__.py
├─ emploees.py
└─ utils.py

总结:如同函数是程序中的可重用部分那般,模块是一种可重用的程序,包是用以组织模块的另一种层次结构。Python 所附带的标准库就是这样一组有关包与模块的例子。

Python · 函数

发表于 2019-10-24 | 更新于 2019-10-25 | 分类于 Python

定义

函数(Functions):是指可重复使用的程序片段。

定义函数:可以通过关键字 def 来定义,关键字 return 来返回一个值,关键字 pass 指示没有内容的语句块。

调用函数:可以在任何地方运行代码块,称为调用(Calling)函数。

示例:function1.py

1
2
3
4
5
6
7
8
9
10
11
12
def say_hello():
# 该块属于这一函数
print('hello world')
# 函数结束

say_hello() # 调用函数
say_hello() # 再次调用函数

输出:
$ python function1.py
hello world
hello world

参数

形参:在定义函数时给定的名称称作形参(Parameters)。

实参:在调用函数时你所提供给函数的值称作实参(Arguments)。

示例:function_param.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def print_max(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')

# 直接传递字面值
print_max(3, 4)

x = 5
y = 7

# 以参数的形式传递变量
print_max(x, y)

输出:
$ python function_param.py
4 is maximum
7 is maximum

默认参数:可以通过在函数定义时附加一个赋值运算符(=)来为参数指定默认参数值。

示例:function_default.py

1
2
3
4
5
6
7
8
9
10
def say(message, times=1):
print(message * times)

say('Hello')
say('World', 5)

输出:
$ python function_default.py
Hello
WorldWorldWorldWorldWorld

Warning:只有那些位于参数列表末尾的参数才能被赋予默认参数值,即在函数的参数列表中拥有默认参数值的参数不能位于没有默认参数值的参数之前!

关键字参数:使用命名(关键字)而非位置来指定函数中的参数,不考虑参数的顺序,函数使用更加容易。

示例:function_keyword.py

1
2
3
4
5
6
7
8
9
10
11
12
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)

输出:
$ python function_keyword.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

可变参数:可以通过使用星号 * 来实现在函数里面能够有任意数量的变量,诸如 *param 的星号参数时汇集成元祖,诸如 **param 的双星号参数时汇集成字典。

示例:function_varargs.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def total(a=5, *numbers, **phonebook):
print('a', a)

# 遍历元组中的所有项目
for single_item in numbers:
print('single_item', single_item)

# 遍历字典中的所有项目
for first_part, second_part in phonebook.items():
print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))

输出:
$ python function_varargs.py
a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None

变量

局部变量:当在一个函数的定义中声明变量时,它们不会以任何方式与身处函数之外但具有相同名称的变量产生关系,也就是说,这些变量名只存在于函数这一局部(Local)。

示例:function_local.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
x = 50

def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)

func(x)
print('x is still', x)

输出:
$ python function_local.py
x is 50
Changed local x to 2
x is still 50

全局变量:可以使用关键字 global 定义于函数之外的变量的值,它的作用域是全局。

示例:function_global.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
x = 50

def func():
global x

print('x is', x)
x = 2
print('Changed global x to', x)

func()
print('Value of x is', x)

输出:
$ python function_global.py
x is 50
Changed global x to 2
Value of x is 2

公有:有的函数和变量我们希望给别人使用,正常的函数和变量名是公开的,可以被引用。

私有:有的函数和变量我们希望仅仅在模块内部使用,以 __ 开头的函数或变量是私有的。

Python · 流程控制

发表于 2019-10-24 | 更新于 2019-10-28 | 分类于 Python

简介

Python 有三种控制流语句: if、for 、while,两种相关语句:break、continue。

  • if
  • while
  • for
  • break
  • continue

流程控制

if

if 语句用以条件检查:如果条件为 true,将运行一块语句,否则运行另一块语句,其中 else 从句是可选的。

示例:if.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
number = 23
guess = int(input('Enter an integer : '))

if guess == number:
# 新块从这里开始
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# 新块在这里结束
elif guess < number:
# 另一代码块
print('No, it is a little higher than that')
# 你可以在此做任何你希望在该代码块内进行的事情
else:
print('No, it is a little lower than that')
# 你必须通过猜测一个大于(>)设置数的数字来到达这里。

print('Done')
# 这最后一句语句将在 if 语句执行完毕后执行。

输出:
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done

$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done

$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done

while

while 语句能够让你在条件为真的前提下重复执行某块语句,while 语句是循环(Looping)语句的一种。

示例:while.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
number = 23
running = True

while running:
guess = int(input('Enter an integer : '))

if guess == number:
print('Congratulations, you guessed it.')
# 这将导致 while 循环中止
running = False
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
# 在这里你可以做你想做的任何事

print('Done')

输出:
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

for

for...in 语句是另一种循环语句,其特点是会在一系列对象上进行遍历。

示例:for.py

1
2
3
4
5
6
7
8
9
10
11
12
for i in range(1, 5):
print(i)
else:
print('The for loop is over')

输出:
$ python for.py
1
2
3
4
The for loop is over

break

break 语句用以中断循环语句,也就是中止循环语句的执行。

示例:break.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')

输出:
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done

continue

continue 语句用以跳过当前循环块中的剩余语句,并继续该循环的下一次迭代。

示例:continue.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
# 自此处起继续进行其它任何处理

输出:
$ python continue.py
Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit

Python · 基本数据类型

发表于 2019-10-24 | 更新于 2019-10-28 | 分类于 Python

数据类型

整型(Integers)

Python 可以处理任意大小的整数:

  • Python 2.x 中有 int 和 long 两种类型
  • Python 3.x 中只有 int 类型

浮点型(Floats)

浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,浮点数除了数学写法(如 123.456)之外还支持科学计数法(如 1.23456e2)。

字符串(String)

  • 单引号:所有引号内的空间,诸如空格与制表符,都将按原样保留
  • 双引号:被双引号包括的字符串和被单引号括起的字符串其工作机制完全相同
  • 三引号:可以书写成多行的形式

布尔值(Boolean)

布尔值只有 True、False 两种值,可以将它们分别等价地视为 1 与 0。

列表(List)

list 是一种可变的有序的集合,可以随时添加和删除其中的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
classmates = ['Michael', 'Bob', 'Tracy']

# 增加
classmates.append('Adam') # 增加元素到末尾
classmates.insert(1, 'Jack') # 增加元素到指定位置

# 删除
classmates.pop(i) # 删除指定i位置的元素

# 修改
classmates[i] = 'Sarah' # 替换指定i位置的元素

# 查询
len(classmates) # 查询列表元素的个数
classmates[i] # 查询第i个元素

# 截取
classmates[i:j] # i是头上标,j是尾下标

# 运算符
加号 + : 列表连接运算符
星号 * : 重复操作

元祖(Tuple)

tuple 是一种不可变的有序的列表,一旦初始化就不能修改,因为不可变,所以代码更安全。

1
2
3
4
5
6
7
8
classmates = ('Michael', 'Bob', 'Tracy')

# 查询
classmates[0]t = ()
classmates[-1]

# 空tuple
t = ()

小结:list 和 tuple 是 Python 内置的有序集合,一个可变,一个不可变。

字典(Dict)

Python 内置了字典 dict,全称 dictionary,类似于其他语言的 map,使用键-值(key-value)存储,具有极快的查找速度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}

# 插入
d['Adam'] = 67
d['Jack'] = 90

# 更新
d['Jack'] = 88

# 删除
d.pop('Bob')

# 查询
'Thomas' in d # in判断key是否存在
d.get('Thomas') # get方法取数据

内部存放的顺序和 key 放入顺序没有关系,需要牢记的第一条就是 dict 的 key 必须是不可变对象,和 list 比较,dict 有以下几个特点:

  • 查找和插入的速度极快,不会随着 key 的增加而变慢。
  • 需要占用大量的内存,内存浪费多。

集合(Set)

set 和 dict 类似,是一组不重复 key 的集合,但不存储 value,可以看成无序和无重复元素的集合。

1
2
3
4
5
6
7
s = {1, 2, 3}

# 添加元素
s.add(key)

# 删除元素
s.remove(key)

空值(None)

  • None 是一个特殊的空值
  • None 不能理解为 0,因为 0 是有意义的

变量与常量

常量:通常用全部大写的变量名表示常量。

变量:变量名必须是大小写英文、数字和 _ 的组合,且不能用数字开头。

占位符:

  • %d :整数的占位符
  • %f :小数的占位符
  • %s :字符串的占位符
  • %x :十六进制整数占位符
  • %% :百分号占位符

类型转换:

  • int():将一个数值或字符串转换成整数,可以指定进制
  • float():将一个字符串转换成浮点数
  • str():将指定的对象转换成字符串形式,可以指定编码
  • chr():将整数转换成该编码对应的字符串(一个字符)
  • ord():将字符串(一个字符)转换成对应的编码(整数)

运算符

运算符 描述
[] [:] 下标,切片
** 指数
~ + - 按位取反, 正负号
* / % // 乘,除,模,整除
+ - 加,减
>> << 右移,左移
& 按位与
^ ` `
<= < > >= 小于等于,小于,大于,大于等于
== != 等于,不等于
is is not 身份运算符
in not in 成员运算符
not or and 逻辑运算符
= += -= *= /= %= //= **= &= ` =^=>>=<<=`

Python · 简介安装

发表于 2019-10-24 | 更新于 2019-10-25 | 分类于 Python

简介

Python 是一种极少数能兼具 简单 与 功能强大 的编程语言。

  • 优点:优雅、明确、简单
  • 缺点:执行效率稍低、代码无法加密

安装

1
2
3
4
5
6
7
8
# Mac上安装
$ brew install python3

$ python -V
Python 2.7.10

$ python3 -V
Python 3.7.4

开发

IDE

  • Sublime Text:高级文本编辑器
  • PyCharm:Python 开发神器

注释

  • 单行注释:以 # 开头的语句
  • 多行注释:以 """ 开头,""" 结尾的语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
第一个 Python 程序 - hello, world!
向伟大的 Guido van Rossum 先生致敬

Version: 0.1
Author: Hui Rao
"""

print('hello, world!')
print('你好', '世界') # print("你好,世界!")
print('hello', 'world', sep=', ', end='!')
print('goodbye, world', end='!\n')

注意:Python 程序是 大小写敏感 的。

缩进

Python 语言官方建议使用 四个空格 来缩进,放置在一起的语句必须拥有相同的缩进,每一组这样的语句被称为块。

1…91011…18
Hui Rao

Hui Rao

最好的成长是分享
173 日志
19 分类
14 标签
GitHub E-Mail
© 2021 Hui Rao
由 Hexo 强力驱动 v3.9.0
|
主题 – NexT.Gemini v7.1.0
|