【啃书系列】Python编程从入门到实践 上

阅读更多文章,请看学习笔记汇总

【啃书系列】Python编程从入门到实践 下
官方Python教程zh
图灵系列Python阅读路径

1. RUNOOB.com_python3-tutorial

2. Python常用函数说明文档

第一章.安装与配置

1.1 配置

  • python官网

  • python3的地址
    终端输入:type -a python3

  • >>>表示终端会话,退出方式ctrl+Dexit()

  • 文件名和文件夹名最好使用小写字母,并用下划线表示空格,这是Python的命名约定,如创建python_work文件夹

  • sublime中设置New Build System,然后删除所有内容,加入如下代码,按Cmd+B即可运行py文件
    { "cmd": ["/usr/local/bin/python3","-u","$file"], }

  • sublime text不支持运行提示用户输入的程序,必须要借助终端来运行,这是它的一个缺点

1.2 PyCharm

  • 推荐用Pycharm,教育邮箱激活,免费试用一年,到期后再次认证即可
    Jetbrains公司开发的IDE功能非常强大
    在这里插入图片描述
    在这里插入图片描述

1.3 头注释

#!/usr/bin/python:这句注释的作用是告诉文件中的代码是用什么编译器去执行;

#!/usr/bin/env python:这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。

-*- coding: UTF-8 -*-:这段注释是告诉Python解释器,按照UTF-8编码读取源代码,否则,在源代码中写的中文输出可能会有乱码

1.4 Python的底层语言是用C实现的

是用 C 语言编写实现的 Python,又称为 CPython。平时我们所讨论的 Python,指的其实就是 CPython。

随着编程语言的不断发展,Python 的实现方式也发生了变化,除了用 C 语言实现外,Python 还有其他的实现方式。例如,用 Java 语言实现的 Python 称为 JPython,用 .net 实现的 Python 称为 IronPython 等等。

Python是C语言实现的,尽管有很多标准库是由python代码实现,但是涉及到底层支撑架构的功能还是C代码。 一些IDE为了对这些进行友好代码提示,会弄和底层一样的访问接口,而其实现直接写 pass 略过


第二章.基础知识

  • python的语句不需要加;
  • 遍历慎用小写字母l和大写字母O,因为容易错看成数字1和0
  • 段注释
"""
python段注释
"""
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
name = input("请输入姓名:") # 输入提示
print(name)
# 换行输出

# 字符串用引号表示,''或""都可以表示
# print()会依次打印每个字符串,遇到逗号,会输出一个空格
print("hello world!", 'I am here.')

# 变量
# ""和''可以结合起来使用
message1 = "Happy 'New' Year"
print(message1) # 输出:Happy 'New' Year 
message2 = 'Happy "New" Year'
print(message2) # 输出:Happy "New" Year

Traceback是一条记录,之处解释器在尝试运行代码时,在什么地方遇到了困境
在这里插入图片描述
名称错误:1.变量名拼写错误 2.使用变量前忘记给它赋值

2.1 方法

方法是Python可对数据执行的操作
官方方法查询传送门

title content
title() 首字母大写
upper() 全部字母大写
lower() 全部字母小写
lstrip() 删除左端空白字符(默认空格或\n)
rstrip() 删除右端空白字符
strip() 删除两端空白字符
str() 整数转为字符串
split() 根据一个字符串创建一个单词列表 默认为所有的空字符

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
str.strip(‘u’);移去字符串首尾的u字符

示例:

# rstrip()默认可以去掉右端(空格或换行符\n),最后有空行是因为print语句会加上一个换行符
str1 = "Here:\ny ou\n \n\n\n\n"
print(str1.rstrip())

输出

Here:
y ou

# 变量
name = "ada Love you"
print(name.title())  # Ada Love You
print(name.upper())  # ADA LOVE YOU
print(name.lower())  # ada love you

t = name.upper()
print(t)  # ADA LOVE YOU


first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name

message = "Hello, " + full_name.title() + "!"
print(message)  # Hello, Ada Lovelace!

在编程中,空白泛指任何非打印字符,如空格、制表符\t和换行符\n

