python 入门到实践 ----笔记

第一部分 基础知识

第 1 章 运行第一个程序 打印消息 “Hello world!” 。
第 2 章 变量中存储信息以及如何使用文本和数字。
第 3 4 章 列表 使用列表能够在一个变量中存储任意数量的信息,从而高效地处理数据:只需几行代码,你就能够处理数百、数千乃至数百万个值。
第 5 章 if 条件判断
第 6 章 使用 Python 字典,将不同的信息关联起来。与列表一样,你也可以根据需要在字典中存储任意数量的信息。
第 7 章 交互式程序 while 循环
第 8 章 函数。函数是执行特定任务的被命名的代码块
第 9 章 类,它让你能够模拟实物,如小狗、小猫、人、汽车、火箭等,让你的代码能够表示任何真实或抽象的东西。
第 10 章 如何使用文件,以及如何处理错误以免程序意外地崩溃。你需要在程序关闭前保存数据,并在程序再次运行时读取它们。你将学习 Python 异常,它们让你能够未雨绸缪,从而让程序妥善地处理错误。
第 11 章为代码编写测试,以核实程序是否像你期望的那样工作。这样,扩展程序时,你就不用担心引入新的 bug要想脱离初级程序员的阵容,跻身于中级程序员的行列,测试代码是你必须掌握的基本技能之一。

第一章 第一个python程序

