Python编程入门(一)

Python编程入门(一)

2变量和简单数据类型

查询Python版本

import sys
print(sys.version)

2.2变量名的命名和使用

使用小写的Python变量名
当程序无法成功运行的时候,Python解释器会提供一个traceback,即显示错误的记录

2.3字符串

单引号双引号都可以
单引号中不能再次包括撇号

message = "One of Python's strengths is its diverse community"
print(message)
message2 = 'I tode my friend,"python is the best language"'
print(message2)

title():以首字母大写的方式显示每一个单词
将Ada、ADA、ada视为同一个名字,并将他们都显示为Ada

name = "this is a test"
print(name.title())

将字符串全都改成大写或小写
用户提供的字符串无法判断大写小写的时候,可以全都存储为小写,后续再进行操作

name = "This Is A Test"
print(name.upper())
print(name.lower())

合并字符串,用加号(+)

first_name = "harry"
last_name = "potter"
full_name = first_name + " " + last_name
message = "hello," + full_name.title() + "!"
print(message)

删除空白
删除字符串末尾的空白:rstrip(),调用后仅为暂时删除末尾多余的空格,永久删除需要将操作的接过存回原变量
删除字符串开头的空白:lstrip()
同时删除字符串两端的空白:strip()
这些剥除函数最常用于在存储用户输入前对其进行清理

>>>name = 'Harry   '
>>>name
'Harry   '
>>>name.rstrip()
'Harry'
>>>name = name.rstrip()
>>>name
'Harry'

2.4数字

对于整数可以执行加(+)减(-)乘(*)除(/)运算,使用两个乘号(**)表示乘方运算
可以使用括号修改优先级,空格不影响Python计算的表达方式,旨在阅读代码

>>>2 ** 3
8

浮点数:带小数点的数字都是浮点数

str():将非字符串值表示为字符串

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

3列表简介

3.1列表

列表:是由一系列按特定顺序排列的元素组成
鉴于列表通常包含多个元素,可以给列表指定一个表示复数的名称(如letters、digits、names)
在python中,用方括号([])来表示列表,用逗号(,)来分隔其中元素
如果直接打印列表,Python将列表的内部表示,即包括[]和,

列表是有序集合,因此要访问列表的任何元素,只需指出列表的名称和元素的索引,可使用title()方法使元素更整洁
索引是从0开始的,Python中将索引指为-1,可以返回列表最后一个元素,-2返回倒数第二个元素,以此类推,仅当列表为空的时候这种访问最后一个元素的方式才会出错

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
print(bicycles[-1].title())

3.2修改、添加和删除元素

创建的大多数列表是动态的
通过指定列表名和要修改元素的索引,来修改列表中的元素

motorcycle = ['honda', 'yamaha', 'suzuki']
motorcycle[0] = 'ducati'
print(motorcycle)

在列表中添加元素
在列表末尾添加元素,方法append(),可以在建空列表后用一系列的append()语句添加元素

motorcycle = ['honda', 'yamaha', 'suzuki']
motorcycle.append('ducato')
print(motorcycle)

在列表中插入元素
使用insert()可在列表的任何位置添加新元素,需要指定新元素的索引和值

motorcycle = ['honda', 'yamaha', 'suzuki']
motorcycle.insert(0, 'ducati')
print(motorcycle)

在列表中删除元素
使用del语句,可以删除任何位置的列表元素,条件是知道其索引

motorcycle = ['honda', 'yamaha', 'suzuki']
del motorcycle[0]
print(motorcycle)

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

motorcycle = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycle.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")

弹出列表中任何位置处的元素,可以使用pop()来删除列表中任何位置的元素的索引即可
使用pop()时,被弹出的元素就不再列表中了
如果要从列表中删除一个元素,且不在以任何方式使用它,就使用del语句;如果要在删除元素后还能继续使用他,就使用方法pop()

motorcycle = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycle.pop(1)
print("The last motorcycle I owned was a " + first_owned.title() + ".")

根据值删除元素
使用remove():如果不知道从列表中删除的值所处的位置,只知道要删除的元素的值
只删除第一个指定的值,如果要删除的值可能在列表中出现多次,需要使用循环来判断是否删除了所有这样的值