message = "  hello world! "
print(message.lstrip())  # 删除左端空格
print(message.rstrip())  # 删除右端空格
print(message.strip())   # 删除两端空格
age = 25
print("Happy " + str(age) + "th Birthday")

2.2 数据类型

python数据很自由,想开多大就多大

2.3 import this

Python之禅
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.

2.4 python3特殊点

  1. Python2中print有些加括号,有些不加括号,而Python3中的print是一个函数,一次括号必不可少
  2. / 和 //区别
Python2 
3 / 2 = 1
3.0 / 2 = 1.5
Python3 
3 / 2 = 1.5
3 // 2 = 1  # Python3特意用//来表示整数除法

因此Python2和Python3相互转换时,一定要注意这种异常细微

  1. Python中用**表示次幂运算
print(4 ** 3)  # 输出64 
  1. 如果你使用的是Python2.7,请使用raw_input()而不是input()来获取输入

  2. Python中是用True或False,C++中用true或false

  3. 在Python2.7中创建类有细微区别,需在括号内包含单词object

class Classname(object)	
	--snip--
  1. Python2.7中的继承
class Car(object):
	def __init__(self, make, model, year):
		--snip--

class ElectricCar(Car):
	def __init__(self, make, model, year):
		super(ElectricCar, self).__init__(make, model, year)
		--snip--

函数super()需要两个实参:子类名和对象self
另外在Python2.7使用继承时务必在定义父类时在括号内指定object

2.5 代码规范PEP8

PEP8(Python Enhancement Proposal)代码格式设置指南

命名

  • 命名尽量用下划线隔开,且要有实际意义
    如用name比n更能表示姓名这个含义
    变量:full_name
    函数:get_formatted_name

缩进

  • PEP8建议每级缩进用4个空格,tab键要设置制表符为4个空格

空行

  • 空行不会影响代码的运行,但会影响代码的可读性。
    建议不要在程序文件中过多地使用空行。
    PyCharm可以自动格式化,包括处理多余空行
    Python解释器根据水平缩进情况来解读代码,不关心垂直间距

函数

  • 描述性的函数名如print_models()让别人阅读这些代码时更清晰

  • 用了函数的好处:如果我们需要对打印代码进行修改,只需修改这些代码一次,就能影响所有调用该函数的地方,效率很高

  • 理念:每个函数都应只负责一项具体工作,这由于使用一个函数来完成两项工作

行长

  • Python程序都建议每行不超过80字符,因为专业程序员都会在同一个屏幕上打开多个文件,使用标准行长可以让他们更好的阅读代码
    大多数编辑器会设置一个视觉标志——通常是一个竖线

函数编写指南

  • 编写函数时应给函数指定描述性名称,且只在其中使用小写字母和下划线,给模块命名时也要遵循这样的约定

  • 每个函数都应包含简要地阐述其功能的注释(文档字符串),让别人相信他们可以如描述那样运行代码:只要知道函数名、需要的实参以及返回值得类型,就能在自己的程序中使用它

  • 给形参指定默认值时,等号两边不要有空格

def function_name(parameter_0, parameter_1='default value')
  • 如果函数包含多个函数,可使用两个空行将相邻的函数分开。这样将更容易知道前一个函数在什么地方结束,下一个函数从什么地方开始

  • 所有import语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序

  • 如果形参很多,导致函数定义的长度超过79字符,可在函数定义中输入左括号后按回车,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来

def function_name(
		parameter_0, parameter_1, parameter_2,
		parameter_3, parameter_4, parameter_5):
	function body...
  • 继承的一点说明:如果一个属性或方法是任何汽车都有的,而不是电动汽车特有的,就应将其加入到Car类而不是ElectricCar类中。这样,使用Car类的人可以获得相应的功能,而使用ElectricCar类只包含处理电动汽车特有的属性和行为代码

类编码风格

  • 类名应采用驼峰命名法,如ElectricCar,不能使用下划线

  • 每个类定义后面包含一个文档字符串,简要地描述类的功能

  • 同时导入标准库中的模块和自己编写的模块时,先编写导入标准库模块的import语句,再用一个空行隔开,再写导入自己的模块的import语句,这样让人更容易明白程序使用了各个模块来自何方

