python编程:从入门到实践

第二章 变量和简单的数据类型

命名变量,要避免与关键字重复。

import keyword

print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

1.删除空白

name = "abc ecDAS  "
print(name)
print(name.rstrip())

要确保字符串后面没有空白,可以使用rstrip()。但是这个删除是暂时的,不会影响到变量本身。
同时也可以剔除字符串两端或者开头的空白,分别使用strip()和lstrip()。

2.在python中输出双引号或者单引号的四种解决方案

(1)使用转义字符

print( "\"abc\"")

输出如下

"abc"

(2)单双引号交叉使用
字符串本身含有单引号,那么字符串两端就用双引号来标记,反之亦然
(3)三引号
虽然三引号被用来定义多行文本,但是同样可以用来定义单行文本,当使用三引号标记字符串时,那么字符串本身的单引号和双引号都能正常显示

3.使用str()函数避免类型错误

age = 22
mes = "happy " + str(age) + "rd birthday"
print(mes)

结果:

happy 22rd birthday

第三章 列表简介

3.1 列表是什么

在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。

3.2 修改、添加、删除元素

1.在列表末尾添加元素

a = [2,5,4,7]
a.append(8)
print(a)

结果:

[2, 5, 4, 7, 8]

方法 append () 将元素8添加到了列表末尾。

2.在列表中插入元素

a = [2,5,4,7]
a.insert(0,1)
print(a)

结果:

[1, 2, 5, 4, 7]

方法insert()将元素插入到指定位置。

3.从列表中删除元素

(1)使用del删除元素

a = [0,1,2,3,4]
del a[0]
print(a)

结果:

[1, 2, 3, 4]

del可以删除指定位置的元素
(2)使用pop删除元素

a = [0,1,2,3,4]
b = a.pop(2)
print(a)
print(b)

结果:

[0, 1, 3, 4]
2

pop()删除指定位置的元素,并且可以使用该元素,pop()默认弹出的位置是列表末端的元素。
(3)根据元素值删除元素

a = [0,1,2,3,4,4]
a.remove(4)
print(a)

结果:

[0, 1, 2, 3, 4]

remove只能删除第一个为该值的元素,若多次出现,需要结合循环使用。

3.3 组织列表

1.使用sort()对列表进行永久性排序

a = [2,5,4,2,4,8,9,1,0,7,5]
a.sort()
print(a)

结果:

[0, 1, 2, 2, 4, 4, 5, 5, 7, 8, 9]

也可以进行反向排序,此时sort(reverse = True)。

a = [2,5,4,2,4,8,9,1,0,7,5]
a.sort(reverse = True)
print(a)

结果:

[9, 8, 7, 5, 5, 4, 4, 2, 2, 1, 0]

2.使用sorted()对列表进行临时性排序

该函数只是展示出来一定的顺序,并没有改变列表本身,跟删除空白的strip()是类似的,只是暂时。

a = [2,5,4,2,4,8,9,1,0,7,5]
print(sorted(a))
print(a)

结果:

[0, 1, 2, 2, 4, 4, 5, 5, 7, 8, 9]
[2, 5, 4, 2, 4, 8, 9, 1, 0, 7, 5]

3.倒着打印列表

将该列表颠倒顺序。

a = [0,1,2,3,4]
a.reverse()
print(a)

结果:

[4, 3, 2, 1, 0]

4.确定列表长度

使用len()函数。

第四章 操作列表

1.遍历整个列表

a = [0,1,2,3,4]
for b in a:
    print(b)

结果:

0
1
2
3
4

2.创建数值列表

(1)使用range()函数

a = [0,1,2,3,4]
for b in range(0,5,2):
    print(b,end="")

结果:

024

(2)使用range()创造数字列表

b = list(range(0,5))
print(b,end="")

结果:

[0, 1, 2, 3, 4]

(3)列表解析

squares = [value**2 for value in range(0,5)]
print(squares)

结果:

[0, 1, 4, 9, 16]

复制列表进行操作:

a = list(range(0,11))
b = a[:]
c = a

a.append(11)
b.append(12)
c.append(13)

print(a)
print(b)
print(c)

结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13]

其中,b = a[:]才是复制,c = a只是两个变量关联起来。

3.元组

元组是不可以修改的,用圆括号表示,而可修改的列表是方括号。

第五章 if语句

1.检查特定值是否在列表中

使用关键词in。

cars = ['bmw','audi','toyota','subaru']
car = 'bmw'
if car in cars:
    print(car.upper())
else:
    print(car.title())

结果:

BMW

2.if语句

(1)简单if语句
(2)if-else语句
(3)if-elif-else语句
(4)使用多个elif语句
(5)省略else语句块:有时候最后使用else很有用,能够节省条件满足的显示,但是有时候elif会让条件更加的清晰。
(6)测试多个条件

