Python学习笔记

来源:互联网 发布:windows清理垃圾命令 编辑:程序博客网 时间:2024/05/25 16:38

变量和简单数据类型

变量

  • Python无需定义变量,变量是无类型的。

    message = "Hello, world!"print(message)
  • 变量可以被赋值:

    message = "Hello, world!"print(message)message = 2print(message)

变量的命名

  • 变量名只能有字母、数字、下划线组成,且不能以数字开头。
  • 不能用关键字命名变量
  • 变量名应该尽量短,但具有描述性。

字符串

  • 字符串可以使用双引号也可是使用单引号:

     #两者等价"Hello, world!\n"'Hello, world!\n'

改变字符串大小写

  • title()返回首字母大写的字符串;upper()返回大写的字符串;lower()返回小写的字符串。这三个函数不改变字符串本身。

    name = "cynhard liu"print(name.title()) # Cynhard Liuprint(name.upper()) # CYNHARD LIUprint(name.lower()) # cynhard liu

字符串拼接

  • 用+拼接字符串:

    first_name = "cynhard"last_name = "liu"print(first_name + " " + last_name)  # cynhard liu

转义字符

  • 和其他语言一样,Python支持转义字符:

    print("Hello\tPython\nworld!") # Output: # Hello   Python # world!

删除空白

  • lstrip(),rstrip(),strip()分别删除左侧,右侧,两侧空白:

    print("Hello" + " Python ".lstrip() + "world!")  # HelloPython world!print("Hello" + " Python ".rstrip() + "world!")  # Hello Pythonworld!print("Hello" + " Python ".strip() + "world!")  # HelloPythonworld!

数字

整数和浮点数

  • 整数和浮点数支持 + - * / 等运算,另外还支持**乘幂运算:

    print(2**3)  # 8print(2.4**3.4)  # 19.62086826044312

数字转字符串

  • 使用str()将数字转字符串:

    print("123" + 456) # error,类型不匹配print("123" + str(456))  # 123456

注释

  • Python中注释用#开头

Python之禅

  • 在Python命令行下输入 import this,可以打印Python之禅。

    >>> import thisThe Zen of Python, by Tim PetersBeautiful 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!

列表

  • 列表由一系列按特定顺序排列的元素组成。
  • 用[]来表示列表:

    log_levels = ['info', 'debug', 'warning', 'error', 'fatal']print(log_levels)  # ['info', 'debug', 'warning', 'error', 'fatal']
  • 用下标运算符访问元素,下标从0开始:

    log_levels = ['info', 'debug', 'warning', 'error', 'fatal']print(log_levels[0]) # infoprint(log_levels[1].upper()) # DEBUG

修改、添加和删除元素

修改元素

  • 使用下标运算符修改元素:

    log_levels = ['info', 'debug', 'error', 'fatal']log_levels[1] = 'warning'print(log_levels) # ['info', 'warning', 'error', 'fatal']

添加元素

  • 用append()追加
  • 用insert()插入

    log_levels = ['debug', 'warning', 'error']log_levels.append('fatal')log_levels.insert(0, 'info')print(log_levels) # ['info', 'debug', 'warning', 'error', 'fatal']

删除元素

  • 用del删除

    log_levels = ['debug', 'warning', 'error']del log_levels[0]print(log_levels) # ['warning', 'error']
  • 用pop弹出,如果不加参数,则弹出最后一个,如果有参数,则弹出相应位置的元素。pop会返回弹出的结果

    log_levels = ['debug', 'warning', 'error']last_elem = log_levels.pop()print("pop '" + last_elem + "', result: " + str(log_levels)) # pop 'error' result: ['debug', 'warning']log_levels = ['debug', 'warning', 'error']elem_at_index = log_levels.pop(1)print("pop '" + elem_at_index + "', result: " + str(log_levels)) # pop 'warning' result: ['debug', 'error']
  • 用remove根据值删除

    log_levels = ['debug', 'warning', 'error']log_levels.remove('debug')print(log_levels) # ['warning', 'error']

排序

  • sort方法对列表本身进行排序

    log_levels = ['debug', 'warning', 'error', 'fatal']log_levels.sort()print(log_levels)  # ['debug', 'error', 'fatal', 'warning']
  • sorted函数对返回排序后的列表,本身不变

    log_levels = ['debug', 'warning', 'error', 'fatal']print(sorted(log_levels)) # ['debug', 'error', 'fatal', 'warning']print(log_levels) # ['debug', 'warning', 'error', 'fatal']