from collections import OrderedDict  # 标准库中模块

from car import Car  # 自己编写的模块
from electric_car import ElectricCar, Battery

第三章.列表

3.1 列表是有序集合[]

列表中可以放任何东西,其中的元素之间可以没有任何关系
给列表指定名字一般用复数,如:letters、digits、names

在Python中用方括号[]来表示列表,并用逗号分隔元素
访问最后一个列表元素可以用下标-1

bicycles = ["cannondale", '666', 23, "specialized", 'trek']
print(bicycles)  # 输出 ['cannondale', '666', 23, 'specialized', 'trek']
print(bicycles[4].title())  # 输出 Trek

# 通过索引指定为-1,可以让Python返回最后一个列表元素
# 通过索引指定为-2,可以让Python返回倒数第二个列表元素
# 因此可以在不知道列表长度的情况下访问最后的元素

print(bicycles[-1]) # 输出trek

3.2 列表的增删改查append del pop

列表是动态的,可以快速进行增删改查

append(word)
insert(index,word)

# 在列表末尾添加元素
bicycles.append("wilson")
print(bicycles)  # ['cannondale', '666', 23, 'specialized', 'trek', 'wilson']
# 在列表中插入元素
bicycles.insert(1, "here")  # 在下标为1的位置插入"here"(变成第二个元素,其余元素后移)
print(bicycles)  # ['cannondale', 'here', '666', 23, 'specialized', 'trek', 'wilson']

我们常需要从列表中删除元素,例如,玩家将空中的一个外星人射杀后,你需要将其从存活的外星人列表中删除

使用del删除元素

使用pop()删除元素
方法pop()可以删除列表末尾的元素,并让你能够接着使用它

arrays = ["Lebron", "Durant", "Kobe","Davis"]
del arrays[1] # 删除"Durant"

great = arrays.pop() # 删除"Davis",并把Davis赋给great
print(arrays) # ['Lebron', 'Kobe']
print(great) # Davis

使用pop(index)删除指定元素

players = ["Lebron", "Durant", "Kobe","Davis"]
players.pop(2) # 弹出索引为2的元素
print(players) # ['Lebron', 'Durant', 'Davis']

remove根据值删除元素

players = ["Lebron", "Durant", "Kobe","Davis"]
players.remove("Kobe") # 有时不知道列表中删除的值所处的位置,可用remove方法
sd = ["d"]
sd = players # 列表可以直接赋给另个列表
print(sd) # ['Lebron', 'Durant', 'Davis']

注意:remove只删除第一个指定的值

用while可以删除包含指定值的所有列表元素

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

输出

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

3.3 排序list.sort()和sorted(list)

sort()和sort(reverse=True) 永久性修改列表

pt = ["faith", "Computer", "79", "share"]
pt.sort() # 按字符从小到大排序
print(pt) # ['79', 'Computer', 'faith', 'share']
pt.sort(reverse=True) # 按字符从大到小排序
print(pt) # ['share', 'faith', 'Computer', '79']

sorted(list) 暂时性修改列表

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars)) # ['audi', 'bmw', 'subaru', 'toyota']
print(cars) # ['bmw', 'audi', 'toyota', 'subaru']

list.reverse() 反转列表

len(list) 确定列表的长度
用途:确定还有多少个外星人未被射杀,需要管理多少项可视化数据,网站有多少注册用户

注意:发生索引错误(下标越界)却找不到解决方法时,可以尝试将列表或其长度打印出来

3.4 列表非空时执行

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if requested_toppings:  # 列表非空时执行
...

第四章.操作列表

4.1 for循环

for循环要加冒号和注意缩进

使用单数和复数式名称,可以帮助判断代码段处理的是单个列表元素还是整个列表

for car in cats:
for item in list_of_items:

magicians = ['alice', 'david', 'carolina']
for magician in magicians:  # 每个缩进的代码行都是for循环的一部分
    print(magician.title() + 'Alice, that was great trick!')
    print("I can't wait to see your next trick, " + magician.title() + ".\n")