motorcycle = ['honda', 'yamaha', 'suzuki', 'ducati']
motorcycle.remove('ducati')
print(motorcycle)
motorcycle = ['honda', 'yamaha', 'suzuki', 'ducati']
too_expensive = 'ducati'
motorcycle.remove(too_expensive)
print(motorcycle)
print("\nA " + too_expensive.title() + " is too expensive for me.")
names = ['James', 'Peter', 'Amy']
print("dear " + names[0] + "、 " + names[1] + "、 " + names[2] + " shall we have dinner together?")

print("It's a pity that " + names[2] + " couldn't make the appointment.")
names[2] = 'Tom'
print("dear " + names[0] + "、 " + names[1] + "、 " + names[2] + " shall we have dinner together?")

print("I find a bigger dinner table")

names.insert(0, 'Bob')
names.insert(2, 'Lily')
names.append('Ron')
print("dear " + names[0] + "、 " + names[1] + "、 " + names[2] + "、 " + names[3] + "、 " + names[4] + "、 " + names[5] + "shall we have dinner together?")
print("I can only invite two guests to dinner")

person = names.pop()
print("I'm sorry " + person + ", we can't have dinner together")

person = names.pop()
print("I'm sorry " + person + ", we can't have dinner together")

person = names.pop()
print("I'm sorry " + person + ", we can't have dinner together")

person = names.pop()
print("I'm sorry " + person + ", we can't have dinner together")

print("Dear " + names[0] + ", I sincerely invite you to have dinner with me")
print("Dear " + names[1] + ", I sincerely invite you to have dinner with me")

del names[0]
del names[0]
print(names)

3.3组织列表

使用方法sort()对列表进行永久性排序,再也无法恢复到原来的排列顺序

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

按与字母顺序相反的顺序,向sort()方法传递参数reverse=True

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)

使用sorted()对列表进行临时排序
能够按照特定顺序显示列表元素,同时不影响他们在列表中的原始排列顺序
如果要显示与字母顺序相反,同样向sorted()方法传递参数reverse=True
在并非所有值都是小写时,按照字母顺序排列列表会变得复杂

cars = ['bmw', 'audi', 'toyota', 'subaru']
print("here is a original list:")
print(cars)
print("\nhere is a sorted list:")
print(sorted(cars))
print("\nhere is the original list again:")
print(cars)
laces = ['France', 'America', 'Italy', 'Germany', 'Egypt']
print(sorted(places, reverse=True))

倒着打印列表
要反转列表元素的排序顺序,可以使用方法reverse()
reverse()不是指按与字母顺序相反的顺序排列列表元素,而是反转列表元素的排列顺序
方法reverse()永久性的修改列表元素的排列顺序,但可以随时恢复到原来的排列顺序,只需要再一次调用reverse()

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars)

确定列表的长度
使用len()可以获得列表的长度
Python计算列表长度时从1开始

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

4操作列表

4.1遍历整个列表

循环这种概念很重要,他是让计算机自动完成重复工作的常见方法之一
编写for循环时,对于用于存储列表中每个值的临时变量,可以指定任何名称。选择描述单个列表元素的有意义的名称更有帮助。使用单数和复数式名称有助于判断代码段处理的是单个列表元素还是整个列表

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician.title() + ", that was a great trick! ")

4.2缩进

Python根据缩进来判断代码与前一个代码行的关系

4.3创建数字列表

列表非常适合用于存储数字集合,数据可视化
range()函数能够轻松的生成一些列的数字,让Python从你指定的第一个值开始数,并在达到你指定的第二个值后停止,因此输出不包含第二个值

for value in range(1,5):
    print(value )

要创建数字列表,可使用list()将range()的结果直接转换为列表

numbers = list(range(1, 6))
print(numbers)

使用range()函数时,可以指定步长
这个实例中,函数range()从2开始,然后不断地加2,知道达到或超出终值11

even_numbers = list(range(2, 11, 2))
print(even_numbers)
squares = []
for value in range(1, 11):
    squares.append(value ** 2)
print(squares)

对数字列表执行简单的统计计算
有几个专门用于处理数字列表的Python函数,如最大值、最小值、总和

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))

列表解析
列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素
首先指定一个描述性的列表名(square),然后指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值(value**2),接下来编写一个for循环,用于给表达式提供值(for value in range(1, 11),且这里的for循环没有冒号,再加上右方括号

square = [value**2 for value in range(1, 11)]
print(square)

4.4使用列表的一部分

切片,要创建切片可以指定要使用的第一个元素的索引和最后一个元素的索引加1.与函数range()一样,Python在到达指定的第二个索引前面的元素后停止

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])