[root@localhost ~/python]# python #进入python2.7交互式界面 相关版本以及提示信息
Python 2.7.5 (default, Aug 4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>> print("Hello Python World") #也可将代码保存在文件中中使用python命令运行 .py文件
Hello Python World

第二章 变量以及简单数据类型:字符串 数字

2.1变量命名规范

  • 1.变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,
    例如,可将变量命名为 message_1 ,但不能将其命名为 1_message 。
  • 2.变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名 greeting_message 可行,但变量名 greeting message 会引发错误。
  • 3.不要将 Python 关键字和函数名用作变量名,即不要使用 Python 保留用于特殊用途的单词,如 print (请参见附录 A.4 )。
  • 4.变量名应既简短又具有描述性。例如, name 比 n 好, student_name 比 s_n 好, name_length 比 length_of_persons_name 好。
  • 慎用小写字母 l 和大写字母 O ,因为它们可能被人错看成数字 1 和 0 。

    vim hello_world.py

    message = "hello world"   #定义一个变量
    print(message)
    message = "hello python world"
    print(message)
    
    输出信息:
    hello world
    hello python world
    python将记录变量最新值

    2.2字符串

  • pyhon 中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。例如:
    print('I told my friend, "Python is my favorite language!"')
    print("The language 'Python' is named after Monty Python, not the snake.")
    print("One of Python's strengths is its diverse and supportive community.")

  • 调用一些简单的方法进行处理 格式: 实例名.方法名

    >> name = "test_name"
    >> print(name.title())
    Test_Name
    >> print(name.upper())
    TEST_NAME
    >> print(name.lower())
    test_name
    其他方法:
    rstrip() 删除字符串右侧空白
    lstrip() 删除左侧空白
    strip() 删除两端空白

  • 字符串 合并或拼接 用+号
    制表符:"\t"
    换行符:"\n"
    first_name = "ada"
    last_name = "lovelace"
    full_name = first_name + " " + last_name
    print("Hello, " + full_name.title() + "!")
    print("Languages:\nJavaScript\n\t Python")
    注意:在 Python 2 中,无需将要打印的内容放在括号内。
    从技术上说, Python 3 中的 print 是一个函数,因此括号必不可少。有些 Python 2 print 语句也包含括号,但其行为与 Python 3 中
    稍有不同。简单地说,在 Python 2 代码中,有些 print 语句包含括号,有些不包含。
  • 函数的使用方式 #函数名(参数名)
    使用str()函数
    age = 23
    message = "Happy " + str(age) + "rd Birthday!"
    print(message)

2.3数字

  • 整数 :+ - x / 取余:% 乘方:*
    实例:(2 + 3)
    4
  • 浮点数 Python 将带小数点的数字都称为 浮点数
    从很大程度上说,使用浮点数时都无需考虑其行为。你只需输入要使用的数字, Python 通常都会按你期望的方式处理它们

2.4添加 注释

注释用井号( # )标识。井号后面的内容都会被 Python 解释器忽略,如下所示:
#向大家问好
print("Hello Python people!")

2.5python 之禅 .指导原则

编程语言 Perl 曾在互联网领域长期占据着统治地位,早期的大多数交互式网站使用的都是 Perl 脚本。彼时, “ 解决问题的办法有多个 ” 被 Perl 社区奉为座右铭。这种理念一度深受大家的喜爱,因为这种语言固有的灵活性使得大多数问题都有很多不同的解决之道。在开发项目期间,这种灵活性是可以接受的,但大家最终认识到,过于强调灵活性会导致大型项目难以维护:要通过研究代码搞清楚当时解决复杂问题的人是怎么想的,既困难又麻烦,还会耗费大量的时间
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的禅宗
美丽胜于丑陋。
显式比隐式更好。
简单胜于复杂。
复杂比复杂更好。
Flat比嵌套更好。
稀疏比密集好。
可读性计数。
特殊情况不足以打破规则。
虽然实用性胜过纯净。
错误不应该默默通过。
除非明确沉默。
面对歧义,拒绝猜测的诱惑。
应该有一个 - 而且最好只有一个 - 明显的做法。
尽管这种方式一开始可能并不明显,除非你是荷兰人。
现在比永远好。
虽然现在永远不会比正确更好。
如果实现很难解释,这是一个坏主意。
如果实现很容易解释,这可能是一个好主意。
命名空间是一个好主意 - 让我们做更多的这些!

第三章 列表( 索引 元素的值 组织列表)

3.1列表 (索引 元素增删改查)

一系列按特定序列排列的元素组成。给列表启一个表示复数的名称是个不错的选择。在 用方括号[ ] 来表示列表,并用逗号来分隔其中的元素。
下面是一个简单的列表示例,这个列表包含几种自行车:
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

  • 访问列表元素 需要指定元素的位置或索引
    print(bicycles[0])
  • 索引 从0开始不是1
    print(bicycles[3]) ##要访问第四个列表元素,可使用索引 3
    print(bicycles[-1].title()) ##对最后一个元素使用title()方法
  • 元素的增删改
    增:
    列表末尾添加元素 方法 append() 将元素 添加到了列表末尾,而不影响列表中的其他所有元素:
    motorcycles = [] ##定义空列表
    motorcycles.append('honda')
    motorcycles.append('yamaha')
    motorcycles.append('suzuki')
    print(motorcycles)
    插入:
    使用方法insert()可以在列表的任意位置添加元素,但是需要指定索引以及值。
    motorcycles.insert(0, 'ducati') #指定索引以及值
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    motorcycles[0] = 'ducati'
    print(motorcycles)
    删:根据位置或值来删除列表中的元素。
    • del 语句 条件是知道其索引,删除后,你就无法再访问它
      del motorcycles[1]
    • pop() 方法:弹出列表末尾的元素 列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。将元素从列表中删除,并接着使用它的值将其保存在变量中
      popped_motorcycle = motorcycles.pop()
      first_owned = motorcycles.pop(0) ##指定索引删除特定的值
    • remove()方法: 知道要删除的元素的值,可使用方法 remove()
      motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
      print(motorcycles)
      too_expensive = 'ducati'
      motorcycles.remove(too_expensive)
      print(motorcycles)
      print("\nA " + too_expensive.title() + " is too expensive for me.") #变量中保存删除的元素
      回显信息:
      ['honda', 'yamaha', 'suzuki', 'ducati']
      ['honda', 'yamaha', 'suzuki']
      A Ducati is too expensive for me.
      注意:方法 remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
      将在第七章使用循环处理上述问题

3.2 组织列表的常见方式:sort()、 倒序打印列表 、 sorted() 、确定列表的长度}

  • 使用方法 sort() 对列表元素按字母排序 永久排序
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    cars.sort() #字母顺序
    cars.sort(reverse=True) #字母倒序 向 sort() 方法传递参数 reverse=True
  • 使用方法 reverse() 反转列表元素的排列顺序 永久排序
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    print(cars)
    cars.reverse()
    print(cars)
  • 使用sorted()函数进行临死性排序 格式: 函数名(传递给函数的参数)
    sorted(cars)
    ['audi', 'bmw', 'subaru', 'toyota']
  • 函数 len() 可快速获悉列表的长度
    len(cars)

第四章 操作列表

遍历列表 切片 遍历切片 复制切片 元组(定义 遍历 修改元组变量)

4.1 遍历列表 创建数字列表 列表解析

  • 使用for循环遍历列表中的元素,缩进的大妈行都是循环体的一部分
    magicians = ['alice', 'david', 'carolina']
    for magician in magicians: ##注意冒号不要丢
    print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")
    print("Thank you, everyone. That was a great magic show!") ##循环结束后的语句

  • 使用range() 函数生成一系列数字 Python 从你指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为 5)
    for value in range(1,5):
    print(value)
  • 创建数字列表 使用list()函数将range()的结果转话为列表,将range()作 为list()的参数,输出一个数字列表。
    numbers = list(range(1,6)) ##range(1,10,2) 可以指定步长(起始,结束,步长)
    print(numbers)
    创建列表实例:
    squares = []
    for value in range(1,11):
    square = value**2
    squares.append(square)
    print(squares)
    结果:
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • 简单统计计算 函数(参数)
    min(digits)
    max(digits)
    sum(digits)
  • 列表解析
    要使用这种语法,首先指定一个描述性的列表名,如 squares然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。
    在这个示例中,表达式为 value2 ,它计算平方值。接下来,编写一个 for 循环,用于给表达式提供值,再加上右方括号。在这个示例中, for 循环为 for value in range(1,11) ,它将值1~10 提供给表达式 value2 。
    注意:这里的 for 语句末尾没有冒号。
    squares = [value**2 for value in range(1,11)]
    print(squares)
    结果与你在前面看到的平方数列表相同:
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4.2 切片 遍历切片 复制列表

  • 切片:对列表的部分元素进行处理
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[0:3])
    print(players[1:4]) #提取列表的第 2~4 个元素
    print(players[:4]) #不指定第一个索引默认为开头
    print(players[2:]) #到列表末尾
    负数索引返回离列表末尾相应距离的元素,因此你可以输出列表末尾的任何切片。例如,如果你要输出名单上的最后三名队员:
    可使用切片 players[-3:]
  • 遍历切片 在for循环中遍历切片
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print("Here are the first three players on my team:")
    for player in players[:3]:
    print(player.title())
  • 复制列表:创建一个包含整个列表的切片,同时省略起始索引和终止索引[:]

    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foods[:]     #起始末尾复制列表
    ----------------------------------------------------------------
    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foods[:]     #复制列表
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    print("My favorite foods are:")
    print(my_foods)
    print("\nMy friend's favorite foods are:")
    print(friend_foods)
    ----------------------------------------------------------------
    friend_foods = my_foods   #仅仅简单赋值
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    print("My favorite foods are:")
    print(my_foods)
    print("\nMy friend's favorite foods are:")
    print(friend_foods)

    注意:这里将 my_foods 赋给 friend_foods ,而不是将 my_foods 的副本存储到 friend_foods (见❶)。这种语法实际上是让 Python 将新变量 friend_foods 关联到包含在 my_foods 中的列表,因此这两个变量都指向同一个列表。鉴于此,当我们将 'cannoli' 添加到 my_foods 中时,它也将出现在 friend_foods 中;同样,虽然 'icecream' 好像只被加入到了 friend_foods 中,但它也将出现在这两个列表中。

    4.3 元组 (定义 遍历 修改)

  • 元组:
    列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网站的用户列表或游戏中的角色列表至关重要然而,有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。 Python 将不能修改的值称为 不可变的 ,而不可变的列表被称为 元组。
    dimensions = (200, 50) #(定义元组元素的值,号分割)
    ❶ dimensions[0] = 250 #不可给元组的元组的元素赋值
    ❶处的代码试图修改第一个元素的值,导致 Python 返回类型错误消息。由于试图修改元组的操作是被禁止的,因此 Python 指出不能给元组的元素赋值:
    Traceback (most recent call last):
    File "dimensions.py", line 3, in <module>
    dimensions[0] = 250
    TypeError: 'tuple' object does not support item assignment
  • for遍历元组
    dimensions = (200, 50)
    for dimension in dimensions:
    print(dimension)
  • 修改元组变量
    虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺寸,可重新定义整个元组:
    dimensions = (200, 50)
    print("Original dimensions:")
    for dimension in dimensions:
    print(dimension)
    dimensions = (400, 100)
    print("\nModified dimensions:")
    for dimension in dimensions:
    print(dimension)