第六章 字典

1.使用字典

字典是一系列键-值对,每个键都与一个值相关联,可以使用键来访问相关联的值,这个值可以是各种格式。
字典用放在花括号{}中的一系列键值对表示。

car_0 = {'color':'blue','brand':'subaru'}
print(car_0['color'])
print(car_0['brand'])

结果:

blue
subaru

(1)添加,改变键-值对

字典是一种动态结构,可随时在其中添加键-值对。要添加键-值对,可依次指定字典名、用方括号括起的键和相关联的值。

car_0 = {'color':'blue','brand':'subaru'}
car_0['type'] = 'STI'
print(car_0)

结果:

{'color': 'blue', 'brand': 'subaru', 'type': 'STI'}

这个方法依然可以用来修改键-值对

(2)删除一对键-值对

使用del语句。

car_0 = {'color':'blue','brand':'subaru'}
car_0['type'] = 'STI'
print(car_0)
del car_0['type']
print(car_0)

结果:

{'color': 'blue', 'brand': 'subaru', 'type': 'STI'}
{'color': 'blue', 'brand': 'subaru'}

2.遍历字典

car_0 = {'color':'blue','brand':'subaru'}
car_0['type'] = 'STI'
for k,v in car_0.items():
    print(k,v)

结果:

color blue
brand subaru
type STI

一定要注意这个items()。
同样的,若只想遍历键,将后缀改为keys(),若只想遍历值,将后缀改为values()。
可以按照排序顺序遍历:添加sorted()函数:

car_0 = {'color':'blue','brand':'subaru'}
car_0['type'] = 'STI'
for k in sorted(car_0.keys()):
    print(k)

结果:

color
brand
type

3.嵌套

可以在列表中嵌套字典,也可以在字典中嵌套列表,也可以字典嵌套字典。

第七章 用户输入和while循环

1.input()函数

message = input("输入名字:")
print("你好," + message + "!")

结果:

输入名字:水熊
你好,水熊!

但是在使用input()函数时,python将用户输入解读为字符串。
所以可以使用int()函数来将数字的字符串表示转化为数值,有点类似str()函数,都是格式的转换。

2.while循环

(1)使用标志
(2)使用break跳出循环
break是不执行余下代码,直接跳出循环。
(3)使用continue
continue是让python忽略下列的代码,回到循环的开头。

num = 1
while num < 10:
    num += 1
    if num %2 == 0:
        continue
    print(num)

结果:

3
5
7
9

(4)填充字典

cars = {}
flag = True
while flag:
    name = input("please enter your name:")
    car = input("please enter your favirate car:")
    cars[name] = car
    repeat = input("would want to repeat(y/n):")
    if repeat == 'n':
        flag = False
print(cars)
for k,v in cars.items():
    print(k + " like "+v)

输入:

please enter your name:jack
please enter your favirate car:subaru
would want to repeat(y/n):y
please enter your name:tom
please enter your favirate car:tayota
would want to repeat(y/n):y
please enter your name:lisa
please enter your favirate car:honda
would want to repeat(y/n):n

结果:

{'jack': 'subaru', 'tom': 'tayota', 'lisa': 'honda'}
jack like subaru
tom like tayota
lisa like honda

第八章 函数

1.传递参数

(1)位置实参

当调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。

(2)关键字实参

关键字实参是传递给函数的名称一值对。你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆。关键字实参让你无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。

(3)默认值

编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,Pton将使用指定的实参值﹔否则,将使用形参的默认值。因此。给形参指定默认值后,可在函数调用中省略相应的实参。使用默认值可简化函数调用,还可清楚地指出函数的典型用法。
注意﹐使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。这让Python依然能够正确地解读位置实参。

2.传递列表

可以在函数中修改传递给函数的列表,也可以传递给函数这个列表的副本,不改变原来的列表。
下面展示不修改的示例:

def print_modles(unprinted_modles,complete_modles):
    while unprinted_modles:
        current_modles = unprinted_modles.pop()
        complete_modles.append(current_modles)

def show_completed_modles(complete_modles):
    for complete_modle in complete_modles:
        print(complete_modle)
        
unprinted_modles = ['subaru','tayota','bmw']
complete_modles = []

print_modles(unprinted_modles[:], complete_modles)
show_completed_modles(complete_modles)
print(unprinted_modles)

结果:

bmw
tayota
subaru
['subaru', 'tayota', 'bmw']

3.传递任意数量的实参

(1)* 元组

下面的函数只有一个形参*toppings ,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中:

def make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('jack','rose','james')

形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。函数体内的print语句通过生成输出来证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此:
结果:

('pepperoni',)
('jack', 'rose', 'james')

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

(2)** 字典