如果没有指定起始索引,Python从列表头开始提取,也可以使用类似的方法让切片终止与列表尾
无论列表多长,都可以输出凶特定位置到列表末尾的所有元素

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:3])
print(players[2:])

负数索引返回离列表末尾相应距离的元素,因此可以输出列表末尾的任何切片

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])

遍历切片
处理数据时可以用切片进行批量处理,编写Web应用程序时可以用切片来分页显示信息

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_food = ['pizza', 'falafel', 'carrot cake']
friend_food = my_food[:]
my_food.append('cannoli')
friend_food.append('ice cream')
print("My favorite foods are:")
print(my_food)
print("\nMy friend favorite food are:")
print(friend_food)

4.5元组

列表非常适合用于存储在程序运行期间可能变化的数据集,列表是可以修改的
Python将不能修改的值成为不可变的,而不可变的列表被称为元组

定义元组
元组使用圆括号来标识,定义元组后就可以使用索引来访问其元素

dimensions = (200, 50)
print(dimensions[0])

遍历元组中的所有值
像列表一样,可以使用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)

4.6设置代码格式

每次缩进都使用了四个空格,行长不超过80个字符,注释的行长不超过72个字符
空行不会影响代码的运行,只有关可读性

5 if语句

5.2条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式被成为条件测试

检查是否相等:一个等号是陈述,两个等号是发问(==)
检查是否相等时区分大小写,Python区分大小写

检查是否不相等使用(!= )

比较数字,可以比较相等、不相等、大于、小于、大于等于等等

检查多个条件使用关键词and或者or

age_0 = 22
age_1 = 18
print(age_0 >=21 and age_1 >= 21)
print((age_0 >= 21) and (age_1 >= 16))
age_0 = 22
age_1 = 18
print(age_0 >=23 or age_1 >= 21)
print((age_0 >= 21) or (age_1 >= 23))

检查特定值是否包含在列表中
使用关键词 in

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)

检查特定值是否不包含在列表中
使用关键词 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.")

布尔表达式
在跟踪程序状态或者程序中重要的条件方面,布尔表达式提供了一种高效的方式

5.3 if语句

if-else 语句

age = 17
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry,you are too young to vote.")
    print("Please register to vote as soon as tou turn 18!")

if-elif-else 结构

age = 17
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5
print("Your admission is $" + str(price) + ".")

省略else代码块
Python并不要求 id-elif 结构后面必须有 else 代码块
如果知道最终要测试的条件,应考虑用一个 elif 代码块来代替 else 代码块,这样可以肯定,仅当满足相应条件时代码才会执行

age = 17
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
elif age >= 65:
    price = 5

如果只想执行一个代码块,就是用 if-elif-else 结构;如果要运行多个代码块,就是用一系列独立的 if 语句

5.4 使用 if 语句处理列表

对列表中特定的值做处理,高效的管理不断变化的情形
检查特殊元素

requested_toppings = ['mushrooms', 'onions', 'pineapple', 'green peppers']
for requested_topping in requested_toppings:
    if requested_topping.lower() == 'green peppers':
        print("Sorry,we are out of green peppers right now.")
    else:
        print("Adding " + requested_topping + '.')
print("Finished making your pizza.")

确定列表不是空的
在运行 for 循环前确定列表是否为空很重要,在 if 语句中将列表名用在条件表达式中,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + '.')
    print("Finished 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 dont have " + requested_topping + ".")
print("Finished making your pizza!")

6 字典

字典课存储的信息量几乎不受限制

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

6.2 使用字典

在Python中,字典是一系列 键-值 对,每个键都与一个值相关联,可以使用键来访问与之相应的值,与键相关联的值可能是数字、字符串、列表、字典,即任何Python的作用对象
在Python中,字典用放在花括号中的一些列键-值对表示
键-值对实两个相关联的值。指定键时Python将返回与之相关联的值,键和值之间用冒号分隔,键-值对之间用逗号分隔,在字典中想存储多少个键-值对都可以
访问字典中的值
要获取与键相关的值,可依次指定字典名和放在方括号内的键

alien_0 = {'color': 'green', 'points': 5}
new_point = alien_0['points']
print("You just earned " + str(new_point) + " points!")