逆序

  • 使用reverse方法逆序列表

    log_levels = ['debug', 'warning', 'error', 'fatal']log_levels.reverse()print(log_levels) # ['fatal', 'error', 'warning', 'debug']

数组长度

  • 内置函数len()返回数组长度:

    log_levels = ['debug', 'warning', 'error', 'fatal']print(len(log_levels)) # 4

遍历列表

  • 使用for in遍历列表

    log_levels = ['debug', 'warning', 'error', 'fatal']for log_level in log_levels:    print(log_level) # Output: # debug # warning # error # fatal

缩进和冒号

  • 行尾冒号表示下一行应该缩进,从下一行开始,所有缩进的语句都从属于冒号那一行:

    log_levels = ['debug', 'warning', 'error', 'fatal']for log_level in log_levels: # 以下两行从属于for    message = log_level    print(message)print(log_levels) # 不属于for,在for结束时执行该语句

数值列表

使用range()

  • 使用range(start,end)函数生成从start到end(不包括)的一系列数字:

    for v in range(1, 5):    print(v) # Output: # 1 # 2 # 3 # 4

使用range()创建数字列表

  • 使用list()将range()的结果转换为列表。

    print(list(range(1,5))) # [1, 2, 3, 4]
  • range()可以指定跨度:

    print(list(range(1,10,2))) # [1, 3, 5, 7, 9]

对数字列表进行统计

  • max() min() sum()分别计算最大值、最小值与和。

    nums = list(range(1,11))print(max(nums)) # 10print(min(nums)) # 1print(sum(nums)) # 55

列表解析

  • 列表解析语法可以将for循环和创建新元素的代码合并到一起:

    squares = [value**2 for value in range(1,11)]print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

切片

  • [i:j]返回一个列表从i到j(不包括j)的切片,如果省略i,则为0,如果省略j,则为列表长度。

    log_levels = ['debug', 'warning', 'error', 'fatal']print(log_levels[0:2]) # ['debug', 'warning']print(log_levels[:2]) # ['debug', 'warning']print(log_levels[2:]) # ['error', 'fatal']
  • 如果[i:j]其中有负数,则表示从列表尾部开始计算。

    log_levels = ['debug', 'warning', 'error', 'fatal']print(log_levels[-2:]) # 最后两个元素 ['error', 'fatal']print(log_levels[:-2]) # 最后两个元素之前的元素 ['debug', 'warning']

遍历切片

  • for in 遍历切片

    log_levels = ['debug', 'warning', 'error', 'fatal']for log_level in log_levels[0:3]:    print(log_level) # Output: # debug # warning # error

复制列表

  • 使用切片[:]复制列表

    log_levels = ['debug', 'warning', 'error', 'fatal']log_levels_copy = log_levels[:]log_levels_copy[0] = 'info'print(log_levels_copy)  # ['info', 'warning', 'error', 'fatal']print(log_levels) # ['debug', 'warning', 'error', 'fatal']

元组

  • 元组使用圆括号括起来,元组的值是不能改变的:

    log_levels = ('debug', 'warning', 'error', 'fatal')print(log_levels) # ('debug', 'warning', 'error', 'fatal')print(log_levels[0]) # debuglog_levels[0] = 'info' # error

遍历元组

  • 使用for in遍历元组:

    log_levels = ('debug', 'warning', 'error', 'fatal')for log_level in log_levels:    print(log_level) # Output: # debug # warning # error # fatal

元组赋值

  • 可以给元组重新赋值:

    log_levels = ('debug', 'warning', 'error', 'fatal')log_levels = ('info', 'warning', 'error')print(log_levels) # ('info', 'warning', 'error')

if语句

条件测试

  • == != 比较两个数字或字符串是否相等。

    >>> a,b = 1,1>>> a == bTrue>>> a,b = 1,2>>> a != bTrue
  • 用 > >= < <= 可以比较两个数字大小。

    >>> a,b=1,2>>> a<bTrue
  • 使用and or测试多个条件

    >>> a,b=1,2>>> a==1 and b==2True>>> a,b=1,2>>> a==2 or b==2True
  • 使用in not int测试从属

    >>> a=[1,2,3]>>> 1 in aTrue>>> 4 not in aTrue
  • 空列表作为if条件时为False

    a = []if a:    print("Not empty")else:    print("Empty") # Output: Empty