def buy_cars(name,number,**detailes):
    consumer_info = { }
    consumer_info['Name'] = name
    consumer_info['Number'] = number
    for key,value in detailes.items():
        consumer_info[key] = value
    print(detailes)
    return consumer_info

consumer_info = buy_cars('jack', 21, 
                         brand = 'subaru',
                         color = 'blue',
                         model = 'brz')
print(consumer_info)

结果:

{'brand': 'subaru', 'color': 'blue', 'model': 'brz'}
{'Name': 'jack', 'Number': 21, 'brand': 'subaru', 'color': 'blue', 'model': 'brz'}

4.将函数存在模块中

通过将函数存储在独立的文件中,可隐藏程序代码的细节,将重点放在程序的高层逻辑上。这还能让你在众多不同的程序中重用函数。将函数存储在独立文件中后,可与其他程序员共享这些文件而不是整个程序。知道如何导入函数还能让你使用其他程序员编写的函数库。
(1)通过import导入模块。
(2)也可以通过 form module_name import function_1,function_2,function_3导入模块中的特定函数。
(3)使用as给函数或者模块定别名, form module_name import function_name as fn

第九章 类

1.创建和使用类

class Car():
    def __init__(self,owner,brand,type,color,year):
        self.owner = owner
        self.brand = brand
        self.type = type
        self.color = color
        self.year = year
        self.odometer = 0
        
    def print_detailes(self):
        detailes = self.owner + " buy a " 
        detailes += self.brand + "'s " + self.type
        detailes += " in " + str(self.year)
        detailes += "\n" + self.owner +"\'s car is " + self.color
        print(detailes)
        
    def print_odometer(self):
        print(self.owner +"\'s car has " + str(self.odometer) +" miles on it")

    def update_odometer(self,milage):
        self.odometer = milage
        
my_car = Car('pirlo','subaru','STI','blue',2020)
my_car.print_detailes()
my_car.odometer = 23
my_car.print_odometer()
my_car.update_odometer(81)
my_car.print_odometer()

结果:

pirlo buy a subaru's STI in 2020
pirlo's car is blue
pirlo's car has 23 miles on it
pirlo's car has 81 miles on it

有两种方法来改变属性的值,一种是直接修改,第二种是通过方法来修改属性的值。

2.继承

class Electric_Car(Car):
    def __init__(self, owner, brand, type, color, year):
        super().__init__(owner, brand, type, color, year)

创建子类时,父类必须包含在当前文件中,且位于子类前面。我们定义了子类Electric_Car。定义子类时,必须在括号内指定父类的名称。方法__init__()接受创建car 实例所需的信息。
super()是一个特殊函数,帮助Pyron将父类和子类关联起来。这行代码让Python调用ElectricCar的父类的方法__init__(),让Electric_Car实例包含父类的所有属性。父类也称为超类(superclass),名称super因此而得名。

# -*- coding: utf-8 -*-
#!/usr/bin/python
class Car():
    def __init__(self,owner,brand,type,color,year):
        '''初始化描述汽车属性'''
        self.owner = owner
        self.brand = brand
        self.type = type
        self.color = color
        self.year = year
        self.odometer = 0
        
    def print_detailes(self):
        '''整洁地输出汽车的信息'''
        detailes = self.owner + " buy a " 
        detailes += self.brand + "'s " + self.type
        detailes += " in " + str(self.year)
        detailes += "\n" + self.owner +"\'s car is " + self.color
        print(detailes)
        
    def print_odometer(self):
        '''输出汽车的行驶里程'''
        print(self.owner +"\'s car has " + str(self.odometer) +" miles on it")

    def update_odometer(self,milage):
        '''
        将汽车的行驶里程设为定值
        并且拒绝回调里程数
        '''
        if milage >= self.odometer:
            self.odometer = milage
        else:
              print("你不能回调里程数!!!")  
        
    def increase_odometer(self,miles):
        '''将里程表增加指定值'''
        if miles >= 0:
            self.odometer += miles
        else:
            print("你不能减少里程数!!!")

class Battery():
    def __init__(self,battery_size = 70):
        '''初始换电瓶属性'''
        self.battery_size = battery_size
        
    def print_battery_size(self):
        '''输出电瓶的剩余电量'''
        print("the car has a " + str(self.battery_size)+"-KWh battery")

class Electric_Car(Car):
    def __init__(self, owner, brand, type, color, year):
        '''初始化父类的属性,再初始化电动车自有的属性'''
        super().__init__(owner, brand, type, color, year)
        self.battery = Battery()
        
my_electric_car = Electric_Car('pirlo','tesla','Modle X','black',2020)
my_electric_car.print_detailes()
my_electric_car.battery.battery_size = 170
my_electric_car.battery.print_battery_size()

结果:

pirlo buy a tesla's Modle X in 2020
pirlo's car is black
the car has a 170-KWh battery

第十章 文件和异常

