help(print) #如查看print函数的使用方法。 ---------------------------- Help on built-in functionprintin module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
2变量和简单数据类型
变量的命名和使用
变量名只能包含字母、数字和下划线。
变量名不能包含空格,但可使用下划线来分隔其中的单词。
不要将Python关键字和函数名用作变量名。
变量名应既简短又具有描述性
慎用大写字母I和O,因为它们可能被人错看成数字1和0。
使用变量时避免命名错误
hello_world.py #文件名 ---------------------------- message = "Hello Python Crash Course reader!" print(mesage) #Python运行代码 ---------------------------- Traceback (most recent call last): File "hello_world.py", line 2, in#文件“hello_world.py”中第二行有问题 print(mesage) #报错代码 NameError: name 'mesage' is not defined #具体问题:名为“mesage”的对象未找到。
字符串
使用方法修改字符串的大小写
name = "Ada Lovelace" print(name.upper()) #将字符串改为全部大写 print(name.lower()) #将字符串改为全部小写 ---------------------------- ADA LOVELACE #上述代码输出结果 ada lovelace
import this #编写优秀Python代码的指导原则 ---------------------------- The Zen of Python, by Tim Peters Beautiful is better than ugly. ... #在此省略,完整内容可在Python中输入上述代码查看。 If the implementation is hard to explain, it's a bad idea.
magicians = ['alice', 'david', 'carolina'] for magician in magicians: #for循环。注意,冒号不能遗漏 print(magician) #从列表magicians中取出一个名字,并将其存储在变量magician中,并将其打印出来 print("Thank you, everyone. That was a great magic show!") #for循环后面,缩进的代码才属于循环内容,会重复执行 ---------------------------- alice david carolina Thank you, everyone. That was a great magic show!
#Python将不能修改的值称为不可变的,而不可变的列表被称为元组 dimensions = (200, 50) #元组看起来犹如列表,但使用圆括号来标识 print(dimensions[0]) dimensions[0] = 250 #尝试修改元组dimensions中的一个元素 ---------------------------- 200 Traceback (most recent call last): #试图修改元组的操作是被禁止的 File "dimensions.py", line 3, in dimensions[0] = 250 TypeError: 'tuple' object does not support item assignment
修改元组变量
dimensions = (200, 50) for dimension in dimensions: print(dimension) dimensions = (400, 100) #重新定义整个元组 for dimension in dimensions: print(dimension) ---------------------------- 200 50 400 100
设置代码格式
PEP 8(Python Enhancement Proposal 8)向Python程序员提供了代码格式设置指南,一般编辑器里都有相关的设置,如Pycharm,一个TAB等于4个空格(可以在设置里修改)(tab:向右缩进)(shift + tab:向左缩进)、行长一般不超过80字符(上图的那条竖线)、还有一些其他问题Pycharm也在代码检查的时候给标记了出来(只要不是红色,代码就没有语法问题)。
5if语句
cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) #检查当前的汽车名是否是'bmw'。如果是,就以全大写的方式打印它; #否则就以首字母大写的方式打印 ---------------------------- Audi BMW Subaru Toyota
requested_toppings = ['mushrooms', 'onions', 'pineapple'] 'mushrooms'in
requested_toppings #是否包含 'mushrooms' not in requested_toppings #是否不包含 ---------------------------- True False
if-elif-else 结构
age = 12 if age #年龄小于4岁免门票 price = 0 elif age #4-18岁半价 price = 5 elif age #18-65岁全票 price = 10 else: #其他年龄组半价 price = 5 print("Your admission cost is $" + str(price) + ".") ---------------------------- Your admission cost is $5.
省略 else 代码块
age = 12 if age price = 0 elif age price = 5 elif age price = 10 elif age >= 65: price = 5 print("Your admission cost is $" + str(price) + ".") ---------------------------- Your admission cost is $5. #else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试, #其中的代码就会执行,这可能会引入无效甚至恶意的数据 #如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块
确定列表不是空的
requested_toppings = [] #创建空列表 if requested_toppings: #如果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?") ---------------------------- Are you sure you want a plain pizza?
user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi', } #使用for循环,声明两个变量,用于存储键—值对中的键和值 for key, value in user_0.items(): #items()返回一个键—值对列表 print("\nKey: " + key) print("Value: " + value) ----------------------------
Key: username Value: efermi
Key: first Value: enrico
Key: last Value: fermi
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): #keys()提取字典中的所有键 print(name.title()) #省略keys(),输出结果不变 for language in favorite_languages.values(): #values()提取字典中的所有值 print(language.title()) ---------------------------- Jen Sarah Edward Phil Python C Ruby Python
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for language inset(favorite_languages.values()): #剔除重复项 print(language.title()) #集合(set)类似于列表,但每个元素都必须是独一无二的 ---------------------------- Python Ruby C
#input()让程序暂停运行,等待用户输入一些文本。 #获取用户输入后,Python将其存储在一个变量中,以方便你使用 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 + "!") #运算符+=在存储在prompt中的字符串末尾附加一个字符串 ---------------------------- If you tell us who you are, we can personalize the messages you see. What is your first name? >? fanchen
Hello, fanchen!
age = input("How old are you? ") #input()会将用户输入解读为字符串 type(age) #查看age类型 age = int(age) #将字符串转换为整型 age >= 18 ---------------------------- How old are you? >? 21 'int'> True
求模运算符
number = input("Enter a number, and I'll tell you if it's even or odd: ") number = int(number) if number % 2 == 0: #它将两个数相除并返回余数 print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.") #如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0 #你可利用这一点来判断一个数是奇数还是偶数 ---------------------------- Enter a number, and I'll tell you if it's even or odd: >? 42 The number 42 is even.
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " active = True #这个变量被称为标志,用于判断整个程序是否处于活动状态 while active: message = input(prompt) if message == 'quit': active = False #当标志的值为False时,程序停止运行 else: print(message)
使用 break 退出循环
prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " while True: city = input(prompt) if city == 'quit': break#执行break语句,使Python退出循环 else: print("I'd love to go to " + city.title() + "!")
#调用函数时,基于实参顺序的关联方式被称为位置实参 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') #实参'hamster'存储在形参animal_type中, #实参'harry'存储在形参pet_name中 ---------------------------- I have a hamster. My hamster's name is Harry.
关键字实参
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') #传递给函数的名称—值对,无需考虑函数调用中的实参顺序
默认值
#在调用函数中给形参提供了实参时,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') #Python依然将这个实参视为位置实参 #所以在函数定义时,没有默认值的参数应放在设置了默认值的参数之前 ---------------------------- I have a dog. My dog's name is Willie.
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') #如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。 #Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中 ----------------------------
Making a 16-inch pizza with the following toppings: - pepperoni
Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese
使用任意数量的关键字实参
#形参**user_info中的两个星号让Python创建一个名为user_info的空字典, #并将收到的所有名称—值对都封装到这个字典中 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) ---------------------------- {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
将函数存储在模块中
要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码。
pizza.py #文件名 ---------------------------- def make_pizza(size, *toppings): """概述要制作的比萨""" print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping)
class Dog(): #创建 Dog 类 """一次模拟小狗的简单尝试"""#类中的函数称为方法 #__init__()是一个特殊的方法,每当你根据Dog类创建新实例时,Python都会自动运行它 def __init__(self, name, age): #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!") #以self为前缀的变量都可供类中的所有方法使用 ----------------------------
根据类创建实例
#使用前一个示例中编写的Dog类 my_dog = Dog('willie', 6) #创建实例 my_dog.name #使用句点表示法访问实例的属性 my_dog.sit() #调用方法 #可按需求根据一个类创建任意数量的实例, #条件是将每个实例都存储在不同的变量中,或占用列表或字典的不同位置 ---------------------------- 'willie' Willie is now sitting.
继承
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): #初始化 self.make = make self.model = model self.year = year self.odometer_reading = 0 #设置里程表默认值 def get_descriptive_name(self): #描述车的基本信息 long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): #获取车的里程表 print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): #更新里程表 if mileage >= self.odometer_reading: self.odometer_reading = mileage else: #设置里程表不能往下调 print("You can't roll back an odometer!") def increment_odometer(self, miles): #将里程表读数增加指定的量 self.odometer_reading += miles
class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """初始化父类的属性,再初始化电动汽车特有的属性""" #特殊函数super()帮助Python将父类和子类关联起来 super().__init__(make, model, year) #这行代码让Python调用ElectricCar的父类的方法__init__(), #让ElectricCar实例包含父类的所有属性。 #父类也称为超类(superclass),名称super因此而得名 self.battery_size = 70 #创建电动汽车特有的属性 def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery() ---------------------------- 2016 Tesla Model S This car has a 70-kWh battery.
with open('pi_digits.txt') as file_object: #确保和该文件在同一路径下 contents = file_object.read() #读取文件 print(contents) #用完文件可以调用close()来关闭文件,防止在某些情况下会产生一些错误。 #当然,如果未写close()语句,Python会在合适的时候自动将其关闭。 ---------------------------- 3.1415926535 8979323846 2643383279
文件路径
#如果想打开的文件和运行的程序不在同一路径下, #可使用绝对路径读取文件 file_path = 'C:/Users/ehmatthes/other_files/text_files/filename.txt' with open(file_path) as file_object: #建议使用斜杠(/)而不是反斜杠(\)来查找文件(包括windows系统)
#还有一种方法,修改当前的工作路径,使之与要打开的文件保持一致 import os #导入os库 print(os.getcwd()) #查看当前工作路径 os.chdir('C:/Users/ASUS/Desktop/venv') #修改工作路径
逐行读取
filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: #使用for循环以每次一行的方式检查文件 print(line) ---------------------------- 3.1415926535
#另一种逐行读取文件的方法 filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() #创建一个包含文件各行内容的列表 for line in lines: print(line.rstrip()) #读取文本文件时,Python将其中的所有文本都解读为字符串
写入文件
filename = 'programming.txt' with open(filename, 'w') as file_object: #第二个实参('w')告诉Python,我们要以写入模式打开这个文件 file_object.write("I love programming.\n") file_object.write("I love creating new games.\n") #写入多行
help(open) #查看open()的帮助文档 ---------------------------- Help on built-in function open in module io: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Open file and return a stream. Raise OSError upon failure. ... ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= =============================================================== ...
异常
使用 try-except 代码块
try: print(5/0) #错误代码 except ZeroDivisionError: #ZeroDivisionError是一个异常对象 print("You can't divide by zero!") #如果try代码块中的代码运行起来没有问题,Python将跳过except代码块; #如果try代码块中的代码导致了错误,Python将查找这样的except代码块, #并运行其中的代码,即其中指定的错误与引发的错误相同。 ---------------------------- You can't divide by zero!
分析文本
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: #计算文件大致包含多少个单词 words = contents.split() #根据一个字符串创建一个单词列表 num_words = len(words) #确定列表的长度 print("The file " + filename + " has about " + str(num_words) + " words.")
test_name_ function.py ---------------------------- #运行test_name_function.py时,所有以test_打头的方法都将自动运行 import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): #创建了名为NamesTestCase的类,用来继承unittest.TestCase类 """测试name_function.py""" def test_first_last_name(self): """能够正确地处理像Janis Joplin这样的姓名吗?""" formatted_name = get_formatted_name('janis', 'joplin') self.assertEqual(formatted_name, 'Janis Joplin') #self.assertEqual():是一种断言方法,用来核实得到的结果是否与期望的结果一致 #本行代码意思:将formatted_name的值同字符串'Janis Joplin'进行比较,判断是否相等 unittest.main() #不能用console窗口执行parse_args方法,一旦执行,就会导致console报错 ================================ #如果测试通过,则会出现如下的类似结果。 . ----------------------------------------------------------- Ran 1 tests in 0.000s OK Process finished with exit code 0 #运行测试用例时,每完成一个单元测试,Python都打印一个字符: #测试通过时打印一个句点;测试引发错误时打印一个E; #测试导致断言失败时打印一个F。
测试类
各种断言方法
方法 setUp()
import unittest from survey import AnonymousSurvey #相关代码及文件可在文末获取 class TestAnonymousSurvey(unittest.TestCase): """针对AnonymousSurvey类的测试""" def setUp(self): #Python会先运行setUp(),再运行各个以test_打头的方法 """创建一个调查对象和一组答案,供使用的测试方法使用""" question = "What language did you first learn to speak?" self.my_survey = AnonymousSurvey(question) self.responses = ['English', 'Spanish', 'Mandarin'] #在setUp()方法中创建一系列实例并设置它们的属性,再在测试方法中直接使用这些实例 def test_store_three_responses(self): """Test that three individual responses are stored properly.""" for response in self.responses: self.my_survey.store_response(response) for response in self.responses: self.assertIn(response, self.my_survey.responses) unittest.main()