4.2 避免缩进错误

Python根据缩进来判断代码行与前一个代码行的关系
对于for语句后面且属于循环组成部分的代码行,一定要缩进

如果你预期某项操作将针对每个列表元素都执行一次,但它却只执行了一次,请确定是否需要将一行或多行代码缩进

下面示例中print无效缩进,因为它不属于前一行代码

message = "Hello Python World"
    print(message) # unexpected indent

为避免意外缩进错误,请只缩进需要缩进的代码

4.3 数字列表range(start, end, gap)

使用range()函数

range(start,end) # 左闭右开
range(end) = range(0,end) # 默认从0开始
range(start,end, gap)

for value in range(2, 7):
    print(value)  # 输出2-6

for va in range(3):
    print(va)  # 输出0-2

# 可以使用list()将range()的结果直接转换为列表
even_numbers = list(range(2, 11, 2))
print(even_numbers)  # 输出[2, 4, 6, 8, 10]

创建一个列表,1-10的平方

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(list)
max(list)
sum(list)

digits = [1, 2, 3, 4, 5]
print(max(digits))  # 5
print(min(digits))  # 1
print(sum(digits))  # 15

列表解析

列表解析是将for循环和创建新元素的代码合并成一行

# 列表解析
Ones = [val for val in range(5)]
print(Ones)    # [0, 1, 2, 3, 4]
Threes = [value ** 3 for value in range(1, 11)]
print(Threes)  # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

4.4 切片list[start: end: gap] 列表/字符串

players[start:end:gap] 左闭右开

players = ['Lebron', 'Irving', 'Love', 'JR', 'Thompson']
print(players[1:5])  # 输出下标1-2的元素
print(players[1:5:3])  # 输出下标1, 4的元素
print(players[:4])  # 输出下标0-3的元素
print(players[1:])  # 没有结束索引时,自动终止于列表末尾
# ['Irving', 'Love', 'JR', 'Thompson']
# ['Irving', 'Thompson']
# ['Lebron', 'Irving', 'Love', 'JR']
# ['Irving', 'Love', 'JR', 'Thompson']

输出最后三个元素

players = ['Lebron', 'Irving', 'Love', 'JR', 'Thompson']
print(players[-3:]) # 输出最后三个元素

遍历切片

players = ['Lebron', 'Irving', 'Love', 'JR', 'Thompson']
for player in players[1:4]: # 遍历下标为1-3的元素
    print(player)

用途:排序后,获取某个玩家的三个最高得分;编写Web应用程序时,可使用切片来分页显示信息,并在每页显示数量合适的信息

字符串也有切片

filename = 'text_files/pi_million_digits.txt'

with open(filename) as file_object:
    pi_million = ""
    for line in file_object:
        pi_million += line.strip()  # 删除两端空格或\n

    print(pi_million[0:12])  # 输出字符串前12个字符

4.4.1 直接用列表赋值(指向)

相当于C++引用,把stars指向了players

players = ['Lebron', 'Irving', 'Love', 'JR', 'Thompson']
stars = players
players.append('Durant')
stars.append('Curry')
print(players)
print(stars) # 输出结果相同

4.4.2 用切片[:]赋值列表

切片表示法[:]创建列表副本

得到的两个不同的列表,相当于生成一个副本

players = ['Lebron', 'Irving', 'Love', 'JR', 'Thompson']
stars = players[:]
players.append('Durant')
stars.append('Curry')
print(players)  # ['Lebron', 'Irving', 'Love', 'JR', 'Thompson', 'Durant']
print(stars)  # ['Lebron', 'Irving', 'Love', 'JR', 'Thompson', 'Curry']

4.5 元组()

有时需要创建一系列不可修改的元素,元组(tuple)就可以满足这种需求

元组类似列表,但是使用圆括号而不是方括号来标识

不能修改元组中的元素,但能修改元组变量

# 元组
dimensions = (10, 15, 13)
print(dimensions)  # 输出 (10, 15, 13)
# dimensions[0] = 20    # 错误,不能修改元组中的元素
dimensions = (11, '2')  # 修改元组变量是可以的
print(dimensions)  # 输出 (11, '2')