第五章 条件测试if语句

if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式被称为 条件测试 或者 布尔表达式 ,结果要么为 True ,要么为 False 。Python 根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码如果条件测试的值为 True , Python 就执行紧跟在 if 语句后面的代码;如果为 False , Python 就忽略这些代码。

5.1简单示例:

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

5.2 常用条件测试

  • 字符串比较=或 !=
    car = 'bmw' #定义变量的值
    car == 'bmw' #逻辑判断是否相等 结果为True

    requested_topping = 'mushrooms'
    ❶ if requested_topping != 'anchovies':       #if判断是否不等注意必须:
    print("Hold the anchovies!")
    
    Python 中检查是否相等时区分大小写
    car.lower() == 'audi' #先进行转换然后比较
  • 数值比较

    >> age = 19
    >> age < 21
    True
    >> age <= 21
    True
    >> age > 21
    False
    >> age >= 21
    False

  • 检测多个条件 关键字and or

    >> age_0 = 22
    >> age_1 = 18
    age_0 >= 21 and age_1 >= 21 ##相当与bash中的&&
    age_0 >= 21 or age_1 >= 21 ##相当与bash中的||

  • 检测特定的值是否在列表中 in 、not in
    banned_users = ['andrew', 'carolina', 'david']
    user = 'marie'
    if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")
  • 布尔表达式
    布尔表达式 ,它不过是条件测试的别名。与条件表达式一样,布尔表达式的结果要么为 True ,要么为 False 。可以作为条件。
    game_active = True
    can_edit = False

    5.3 if语句

  • if语句
  • if-else
    age = 17
    if age >= 18:
    print("You are old enough to vote!")
    else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")
  • if-elif-else
    Python 只执行 if-elif-else 结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后, Python 将执行紧跟在它后面的代码,并跳过余下的测试
    age = 12
    if age < 4:
    print("Your admission cost is $0.")
    elif age < 18:
    print("Your admission cost is $5.")
    else:
    print("Your admission cost is $10.")
  • 多个elif 代码块
    age = 12
    if age < 4:
    price = 0
    elif age < 18:
    price = 5
    elif age < 65:
    price = 10
    else:
    price = 5
    print("Your admission cost is $" + str(price) + ".")
  • 省略代码块
    Python 并不要求 if-elif 结构后面必须有 else 代码块。在有些情况下, else 代码块很有用;而在其他一些情况下,使用一条 elif 语句来处理特定的情形更清晰
  • 测试多个条件
    if-elif-else 结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后, Python 就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。然而,有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含 elif 和 else 代码块的简单 if 语句。在可能有多个条件为 True ,且你需要在每个条件为 True时都采取相应措施时,适合使用这种方法。
    requested_toppings = ['mushrooms', 'extra cheese']
    if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
    if 'pepperoni' in requested_toppings:
    print("Adding pepperoni.")
    if 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")
    print("\nFinished making your pizza!")