添加键-值对
字典是一种动态结构,可随时在其中添加键-值对,依次指定字典名、用方括号括起的键和相关联的值
Python不关心键-值的排列顺序,只关系键和值之间的关系

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

修改字典中的值
可依次指定字典名、键、与该键相关联的新值

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is " + alien_0['color'] + ".")
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))
if alien_0['speed'].lower() == 'slow':
    x_increment = 1
elif alien_0['speed'].lower() == 'medium':
    x_increment = 2
else:
    x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))

删除键-对值
对于字典中不再需要的信息,使用 del 语句将相应的键-值对删除,使用 del 语句时必须指定字典名和要删除的键
删除的键-值对永远消失

alien_0 = {'color': 'green', 'position': 5}
print(alien_0)
del alien_0['position']
print(alien_0)

由类似对象组成的字典
使用字典存储众多对象的同一种信息
将比较大的字典放在多行中,不错的做法是在最后一个键-值对后面也加上逗号,为以后在下一行添加键-值对做好准备

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")

6.3 遍历字典

遍历所有键-值对
遍历字典时,键-值对的返回顺序也与存储顺序不同,Python不关心键-值对的存储顺序

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}
for k, v in user_0.items():
    print("\nKey: " + k)
    print("Value: " + v)
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + language.title() + ".")

遍历字典中所有键
在不需要使用字典中的值时,方法 key() 很有用
遍历字典时会默认遍历所有的键,for name in favorite_languages.keys(): 与 for name in favorite_language: 是一样的,即key()可以省略

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
    print(name.title())
    if name in friends:
        print(" Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")

方法 key() 并非只能用于遍历,它返回一个列表

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
if 'erin' not in favorite_languages.keys():
    print("Erin, please take our poll!")

按顺序遍历字典中的所有键
要以特定的顺序返回元素,一种办法是在 for 循环中对返回值进行排序,可使用函数 sorted() 来获得按特定顺序排列的键列表的副本

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
    print(name.title() + ",thank you for taking the poll.")

遍历字典中的所有值
使用 value() 方法,它返回一个值列表而不包含任何键
为剔除重复项,可使用集合(set),集合类似于列表,但是每个元素都必须是独一无二的

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

6.4 嵌套

将一些列字典值存放在列表中,或者将列表作为值存放在字典中
字典列表

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)
aliens = []
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)
for alien in aliens[:3]:
    print(alien)
print("...")
print("Total number if aliens:" + str(len(aliens)))
aliens = []
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'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15
for alien in aliens[:5]:
    print(alien)
print("...")

在字典中存储列表
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表
在遍历字典的 for 循环中,我们需要再使用一个 for 循环来遍历相关联的列表

pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese']
}
print("Your ordered a " + pizza['crust'] + "-crust pizza with the following toppings:")
for topping in pizza['toppings']:
    print("\t" + topping)
favorite_language = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
}
for name, languages in favorite_language.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())

在字典中存储字典
可以在字典中嵌套字典
依次将每个键存储在变量 username 中,并依次将与当前键关联的字典存储在变量 user_info 中

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris'
    },
}
for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    loaction = user_info['location']
    print("\t full name: " + full_name.title())
    print("\t location: " + loaction.title())

7 用户输入和 while 循环

7.1 函数 input() 的工作原理

函数 input() 让程序暂停运行,等待用户输入一些文本,获取输入后Python将其存储到一个变量中,以方便使用
每当使用函数 input() 时,应指定清晰而易于明白的提示,通过在提示末尾包含一个空格,可将提示与用户输入分隔开
当提示超过一行的时候,课将提示存储到一个变量中,再将这个变量传递给函数 input()

message = input("Tell me something, and I will repeat it back to you: ")
print(message)
#Tell me something, and I will repeat it back to you: Hello everyone!
#Hello everyone!

prompt = "If you tell us who you are, we can personaliza the message you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")

使用 int() 来获取数值输入
使用函数 input() 会将用户输入解读为字符串,函数 int() 让Python将输入值视为数值

height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
    print("\nYou're tall enough to ride.")
else:
    print("\nYou'll be able to ride when you're a little older.")

求模运算符
求模运算符(%),将两个数相除并返回余数

number = input("Enter a number, and I'll tell you id it's ever or odd: ")
number = int(number)


if number % 2 == 0:
    print("The number " + str(number) + " is even.")
else:
    print("The number " + str(number) + " is odd.")

7.2 while 循环