下面的例子,表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变

tuple = (1, 2, [3, 4])
tuple[2][0] = 5
print(tuple)  # (1, 2, [5, 4])

在这里插入图片描述


第五章.if语句

if, else类似for循环,后面都要加上:

5.1 and or 逻辑运算符

car = "BMW"
print(car == "bmw") # 输出 False
print(car.lower() == "bmw") # 输出 True

if car == "1":
    print("Yes")
else:
    print("No")

age_0 = 22
age_1 = 18
if age_0 > 21 and age_1 > 21:
    print("Both > 21")
else:
    print("Someone <= 21")

if (age_0 > 21) or (age_1 > 21): # 可以加括号增强可读性
    print("Someone > 21")
else:
    print("Both <= 21")

5.2 in 检查特定值是否在列表中

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings) # 输出 True

同理用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")
# 输出 Marie, you can post a response if you wish

用途:在地图程序中,可能需要检查用户提交的位置是否包含在已知位置列表中;结束用户的注册过程前,可能需要检查他提供的用户名是否已包含在用户名列表中,而且通常会先把用户名转为全部小写后再去比较

5.3 if-elif-else结构

Python是if-elif-else结构 后面加:

C++是if-else if-else结构 后面加{}

digit = 12
if digit < 4:
    print("Your admission cost is $0.")
elif digit < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")

else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,所以如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。这样可以肯定,仅当满足相应的条件时,你的代码才会执行

示例

# 披萨店点披萨
# requested_toppings = []
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if requested_toppings:  # 列表非空时执行
    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!")
else:
    print("Are you sure you want a plain pizza?")

输出

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!


第六章.字典

6.1 使用字典{ : , : }

使用字典可以让我们高校地模拟现实世界中的情形,如创建一个表示人的字典,然后可以存储信息:姓名、年龄、地址、职业以及要描述的任何方面

在Python中字典是一系列键-值对(类似C++中的map),任何python对象都可以作为字典中的值

访问字典中的值:指定字典名和放在方括号内的键

# 使用字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['points']) # 输出5

添加键-值对
字典是一种动态结构,可随时在其中添加键-值对
Python不关心键-值对的添加顺序,而只关心键和值之间的关联关系

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['points']) # 输出5

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0) # 输出 {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

6.2 删除键-值对del

使用del时,需要指定字典名和要删除的键

alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
print(alien_0)  # 输出 {'color': 'green'}

6.3 由类似对象组成的字典

# 由类似对象组成的字典
favorite_languages = {
    'jeny': 'Python',
    'sarah': 'c',
    'wilson': 'c++'
}
# 较长的print语句可分成多行
print("Wilson's favorite language is " +
      favorite_languages['wilson'].title()
      + ".")
# 输出 Wilson's favorite language is C++.

6.4 遍历字典 items()

Python遍历字典中的每个键-值对,并将键存在变量name中,将值存在变量language中

items()返回一个键-值对列表

# 遍历字典
favorite_languages = {
    'kevin': 'java',
    'jeny': 'python',
    'sarah': 'c',
    'wilson': 'c++',
}

for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " 
    + language.title() + ".")

6.4.1 遍历字典中所有的键 keys()或缺省

遍历字典时会默认遍历所有的键,所以把下面的for name in favorite_languages.keys():改成for name in favorite_languages:效果是一样的

favorite_languages = {
    'kevin': 'Java',
    'jeny': 'Python',
    'sarah': 'c',
    'wilson': 'c++',
}

for name in favorite_languages.keys():
    print(name.title())

方法keys()会返回dict_keys([ ])列表

print(favorite_languages.keys())  
# 输出 dict_keys(['kevin', 'jeny', 'sarah', 'wilson'])

6.4.2 按顺序遍历字典中的所有键sorted()

用方法sorted()

favorite_languages = {
   'kevin': 'Java',
   'jeny': 'Python',
   'sarah': 'c',
   'wilson': 'c++',
}

for name in sorted(favorite_languages.keys()):
   print(name.title()) 

输出

Jeny
Kevin
Sarah
Wilson