if语句

  • 基本形式:

    if condition:    # ...
  • if-else

    if condition:    # ...else:    # ...
  • if-elif-else

    if condition:    # ...elif condition:    # ...else:    # ...
  • 多个elif

    if condition:    # ...elif condition:    # ...elif condition:    # ...else:    # ...
  • 省略else

    if condition:    # ...elif condition:    # ...

字典

  • 字典是一系列键值对,每个键对应一个值。在Python中字典用大括号括起来的若干个键值对组成,键值之间用冒号分割,键值对之间用逗号分隔:

    debug_info = {'level': 'error', 'msg': 'file not found'}

使用字典

  • 通过下标访问字典中的值:

    debug_info = {'level': 'error', 'msg': 'file not found'}print(debug_info['msg']) # file not found
  • 通过下标添加键值对:

    debug_info = {'level': 'error', 'msg': 'file not found'}debug_info['os'] = 'windows'
  • 使用下标修改字典中的值:

    debug_info = {'level': 'error', 'msg': 'file not found'}debug_info['level'] = 'info'
  • 用del删除键值对:

    debug_info = {'level': 'error', 'msg': 'file not found'}del debug_info['level']print(debug_info)

遍历字典

遍历所有键值对

  • 字典的items()方法返回键值对列表,用for in遍历它:

    debug_info = {'level': 'error', 'msg': 'file not found'}for key, value in debug_info.items():    print("key:" + key + " value: " + value) # Output: # key:msg value: file not found # key:level value: error

遍历字典中所有的键

  • 字典的keys()方法返回所有的键。

    debug_info = {'level': 'error', 'msg': 'file not found'}for key in debug_info.keys():    print("key:" + key) # Output: # key:msg # key:level

遍历字典中的所有值

  • 字典的values()方法返回所有的值。

    debug_info = {'level': 'error', 'msg': 'file not found'}for value in debug_info.values():    print("value:" + value) # Output: # value:file not found # value:error   

嵌套

字典列表

debug_info = {'level': 'error', 'msg': 'file not found'}debug_info = {'level': 'info', 'msg': 'invalid input'}debug_infos = [    {'level': 'error', 'msg': 'file not found'},    {'level': 'info', 'msg': 'invalid input'}] for debug_info in debug_infos:    print(debug_info)# Output:# {'msg': 'file not found', 'level': 'error'}# {'msg': 'invalid input', 'level': 'info'}

字典中存储列表

debug_info = {'level': 'error', 'msgs': ['file not found', 'invalid input']}print(debug_info)# Output:# {'msgs': ['file not found', 'invalid input'], 'level': 'error'}

字典中存储字典

debug_info = {    'level': 'error',     'msgs': 'file not found',    'version':{'main': 5, 'sub': 17}}print(debug_info)# Output:# {'version': {'main': 5, 'sub': 17}, 'msgs': 'file not found', 'level': 'error'}

用户输入和while循环

  • 用input来获取输入,input接收一个字符串参数,用来打印提示。返回值为一个字符串:

    message = input("Enter a message:")print(message) # Output: # Enter a message:hello, world # hello, world
  • 用 int()将字符串转换为整数:

    print(int(21) * 3)  # 63
  • 取模运算符:

    print(4 % 3) # 1

while循环

num = 1while num < 5:    print(num)    num += 1# Output:# 1# 2

break和continue

  • break退出最内层循环
  • continue退出本次迭代,继续执行下一次迭代

函数

  • 基本形式:

    def greet():    print("hello")greet()  # hello
  • 传递参数:

    def greet(name):    print("hello " + name)greet("Cynhard")  # hello Cynhard
  • 形参与实参:形参是函数参数列表中声明的参数。实参是实际传递的参数。

传递参数

位置实参

  • 按位置传递参数:

    def greet(name, msg):    print(name + " says " + msg)greet("Cynhard", "Hello Python")  # Cynhard says Hello Python

关键字实参:

def greet(name, msg):    print(name + " says " + msg)greet(msg="Hello Python", name="Cynhard")  # Cynhard says Hello Python