for 循环针对于集合中的每个元素的一个代码块,而 while 循环不断的运行,直到指定的条件不满足

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
promot = "\nTell me something, and I will repeat it back to you:"
promot += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
    message = input(promot)
    if message != 'quit':
        print(message)

使用标志
导致程序结束的事件有很多时,使用 while 很难检测
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志
可以让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行
在 while 中只需要检查标志的当前值是否为 True ,并将所有测试放在其他地方

promot = "\nTell me something, and I will repeat it back to you:"
promot += "\nEnter 'quit' to end the program. "
active = True
while active:
    message = input(promot)
    if message == 'quit':
        active = False
    else:
        print(message)

使用 break 退出循环
要立即退出 while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,使用 break 语句
break 语句用于控制程序流程,在任何Python循环中都可以使用 break 语句
以 while True 打头的循环将不断运行,知道遇到 break 语句位置

promot = "\nPlease enter your name of city you have visited:"
promot += "\n(Enter 'quit' when you are finished.)"
while True:
    city = input(promot)
    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + ".")

在循环中使用 continue
要返回循环开头,并根据条件测试结果决定是否继续执行循环,continue 语句不像 break 语句那样不再执行行余下的代码并退出整个循环

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

避免无限循环
每个 while 循环都必须有停止运行的途径,按Ctrl+C

7.3 使用 while 循环来处理列表和字典

for 循环是一种遍历列表的有效方式,但是在 for 循环中不应该修改列表,否则将导致Python难以跟踪其中的元素
要在遍历列表的同时对其修改,可以使用 while 循环
在列表之间移动元素

unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

删除包含特定值的所有列表元素
不断运行 while 循环,直到列表中所有该值全都被删除

pets = ['dog', 'cta', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

使用用户输入来填充字典
使用 while 循环提示用户输入任意数量的信息

responses = {}
polling_active = True
while polling_active:
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb somebody? ")
    responses[name] = response
    repeat = input("Would you like to let another person respond?(yes/no) ")
    if repeat == 'no':
        polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + " would like to climb " + response + ".")

8 函数

函数时带名字的代码块,用于完成具体工作,要执行函数定义的特定任务可调用该函数

8.1 定义函数

使用关键字 def 来告诉Python你要定义一个函数,这是函数定义,向Python指出了函数名,还可能在括号内指出函数为完成其任务需要什么样的信息
文档字符串的注释描述了函数是做什么的,文档字符串用三引号括起,Python使用他们来生成有关程序中函数的文档
要调用函数,可依次指定函数名以及用括号括起的必要信息

def greet_user():
    """显示简单的问候语"""
    print("Hello!")
greet_user()

向函数传递信息

def greet_user(username):
    """显示简单的问候语"""
    print("Hello " + username.title() + "!")
greet_user('jesse')

实参和形参
在函数 greet_user 中,变量username是一个形参——函数完成其工作所需额一项信息
在代码 greet_user(‘jesse’) 中,值 ‘jesse’ 是一个实参,实参是调用函数时传递给函数的信息

8.2 传递实参

鉴于函数定义中可能包含多个形参,因此函数调用汇总也可能包含多个实参,向函数传递实参的方式很多,可使用位置实参,值要求是从哪的顺序与形参的顺序相同;也可以使用关键字实参,其中每个实参都有变量名和值组成;还可以使用列表和字典
位置实参
调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此最简单的关联方式就是基于实参的顺序,即位置实参
调用函数多次,可以根据需要调用函数任意次

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry') 
describe_pet('dog', 'willie')

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

def describe_pet(animal_type, pet_name):
    """显示宠物的信息""" 
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='willie', animal_type='dog')

默认值
编写函数时,可给每个形参指定默认值,在调用函数中给形参提供了实参时,Python将使用指定的实参值,否则将使用形参的默认值
使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参

def describe_pet(pet_name, animal_type='dog'):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')

在这个函数的定义中,修改了形参的排列吮吸,由于给 animal_type 指定了默认值,无需通过实参来指定动物类型,因此在函数调用中只包含一个实参——宠物的名字
然而Python依然将这个实参视为位置实参,因此如果函数调用中只包含宠物的名字,这个实参将关联到函数定义中的第一个形参,所以需要将 pet_name 放在形参列表开头

等效的函数调用
鉴于可混合使用位置实参、关键字实参和默认值,通常有很多等效的函数调用方式