6.4.3 遍历字典中的所有值values()

favorite_languages = {
    'kevin': 'java',
    'jeny': 'python',
    'sarah': 'c',
    'wilson': 'c',
}

for language in favorite_languages.values(): # value可能重复
    print(language.title())

print("\nUsing set to remove duplicate values")
# 用set去重
for language in set(favorite_languages.values()): 
    print(language.title())

6.5 set用法{ }

set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

set是无序无重复元素集合

要创建一个set,需要提供一个list作为输入集合:

set用add()和remove()方法增删元素

# set用法
arr = [1, 2, 2, 3, 3]
print(set(arr))  # 输出 {1, 2, 3}
b = set([1, 2, 2])
print(b)  # 输出 {1, 2}

b.add(7)
print(b)  # 输出 {1, 2, 7}
b.remove(7)
print(b)  # 输出 {1, 2}

把set转为list的方法

b = set([1, 2, 2])
print(b)  # 输出 {1, 2}
tt = list(b)
print(tt)  # 输出 [1, 2]

6.6 嵌套

有时我们需要将一系列字典存储在列表中,或者将列表作为值存储在字典中,这些都成为嵌套

如字典alien_0包含一个外星人的各种信息,但无法同时存储外星人的信息。此时我们可以创建一个外星人列表

# 创建一个用于存储外星人的空列表
aliens = []

# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if (alien['color'] == 'green'):
        alien['color'] = 'red'
        alien['points'] = 15
        alien['speed'] = 'fast'

for alien in aliens[0:5]:
    print(alien)

print("...")

输出

{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...

我们经常需要再列表中包含大量的字典,比如做网站时,需要给每个用户创建一个字典,并将这些字典存储在一个名为users的列表中


第七章.用户输入和while循环

7.1 函数input()获取字符串输入

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用

函数input()接受一个参数:即要想用户显示的提示或说明
相当于内置了一行print()但是不自动换行

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print("\nHello, " + name.title() + "!")

输出

If you tell us who you are, we can personalize the messages you see.
What is your first name? wilson79

Hello, Wilson79!

注意:如果你使用的是Python2.7,请使用raw_input()而不是input()来获取输入

7.2 函数int() 字符串转为数值

函数input()将用户输入解读为字符串
函数int()将数字字符串转为数值

age = input("How old are you? ")
age = int(age) # '22' to 22

函数float()将字符串转为浮点数

time = '2.3'
time = float(time)

7.3 while循环

你每天使用的程序很可能就包含while循环,比如游戏使用while循环,确保玩家在想玩的时候不断运行,并在玩家想退出时停止运行;终端按control+c终止运行

示例:让用户选择何时退出

# while循环
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
    message = input(prompt)
    if (message != 'quit'):
        print(message)

7.3.1 使用标志

在游戏中,多种事件都可能导致游戏结束,如玩家一艘飞船都没有了或要保护的城市都被摧毁了。
在要求很多的条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活跃状态。这个变量成为标志
用True或False去表示状态的更改

7.3.2 break和continue

用法和C++类似

while循环要确保程序中至少有一个这样的地方能让循环条件为False或break

sublime text把内容输出到out.txt时,如果是死循环,会导致当前的txt会非常大,占用很大的内存,所以要及时终止程序

7.3.3 使用用户输入填充字典

创建一个调查报告,其中的循环每次执行时提示输入被调查者的名字和回答

# 使用用户输入来填充字典
responses = {}

# 设置一个标志,判断调查是否继续
polling_active = True

while polling_active:
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    # 将答案存到字典中
    responses[name] = response

    # 看看是否还有人要接受调查
    repeat = input("Would you like to let another person respond? (yes / no) ")
    if (repeat == 'no'):
        break

print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name.title() + " would like to climb " + response.title() + ".")

输出


What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes / no) yes

What is your name? Lynn
Which mountain would you like to climb someday? evil's thumbd
Would you like to let another person respond? (yes / no) no

--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Evil'S Thumbd.

【啃书系列】Python编程从入门到实践 下

发布了182 篇原创文章 · 获赞 71 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104012949