了解Python

Python简介

Python是用来编写应用程序的高级编程语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> 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?

Python的应用场景

了解Python语法

(安装略, 此处使用的是VS2017集成Python 3.7.3版本)

Hello Python

1
>>> print("hello python") # hello python

变量: 和大多脚本语言类似, 不需要声明类型名

命名规范: python中尽量使用小写+下划线命名法(文件名也是如此)

python标准数据类型: 6种: 通过type()查看变量类型

  • Number(数字): int float bool(True/False, 大写开头) complex(实数部分a和虚数部分b构成, 可以用a + bj, 或者complex(a,b)表示)

    1
    2
    >>> a, b, c, d = 20, 5.5, True, 4+3j # 依次为a, b, c, d赋值, 简洁
    >>> print(type(a), type(b), type(c), type(d)) # <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
  • String(字符串): 单引号或者双引号皆可, 习惯性还是用双引号

    1
    2
    3
    >>> print("hello" + " " + "python") # 字符串拼接
    >>> print("hello\tpython\n") # hello python
    # 字符串相关函数查API去
  • Tuple(元组): 不可修改的元素列表

    1
    2
    3
    4
    >>> name = ('captzx') # 字符串拼接
    >>> player_info = ('captzx', 18 ,'male')
    # >>> player_info[1] = 23 # oops, 元祖不可以被修改
    >>> player_info = ('yexu', 120, 'male') # 但可以被重定义
  • List(列表): 由一系列按特定顺序排列的元素组成, 元素之间可以没有任何关系.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    >>> letters = ['a', 'b', 'c', 'd'] # 字母列表
    >>> print(letters) # ['a', 'b', 'c', 'd']
    >>> print(letters[0]) # 访问, 索引-1表示最后一个元素
    >>> letters.append('f') # 追加 ['a', 'b', 'c', 'd', 'f']
    >>> letters.insert(4,'g') # 插入 ['a', 'b', 'c', 'd', 'g', 'f']
    >>> letters[4] = 'e' # 修改 ['a', 'b', 'c', 'd', 'e', 'f']
    >>> del letters[5] # 删除指定元素 ['a', 'b', 'c', 'd', 'e']
    >>> letters.pop() # 弹出尾部元素, 可以带参数弹出指定元素 ['a', 'b', 'c', 'd']
    >>> letters.remove('d') # 按值移除, 但只移除一个值 ['a', 'b', 'c']
    # 其他API: letters.sort(reverse=True) sorted(letters)零时排序返回一个零时副本 letters.reverse() len(letters) max(letters)/min(letters)
    # 切片操作: letters[1:2], letters[:2], letters[-2:], letters[2:], letters[:]全部
    # 复制列表: letters_ref = letters类似引用 letters_copy = letters[:]拷贝副本
  • Set(集合): 类似于列表, 但能够消除重复项

    1
    2
    3
    4
    >>> name = ['captzx', 'captzx']
    >>> name_set = set(name)
    >>> print(name) # ['captzx', 'captzx']
    >>> print(name_set) # {'captzx'} 注意是大括号
  • Dictionary(字典): 键值对

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    >>> color_value = {'red': 0x100, 'green': 0x010} # 定义字典 {'red': 256, 'green': 16}
    >>> color_value['blue'] = 0x001 # 增 {'red': 256, 'green': 16, 'blue': 1}
    >>> del color_value['green'] # 删 {'red': 256, 'blue': 1}
    >>> color_value['red'] = 0x110000 # 改 {'red': 1114112, 'blue': 1}
    >>> color_value['red'] # 查 1114112

    # 遍历字典
    >>> for color, value in color_value.items(): # items返回键值对的列表
    >>> print(letter + color) # 自动换行了 red 1114112 \n blue 1

    >>> color_value.keys() # 返回字典所有键值 dict_keys(['red', 'blue'])
    >>> color_value.values() # 返回字典所有键值 dict_values([1114112, 1])

条件语句: if/else

  • if: elif: else:, 注意后面的冒号
  • 逻辑判断: and/or/in/not in
  • 检查列表是否为空, 直接使用列表名判断即可

循环: for/while

  • 缩进代表代码块, 需要十分注意代码缩进对逻辑带来的影响
  • range(1,11), 创建1~10的列表
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    >>> letters = ['a', 'b', 'c', 'd']
    >>> for letter in letters: # 注意冒号
    >>> print(letter) # 自动换行了

    >>> squares = [v ** 2 for v in range(1,11)] # 列表推导, ** 表示乘方
    >>> print(squares)

    >>> while True: # while循环
    >>> c = input() # 等待输入
    >>> if c == 'q':
    >>> break # break
    >>> if c == 'c':
    >>> continue # continue
    >>> else:
    >>> print(c)

函数: def定义函数

1
2
3
4
5
6
7
8
9
>>> def get_name(person_info):	# def定义函数
>>> """this is func""" # 函数文档, 用于文档生成, 描述该函数的作用
>>> return person_info['name']
>>> person_info = {'name' : 'captzx', 'age': 18}
>>> name = get_name(person_info)
>>> print(name)

>>> # 形参为*null_tuple的空元组, 可以接收不定数量形参, 作为元组的元素
>>> # 形参为**null_dict的空字典, 可以接收不定数量键值对, 作为字典的元素

导入模块或指定函数: from…import…as…

1
2
3
4
5
6
import module # 导入模块
from module_name import function_name # 导入模块指定函数
from module_name import Class_name, Class_name2 # 导入模块指定类
from module_name import function_name as alise # 导入模块指定函数并设置别名
import module as md # 导入模块并设置模块别名
from module_name import * # 导入模块所有函数

类: python中的面向对象编程

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
class Dog(): # 类名采用驼峰命名法
"""类的描述"""
def __init__(self, name, age): # 类似于构造方法, self必须且实例化时自动传递
"""初始化描述"""
self.name = name
self.age = age

def sit(self):
"""sit function desc"""
print(self.name.title() + " is noe sitting")

def roll_over(self):
"""roll_over function desc"""
print(self.name.title() + " rolled over!")

class Teddy(Dog): # 继承
"""Class: Teddy Dog"""
def __init__(self, name, age, color):
"""Teddy Dog __init__"""
super().__init__(name, age) # super().__init__()
self.color = color

def ritian(self):
"""ritian function desc"""
print(self.name.title() + " want ritian~")

def sit(self): # 重写父类方法
"""sit function desc"""
print(self.name + " is noe sitting")

File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def write_file(file_name, content):
with open(file_name, 'w') as file_object:
file_object.write(content) # 写文件

def read_file(file_name):
with open(file_name, 'r') as file_object:
contents = file_object.read() # 读文件
print(contents)

for line in file_object:
print(line.rstrip())

lines = file_object.readlines() # readlines()按行读取, 存储在列表中
for line in lines:
print(line.rstrip())

def append_file(file_name, content):
with open(file_name, 'a') as file_object:
file_object.write(content) # 追加文件

0%