def describe_pet(pet_name, animal_type='dog'):
#一条名为Willie的小狗
describe_pet('willie')
describe_pet(pet_name='willie')
#一只名为Harry的仓鼠
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

避免实参错误
你提供的实参多于或少御函数完成其工作所需要的信息时,会出现实参不匹配的错误

8.3 返回值

函数并非总是直接显示输出,可以处理一些数据返回一个或一个组值
使用 return 语句将值返回到调用函数的代码行
调用返回值的函数时,需要提供一个变量,用于存储返回的值

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

让实参变成可选的
将实参变成可选的,这样使用函数的人就只需在必要时才提供额外的信息,可使用默认值让实参变成可选的

def get_formatted_name(first_name, last_name, middle_name=''):
    """返回整洁的姓名"""
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)

给形参 middle_name 指定一个默认值——空字符串,并在用户没有提供中间名时不使用这个形参

返回字典
函数可以返回任何类型的值,包括列表和字典等较为复杂的数据结构

def build_person(first_name, last_name, age=''):
    """返回一个字典,其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)

综合使用函数和 while 循环

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()
while True:
    print("\nPlease tell me your name:")
    print("(Enter 'q' at any time to quit)")
    f_name = input("First name: ")
    if f_name == 'q':
        break
    l_name = input("Last name: ")
    if l_name == 'q':
        break
    formatter_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatter_name.title() + "!")

8.4 传递列表

将列表传递给函数后,函数就能直接访问其内容

def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

在函数中修改列表
在函数中对这个列表所做的任何修改都是永久性的

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
    current_design = unprinted_designs.pop()
    print("Printing model: " + current_design)
    completed_models.append(current_design)
print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

重组代码后:每个函数应只负责一项具体的任务

def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计,知道没有未打印的设计位置
    打印每个设计后,都将其移动到列表completed_model中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

禁止函数修改列表
可向函数传递列表的副本而不是原件,但除非有充分的理由须有传递副本,否则还是应该将原始列表传递给函数
切片表示法 [:] 创建列表的副本

funcation_name(list_name[:])

8.5 传递任意数量的实参

预先不知道函数需要接受多少个实参,Python允许函数从调用语句中收集任意数量的实参
形参名 *toppings 中的星号让Python创建一个名为 toppings 的控元组,并将收集到的所有值都封装到这个元组中

def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print(topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后

def make_pizza(size, *toppings):
    """概述要制作披萨"""
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

使用任意数量的关键字实参
有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息,可将函数编写成能够接受任意数量的键-值对——调用语句提供了多少就接受多少

def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics')
print(user_profile)

形参 **user_info 中的两个星号让Python创建一个名为 user_info 的空字典,并将收到的所有名称-值对都封装到这个字典,在这个字典中可以像访问其他字典一样访问 user_info 中的名称-值对

8.6 将函数存储在模块中

函数的优点之一,使用他们可以将代码块与主程序分离,通过给函数指定描述性名称,可让主程序容易理解的多
还可以更进一步,将函数存储在被称为模块的独立文件中,再将模块导入到主程序中
import 语句允许在当前运行的程序文件中使用模块中的代码
通过将函数存储到独立的文件中,可隐藏程序中代码的细节,将重点放在程序的高层逻辑上,还能在众多不同的程序中重用函数
firsr.py

def make_pizza(size, *toppings):
    """概述要制作的披萨"""
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("-" + topping)

second.py

import first
first.make_pizza(16, 'pepperoni')
first.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
module_name.function_name()

导入特定函数

from module_name import function_name
from module_name import function_0, function_1, function_2

second.py

from first import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

使用 as 给函数指定别名

from module_name iport function_name as fn

second.py

from first import make_pizza as f
f(16, 'pepperoni')
f(12, 'mushrooms', 'green peppers', 'extra cheese')

使用 as 给模块指定别名

import module_name as mn

second.py

import first as f
f.make_pizza(16, 'pepperoni')
f.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

导入模块中所有的函数
使用星号(*)运算符可让Python导入模块中的所有函数,使用非自己编写的大型模块时,不要采用这个导入方法

from module_name import *

second.py

from first import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

8.7 函数编写指南

每个函数都应包含简要地阐述其功能的注释,该注释跟在函数定义的后面
给形参设定默认值的时候,等号两边不要有空格
程序模块包括多个函数,使用两个空行将相邻的函数分隔开

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值