安装
- 下载地址
- 安装(记得添加Path)
# 查看Python安装版本
C:\Users\ThinkPad>python -V
Python 3.5.0
使用Sublime Text
- 创建HelloWorld.py文件
- Ctrl+B运行
变量和简单数据类型
变量
变量的命名和使用
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greetingmessage会引发错误
- 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print
- 变量名应既简短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好
- 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0
字符串
数字
- 整数
- 浮点数
注:
可以使用str()方法将数字转换成为字符串
列表
列表:由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有 任何关系
# 使用 [] 来表示列表,用逗号分隔其中的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
#连通中括号也会打印出来 ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# 单独打印一个元素,下表从0开始
print(bicycles[0])
# python访问列表最后一个元素可以使用-1下标
print(bicycles[-1])
列表的修改、添加和删除
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
修改
# 列表修改元素
bicycles[0] = "ducati"
# 输出:ducati
print(bicycles[0])
添加
# 列表添加元素
# 在列表末尾添加元素
bicycles.append("honda")
# 输出:['ducati', 'cannondale', 'redline', 'specialized', 'honda']
print(bicycles)
# 在列表指定位置添加元素
bicycles.insert(0,"lyb666")
# 输出:['lyb666', 'ducati', 'cannondale', 'redline', 'specialized', 'honda']
print(bicycles)
删除
# 列表删除元素
# 删除列表指定下标元素
del bicycles[0]
# 输出:['ducati', 'cannondale', 'redline', 'specialized', 'honda']
print(bicycles)
# 删除列表中最后的元素,并对其进行使用
name = bicycles.pop()
# 弹出最后一个元素并作为返回值,输出:honda
print(name)
# 使用pop(index)删除列表中的任意元素
name = bicycles.pop(1)
# 删除下标为1的元素,打印:cannondale
print(name)
# 如果不知道要删除元素的索引,可以是用值进行删除
bicycles.remove("redline")
# 删除列表中的值为:redline的元素,输出:['ducati', 'specialized']
print(bicycles)
列表排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
sort()
# 使用sort()对列表进行永久排序
cars.sort()
# 输出:['cannondale', 'redline', 'specialized', 'trek']
print(cars)
# 使用参数reverse=True进行降序排列
cars.sort(reverse=True)
# 输出:['toyota', 'subaru', 'bmw', 'audi']
print(cars)
sorted()
# 使用sorted()对列表进行临时排序
print("原列表:" + str(cars))
print("使用sorted排序列表:" + str(sorted(cars)))
print("使用sorted排序后的列表:" + str(cars))
# 输出
原列表:['toyota', 'subaru', 'bmw', 'audi']
使用sorted排序列表:['audi', 'bmw', 'subaru', 'toyota']
使用sorted排序后的列表:['toyota', 'subaru', 'bmw', 'audi']
reverse()
注意:
倒序输出列表,仅仅是倒着输出,并不是进行降序的排列
# 倒序输出列表,仅仅是倒着输出,并不是进行降序的排列
# 输出:['toyota', 'subaru', 'bmw', 'audi']
print(cars)
# 输出:['audi', 'bmw', 'subaru', 'toyota']
cars.reverse()
print(cars)
len()
# 确定列表长度
print(len(cars))
# 输出
4
常见错误
使用的索引超出列表长度
IndexError: list index out of range
列表遍历
# 列表遍历
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
创建数值列表
使用range()
for value in range(1,5):
print(value)
# 输出,前闭后开
1
2
3
4
使用range()创建数值列表
numbers = list(range(1,5))
print(numbers)
# 输出,前闭后开
1
2
3
4
digits = list(range(0,10))
print(digits)
print("列表最小值:" + str(min(digits)))
print("列表最大值:" + str(max(digits)))
print("列表和:" + str(sum(digits)))
# 输出
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
列表最小值:0
列表最大值:9
列表和:45
列表解析
squares = [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
使用列表一部分:切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:4])
# 遍历切片
for s in players[:4]:
print(s)
# 输出
['charles', 'martina', 'michael', 'florence']
charles
martina
michael
florence
复制列表
players = ['charles', 'martina', 'michael', 'florence', 'eli']
players_copy = players[:]
print(players_copy)
# 输出
['charles', 'martina', 'michael', 'florence', 'eli']
元组
元组:元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。
定义元组
tuple_test = (200,50)
print(tuple_test)
print(tuple_test[0])
# 遍历元组
for i in tuple_test :
print(i)
修改元组
注意:
元组是不允许修改的,但是我们可以重新赋值给元组变量
tuple_test = (200,50)
# 对元组变量重新赋值
tuple_test = (400,200)
if语句
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == "bmw":
print(car.upper())
else:
print(car.title())
符号 | 描述 |
---|---|
== | 等于 |
!= | 不等于 |
< | 小于 |
> | 大于 |
<= | 小于等于 |
>= | 大于等于 |
and | 并且 |
or | 或者 |
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 you turn 18!")
if-elif-else
注意:
最后的else可以省略
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.")
判断列表是否为空
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!")
字典
字典:是一系列 键—值 对 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将 任何Python对象用作字典中的值
字典用放在花括号{} 中的一系列键—值对表示
# 定义字典
alien_0 = {'color': 'green', 'points': 5}
# 获取字典中的值
print(alien_0['color'])
print(alien_0['points'])
# 输出
green
5
向字典中添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 输出
{'y_position': 25, 'color': 'green', 'points': 5, 'x_position': 0}
修改字典中的值
alien_0['color'] = 'yellow'
print(alien_0)
# 输出
{'color': 'yellow', 'points': 5, 'x_position': 0, 'y_position': 25}
删除键值对
del alien_0['points']
print(alien_0)
# 输出
{'color': 'yellow', 'x_position': 0, 'y_position': 25}
由类似对象组成的字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print(favorite_languages)
# 输出
{'edward': 'ruby', 'jen': 'python', 'phil': 'python', 'sarah': 'c'}
遍历字典
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key,value in user_0.items():
print("key:" + key + "\tvalue:" + value )
# 输出
key:username value:efermi
key:last value:fermi
key:first value:enrico
遍历字典中所有键
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key in user_0.keys():
print(key.title())
# 输出
First
Last
Username
按照顺序遍历字典中的键
for key in sorted(user_0.keys()):
print(key.title())
First
Last
Username
遍历字典中的所有值
for value in user_0.values():
print(value)
# 输出
enrico
fermi
efermi
嵌套
字典列表
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)
# 输出
{'points': 5, 'color': 'green'}
{'points': 10, 'color': 'yellow'}
{'points': 15, 'color': 'red'}
用户输入和while循环
input()函数
- 配置sublime_test3运行input()
- 使用快捷键Ctrl + shift + P ,在弹出的输入框中输入install package control。
- 择Install Package等待新的输入框出现,输入SublimeREPL,回车安装。
- 依次点击Preferences—>Key Buildings,输入以下内容,然后保存,设置按键Ctrl+R(可以随意修改)为运行程序快捷键。
{ "keys": ["f5"], "caption": "SublimeREPL:Python",
"command": "run_existing_window_command", "args":
{
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
}
- 配置完毕后保存。运行含有input()的python代码时使用配置好的快捷键即可运行。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
函数
- 定义函数
def greet_user():
print("Hello")
greet_user()
- 向函数传递信息
def greet_user(name):
print("Hello," + name.title())
greet_user("jeses")
- 实参和形参
- 关键字实参
def describe_pet(pet_name,animal_type):
print("I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
"""使用关键字进行传参,可以不按照参数顺序"""
describe_pet(pet_name='harry',animal_type='hamster')
- 默认值
def describe_pet(pet_name,animal_type="dog"):
print("I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='harry')
- 返回值
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 make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 222, '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)
将函数存储在模块中
- 创建pizza.py
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
- 创建make_pizza.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
- 导入整个模块
import pizza
- 导入特定函数
from module_name import function_name1,function_name2,function_name3
- 使用as给函数指定别名
"""样例"""
from pizza import make_pizza as mp
"""模板"""
from module_name import function_name as fn
- 导入模块中的所有函数
"""样例"""
from pizza import *
"""模板"""
from module_name import *
类
创建和使用类
- 创建Dog类
class Dog():
"""初始化方法中,self参数必须指定"""
def __init__(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!")
- 创建类的实例
"""创建Dog实例"""
my_dog = Dog('willie',6)
"""调用实例的属性"""
print(my_dog.name)
print(str(my_dog.age))
"""调用实例的方法"""
my_dog.sit()
my_dog.roll_over()
使用类和实例
- 创建Car类
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
- 给属性指定默认值
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()
- 修改属性的值
my_new_car = Car('audi', 'a4', 2016)
my_new_car.odometer_reading = 23
继承
- 子类的方法__init__()
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
class ElectricCar(Car):
# 初始化父类的属性
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = 70
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model + ' ' + '重写父类中的方法'
return long_name.title()
- 将实例用作属性
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
class ElectricCar(Car):
# 初始化父类的属性
def __init__(self, make, model, year):
super().__init__(make, model, year)
# 将实例作为属性
self.battery = Battery()
def describe_battery(self):
print("This car has a " + str(self.battery.battery_size) + "-kWh battery.")
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model + ' ' + '重写父类中的方法'
return long_name.title()
导入类
- 导入单个类
from car import Car
- 从一个模块中导入多个类
from car import Car, ElectricCar
- 导入整个模块
import car
- 导入模块中所有的类
from module_name import *
python标准库
OrderedDict类
:OrderedDict 实例的行为几乎与字典相同,区别只在于记录了键—值对的添加顺序
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
文件和异常
从文件中读取数据
- 读取整个文件
创建pi_digits.txt文件,它包含精确到小数点后30位的圆周率值,且在小数点后每10位处都换行
3.1415926535
8979323846
2643383279
关键字with 在不再需要访问文件后将其关闭
with open('pi_digits.txt') as file_object:
contexts = file_object.read()
print(contexts)
相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。为何会多出这个空行呢?因为read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一 个空行。要删除多出来的空行,可在print 语句中使用rstrip()
with open('pi_digits.txt') as file_object:
contexts = file_object.read()
print(contexts.rstrip())
- 文件路径
print("相对路径打开的文件:")
with open('test_files\\pi_digits.txt') as file_object:
contexts = file_object.read()
print(contexts.rstrip())
print("绝对路径打开的文件:")
with open('E:\\Python\\python_work\\基础\\pi_digits.txt') as file_object:
contexts = file_object.read()
print(contexts.rstrip())
- 逐行读取
print("逐行打印:")
with open('pi_digits.txt') as file_object:
for line in file_object:
print(line.rstrip())
- 创建一个包含文件各行内容的列表
使用关键字with 时,open() 返回的文件对象只在with 代码块内可用。如果要在with 代码块外访问文件的内容,可在with 代码块内将文件的各行存储在一个列表中,并 在with 代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。
with open('pi_digits.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print("在with代码块之外,处理文件内容:" + line.rstrip())
前面我们分析的都是一个只有三行的文本文件,但这些代码示例也可处理大得多的文件。如果我们有一个文本文件,其中包含精确到小数点后1 000 000位而不是30位的圆周率 值,也可创建一个包含所有这些数字的字符串。为此,我们无需对前面的程序做任何修改,只需将这个文件传递给它即可。在这里,我们只打印到小数点后50位,以免终端为显 示全部1 000 000位而不断地翻滚:
with open('test_files\\pi_million_digits.txt') as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string[:50] + "...")
写入文件
- 写入空文件
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
第一个实参也是要打开的文件的名称;第二个实参(‘w’ )告诉Python,我们要以写入模式 打开这个文件。打开文件 时,可指定读取模式 (‘r’ )、写入模式 (‘w’ )、附加模式 (‘a’ )或让你能够读取和写入文件的模式(‘r+’ )。如果你省略了模式实参,Python将以默认的只读模式打 开文件
- 写入多行
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
- 附加到文件
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
异常
每当发生让Python不知所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继 续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告
- 处理异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
- else代码块
通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力。错误是执行除法运算的代码行导致的,因此我们需要将它放到try-except 代码块 中。这个示例还包含一个else 代码块;依赖于try 代码块成功执行的代码都应放到else 代码块中
try:
answer = 5/1
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
- 出现异常不进行处理
try:
--snip--
except FileNotFoundError:
# 使用pass字段,代码块不进行任何操作
pass
else:
--snip--
存储数据
-
使用json.dump()和json.load()
第一个程序将使用json.dump() 来存储这组数字,而第二个程序将使用json.load()将这些数字读取到内存中的程序 -
number_writer.py
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
- number_read.py
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
保存和读取用户生成的数据
import json
username = 'Eric'
# 将用户名存储在 username.json 的文件中
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remenber you when you come back," + username + "!")
# 将用户名从 username.json 的文件中读出
with open(filename) as f_obj:
username_replication = json.load(f_obj)
print(username_replication)
重构
"""重构"""
def greet_user():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = "defualt_name"
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print(username)
else:
print(username)
greet_user()
测试代码
测试函数
- name_function.py
定义一个接受名和姓并返回整洁的姓名的函数
def get_formatted_name(first,last):
full_name = first + ' ' + last
return full_name.title()
- names.py
循环调用函数进行测试
from name_function import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
first = input("\nPlease give me a first name: ")
if first == 'q':
break
last = input("Please give me a last name: ")
if last == 'q': break
formatted_name = get_formatted_name(first,last)
print(formatted_name)
单元测试和测试用例
Python标准库中的模块unittest 提供了代码测试工具
- 单元测试:用于核实函数的某个方面没有问题
- 测试用例:是一组单元测试,这些单元测试一起核实函数在各种情形下的 行为都符合要求
创建测试用例
要为函数编写测试用例,可先导入模块unittest 以及要测试的函 数,再创建一个继承unittest.TestCase 的类,并编写一系列方法对函数行为的不同方面进行测试。
import unittest
from name_function import get_formatted_name
class NameTestCase(unittest.TestCase):
def test_first_last_name(self):
formatted_name = get_formatted_name('janis','joplin')
# 断言方法,判断我们的的结果是否符合我们期望结果
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
# 输出
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
[Finished in 0.2s]
"""第1行的句点表明有一个测试通过了。接下来的一行指出Python运行了一个测试"""
测试类
各种断言方法
使用这些方法可核实返回的值等于或不等于预期的值、返回的值为True 或False 、返回的值在列表中或不在列表中。你只能在继 承unittest.TestCase 的类中使用这些方法
方法 | 用途 |
---|---|
assertEqual(a, b) | 核实a == b |
assertNotEqual(a, b) | 核实a != b |
assertTrue(x) | 核实x 为True |
assertFalse(x) | 核实x 为False |
assertIn(item , list ) | 核实 item 在 list 中 |
assertNotIn(item , list | 核实 item 不在 list 中 |
进行类测试
- survey.py
class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self,question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_question(self,new_response):
self.responses.append(new_response)
def show_results(self):
print("Survey results:")
for response in self.responses:
print('- ' + response)
- language_survey.py
from survey import AnonymousSurvey
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_question(response)
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
- test_survey.py
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def test_store_single_response(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_question('English')
self.assertIn('English',my_survey.responses)
unittest.main()
方法setUp()
在前面的test_survey.py中,我们在每个测试方法中都创建了一个AnonymousSurvey 实例,并在每个方法中都创建了答案。unittest.TestCase 类包含方法setUp() ,让我 们只需创建这些对象一次,并在每个测试方法中使用它们。如果你在TestCase 类中包含了方法setUp() ,Python将先运行它,再运行各个以test_打头的方法。这样,在你编写 的每个测试方法中都可使用在方法setUp() 中创建的对象了。
- setUp方法
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
""" 创建一个调查对象和一组答案,供使用的测试方法使用 """
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.my_survey.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
# question = "What language did you first learn to speak?"
# my_survey = AnonymousSurvey(question)
# my_survey.store_question(self.responses[0])
# self.my_survey.show_results()
self.assertIn('English',self.my_survey.responses)
unittest.main()
项目
外星人入侵
- 在windows系统中安装Pygame
- 更新pip,修改pip源至国内镜像
# Linux下,修改 ~/.pip/pip.conf (没有就创建一个), 修改 index-url至tuna,内容如下:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=mirrors.aliyun.com
# windows下,直接在user目录中创建一个pip目录,如:C:\Users\xx\pip,新建文件pip.ini,内容如下
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=mirrors.aliyun.com
- 下载并安装,pygame-1.9.6-cp35-cp35m-win_amd64.whl
下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame
# 切换到该文件所在的文件夹,并使用pip来运行它
python install pygame-1.9.6-cp35-cp35m-win_amd64.whl
C:\Users\ThinkPad>pip list
Package Version
---------- -------
pip 20.2.2
pygame 1.9.6 # 安装成功
setuptools 18.2
wheel 0.35.1