默认值

  • 默认值必须放在参数列表中的最后。

    def greet(msg, name="Cynhard"):    print(name + " says " + msg)greet("Hello Python")

返回值

def greetWords(msg, name="Cynhard"):    return name + " says " + msgprint(greetWords("Hello"))  # Cynhard says Hello
  • 返回字典

    def debugInfo():    return {'debug_level':'info', 'msg':'file not found'}print(debugInfo())  # {'debug_level': 'info', 'msg': 'file not found'}

传递列表

  • 在函数中可以修改列表的值:

    def modify(names):    names[0] = 'Cynhard'names = ['Lily', 'Mick']modify(names)print(names)  # ['Cynhard', 'Mick']
  • 禁止修改列表:

    def modify(names):    names[0] = 'Cynhard'names = ['Lily', 'Mick']modify(names[:])print(names)  # ['Lily', 'Mick']

变参函数

def output(*names):    print(names)    for name in names:        print(name)output('Lily', 'Cynhard')

使用任意数量的实参

def print_debuginfo(**debug_info):    for key,value in debug_info.items():        print(key + ":" + value)print_debuginfo(level='debug', msg='file not found')# Output:# level:debug# msg:file not found

将函数存储在模块中

导入整个模块

  • 文件名即为模块

    import module_name#使用时用点访问函数名字module_name.function_name

导入特定函数

# 单个函数from module_name import function_name# 多个函数用逗号隔开from module_name import function_0, function_1, function_2

as给函数指定别名

from module_name import function_name as other_function_name

导入模块中所有函数

from module import *#直接使用函数,无需指定模块名字

class Dog():    # 构造方法    def __init__(self, name, age):        self.name = name        self.age = age    def sit(self):        print(self.name.title() + " is now sitting.")    def roll_over(self):        print(self.name.title() + " rolled over!")# 创建实例        my_dog = Dog('willie', 6)# 访问属性print("My dog's name is " + my_dog.name.title() + ".") # 调用方法my_dog.sit()

继承

class FlyDog(Dog): #括号中指定基类    def __init__(self, name, age, mile):        super().__init__(name, age)  # 用super()指定基类        self.mile = mile    # 重写父类方法        def sit(self):        print(self.name.title() + " is now sitting in the air")my_dog = FlyDog('willie', 6, 10)my_dog.sit()

导入类

导入单个类

创建一个包含Car类的模块,命名为car.py,另一个包导入它:

from car import Car

导入多个类

from module import Class1 Class2

导入整个模块

import car#使用时需要指定carcar.ClassName

导入所有类

from module_name import *#使用时无需指定模块名ClassNamae

文件和异常

读文件

读取整个文件:

with open('hello.py') as file_object:    contents = file_object.read()    print(contents)

关键字with在不需要访问文件后将其关闭。

逐行读取

with open('hello.py') as file_object:    for line in file_object:        print(line)

读取到列表

with open('hello.py') as file_object:    lines = file_object.readlines()for line in lines:    print(line)

写文件

with open('hello.txt', 'w') as file_object:    file_object.write('Hello Python')

附加到文件

with open('hello.txt', 'a') as file_object:    file_object.write('Hello Go')

异常

try:    print(1/0)except ZeroDivisionError:    print("You can't divide by zero!")

else

try:    print(3/2)except ZeroDivisionError:    print("You can't divide by zero!")else:    print('ok')

pass

try:    print(3/2)except ZeroDivisionError:    passelse:    print('ok')

处理json

import jsondata = {'debug_level': 'info', 'msg':'file not found'}file_name = 'test.jon'with open(file_name, 'w') as f_obj:    json.dump(data, f_obj)with open(file_name) as f_obj:    data = json.load(f_obj)    print(data)

测试

  • Python标准库中的模块unittest提供了单元测试工具
  • 必须继承 unittest.TestCase
  • 测试用例以test_开头
  • 断言
    assertEqual(a, b)
    assertNotEqual(a, b)
    assertTrue(x)
    assertFalse(x)
    assertIn(item, list)
    assertNotIn(item, list)

  • setUp()方法初始化方法

  • unittest.main() 执行测试

    import unittestdef echo(msg):    return msgclass MyTest(unittest.TestCase):    def setUp(self):        self.testMsg = 'hello'    def test_echo(self):        self.assertEqual(self.testMsg, echo(self.testMsg))unittest.main()
1 0