1.读文件

(1)读取整个文件

with open('pi.digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

我们先来看看函数open ()。要以任何方式使用文件——哪怕仅仅是打印其内容,都得先打开文件,这样才能访问它。函数open ()接受一个参数。要打开的文件的名称。Python在当前执行的文件所在的目录中查找指定的文件
关键字with在不再需要访间文件后将其关闭。在这个程序中,注意到我们调用了open (),但没有调用close();你也可以调用open ()和close ()来打开和关闭文件,但这样做时,如果程序存在bug。导致close()语句未执行,文件将不会关闭。这看似微不足道,但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早地调用close (),你会发现需要使用文件时它已关闭(无法访问),这会导致更多的错误。并非在任何情况下都能轻松确定关闭文件的恰当时机,但通过使用前面所示的结构,可让Python去确定:你只管打开文件,并在需要时使用它,Python自会在合适的时候自动将其关闭。
有了表示pi_digist.txt的文件对象后,我们使用方法read()读取这个文件的全部内容,并将其作为一个长长的字符串存储在变量contents中。这样,通过打印contents的值,就可将这个文本文件的全部内容显示出来:

3.1415926

相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。为何会多出这个空行呢﹖因为read ()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是个空行。要删除多出来的空行,可在print语句中使用rstrip ():

(2)文件路径

(1)相对路径
根据你组织文件的方式,有时可能要打开不在程序文件所属目录中的文件。例如,你可能将程序文件存储在了文件夹pyton_work中,而在文件夹python_work中,有一个名为text_fies的文件夹,用于存储程序文件操作的文本文件。虽然文件夹text_fies包含在文件夹pfthon_work中,但仅向open ()传递位于该文件夹中的文件的名称也不可行,因为Pyton只在文件夹python_work中查找,而不会在其子文件夹text_fifes中查找。要让Python打开不与程序文件位于同一个目录中的文件,需要提供文件路径,它让.Python到系统的特定位置去查找。

with open('text_files\filename.txt') as fileobject:

(2)绝对路径

with open('D:\Study\Python\Python_Study_Space\study_demo\filename.txt') as fileobject:

(3)逐行读取

with open('pi.digits.txt') as file_object:
    for line in file_object:
        print(line.rstrip())

结果:

3.1415926
23564568

(4)创建一个包含文件各行的列表

with open('pi.digits.txt') as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

结果:

3.1415926
23564568

使用关键字with时,open ()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。

2.写文件

要将文本写入文件,需要在调用open()函数时提供另外的参数,告诉python我们要写文件。

with open('pi.digits.txt','a') as file_object:
    file_object.write('i love football')

在这里插入图片描述在这里插入图片描述

3.异常

(1)使用try-except代码块

try:
    print(5/0)
except ZeroDivisionError:
    print('零不能作除数')

我们将导致错误的代码行print(5/0)放在了一个try代码块中。如果try代码块中的代码运行起来没有问题,Pyton将跳过except代码块;如果try代码块中的代码导致了错误,Python将查找这样的except 代码块,并运行其中的代码,即其中指定的错误与引发的错误相同。
在这个示例中,try代码块中的代码引发了zeroDivisionError异常,因此P)fron指出了该如何解决问题的except代码块,并运行其中的代码。这样,用户看到的是一条友好的错误消息,而不是traceback:

零不能作除数

(2)使用异常避免崩溃

print("Give me two numbers,I'll divide them.")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nPlease input first number:")
    if first_number == 'q':
        break
    second_number = input("Please input second number:")
    if first_number == 'q':
        break
    try:
        print(int(first_number)/int(second_number))
    except ZeroDivisionError:
        print('零不能作除数')

(3)使用esle代码块

print("Give me two numbers,I'll divide them.")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nPlease input first number:")
    if first_number == 'q':
        break
    second_number = input("Please input second number:")
    if first_number == 'q':
        break
    try:
        ans = int(first_number)/int(second_number)
    except ZeroDivisionError:
        print('零不能作除数')
    else:
        print(ans)

当try中的代码块可以执行时,不发生错误,就会执行else中的代码。
用书本中的话来说就是:依赖try代码块成功执行的代码都应该放到else代码块中。

(4)失败时一声不吭

except ZeroDivisionError:
        pass

将except模块中的代码改为pass。

4.存储数据(Json数据格式)

json.dump()和json.load()

第十一章 测试代码

import unittest
from test_name import get_formatted_name

class NameTestCase(unittest.TestCase):
    def test_fisrt_last_name(self):
        formatted_name = get_formatted_name('eric','jia')
        self.assertEqual(formatted_name,'Eric Jia')

unittest.main()

test_name.py

def get_formatted_name(first,last):
    '''产生一个整洁的大写统一名字'''
    full_name = first + ' ' + last
    return full_name.title()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值