5.4 使用if处理列表

  • 检测特殊元素
    如果比萨店的青椒用完了,该如何处理呢?为妥善地处理这种情况,可在 for 循环中包含一条 if 语句:
    requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
    for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
    print("Sorry, we are out of green peppers right now.")
    else:
    print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
  • 确定列表是否为空
    在 if 语句中将列表名用在条件表达式中时, Python 将在列表至少包含一个元素时返回 True ,并在列表为空时返回 False 。
    requested_toppings = []
    if requested_toppings:
    for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
    else:
    print("Are you sure you want a plain pizza?")
  • 使用多个列表
    ❶ available_toppings = ['mushrooms', 'olives', 'green peppers',
    'pepperoni', 'pineapple', 'extra cheese']
    ❷ requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
    ❸ for requested_topping in requested_toppings:
    ❹ if requested_topping in available_toppings:
    print("Adding " + requested_topping + ".")
    ❺ else:
    print("Sorry, we don't have " + requested_topping + ".")
    print("\nFinished making your pizza!")
    在❶处,我们定义了一个列表,其中包含比萨店供应的配料。请注意,如果比萨店供应的配料是固定的,也可使用一个元组来存储它们。
    在❷处,我们又创建了一个列表,其中包含顾客点的配料,请注意那个不同寻常的配料 —— 'french fries' 。
    在❸处,我们遍历顾客点的配料列表。在这个循环中,对于顾客点的每种配料,我们都检查它是否包含在供应的配料列表中(见❹);
    如果答案是肯定的,就将其加入到比萨中,否则将运行 else 代码块(见❺):打印一条消息,告诉顾客不供应这种配料

    5.5 小结

    在本章中,你学习了如何编写结果要么为 Ture 要么为 False 的条件测试。你学习了如何编写简单的 if 语句、 if-else 语句和 if-elif-else 结构。
    在程序中,你使用了这些结构来测试特定的条件,以确定这些条件是否满足。你学习了如何在利用高效的 for 循环的同时,以不同于其他元素的方式对特定的列表元素进行处理。
    你还再次学习了Python 就代码格式方面提出的建议,这可确保即便你编写的程序越来越复杂,其代码依然易于阅读和理解。
    在第 6 章,你将学习 Python 字典。字典类似于列表,但让你能够将不同的信息关联起来。你将学习如何创建和遍历字典,以及如何将字典同列表和 if 语句结合起来使用。
    学习字典让你能够模拟更多现实世界的情形。

第六章 字典 bash关联属组(创建 添加键值对 修改 遍历字典) 嵌套(列表-字典 字典-列表 字典-字典)

第七章 用户输入和while循环

第八章 函数(定义 传递参数的不通方式 返回值 传递列表 将函数存储在模块中)

第九章 类(创建使用 实例化 继承 导入类 python标准库)

第十章 文件和异常

第十一章 测试代码

猜你喜欢

转载自blog.51cto.com/mengyao/2125726