print("Hello Python !")
开始
first_name = "zou"
last_name = "keqing"
full_name = first_name + " " + last_name
方法title() 来将姓名设置为合适的格式
# 方法title() 来将姓名设置为合适的格式
message = "hello," + full_name.title() + " !"
print(message)
# 输出为hello,Zou Keqing !
乘方
print(3 ** 3) ** # 可表示为乘方,输出为27
浮点数
print(0.1 + 0.1)
print(0.2 + 0.1)
# 输出为
# 0.2
# 0.30000000000000004
避免类型错误
age = 23
# str()将整数用作字符串
message = "Happy " + str(age) + "rd birthday!"
print(message)
整数除法
print(3/2)
# Python3 输出为1.5;Python2输出为1
列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
# 返回最后一个元素
print(bicycles[-1].title())
修改、添加和删除元素
修改
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles)
添加
motorcycles.append("ducati")
print(motorcycles)
motorcycles.insert(0,"ducati")
print(motorcycles)
删除
del 语句删除元素
del motorcycles[0]
print(motorcycles)
pop()方法删除列表末尾的元素
motorcycles.pop()
添加参数index删除指定的元素
motorcycles.pop(0)
print(motorcycles)
根据值删除元素
motorcycles.remove("yamaha")
print(motorcycles)
组织列表
sort() 对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True
cars.sort(reverse=True)
print(cars)
函数sorted() 对列表进行临时排序
print(sorted(cars))
print(cars)
reverse()反转列表元素的排列顺序
cars.reverse()
print(cars)
确定列表的长度
print(len(cars))
操作列表
for循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + " !")
创建数值列表
函数range()
for value in range(1,6):
print(value)
print(range(1,6))
使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)
print(list(range(0,11,2)))
列表解析
print([value **2 for value in range(1,11)])
指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值;
接下来,编写一个for 循环,用于给表达式提供值,再加上右方括号
使用列表的一部分
切片 处理列表的部分元素
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[:4])
print(players[2:])
print(players[-3:])
遍历切片
for player in players[:4]:
print(player.title())
复制列表,而不是简单的赋值
other_players = players[:]
print(other_players)
other_players.append("other")
print(players)
print(other_players)
输出结果
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'other']
元组
列表非常适合用于存储在程序运行期间可能变化的数据集。
列表是可以修改的,这对处理网站的用户列表或游戏中的角色列表至关重要。
然而,有时候你需要创建一系列不可修改的元素,元组可以满足这种需求
元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。
dimensions = (200, 50)
print(str(dimensions[0]) + "," + str(dimensions[1]))
遍历
for dimension in dimensions:
print(dimension)
修改元组变量
虽然不能修改元组的元素,但可以给存储元组的变量赋值。
dimensions = (528)
print(dimensions)
if语句
一个简单的示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
检查是否相等时不考虑大小写
car = 'Audi'
print(car == 'audi')
print(car.lower() == 'audi')
检查多个条件
使用and检查多个条件
age = 18
print(age >= 18 and age <= 22)
使用or检查多个条件
print(age <= 16 or age >= 18)
检查特定值是否包含在列表中
if 8 in range(5,9):
print(8 in range(5,9))
print("存在")
if 8 not in range(1,7):
print(8 not in range(1,7))
print("不存在")
if-elif-else 结构
age = 20
if age < 5:
print("age < 5")
elif age < 18:
print("5 <= age < 18")
elif age < 25:
print("18 <= age < 25")
else:
print("age >= 25")
如果列表为空可返回False
car = []
if car:
print("car 不为空")
else:
print("car 为空")
字典
一个简单的字典
创建一个空字典
alien_0 = {}
alien_0 = {'color': 'green', 'points': 5}
访问字典中的值
print(alien_0['color'])
print(alien_0['points'])
添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
修改字典中的值
alien_0['color'] = 'yellow'
print(alien_0)
删除键值对
del alien_0['y_position']
print(alien_0)
遍历字典
for key,value in alien_0.items():
print("\nKey: " + key)
print("Value: " + str(value))
遍历字典中的所有键
for name in alien_0.keys():
print(name)
for name in alien_0 也默认为 for name in alien_0.keys()
按顺序遍历字典中的所有键
使用函数sorted() 来获得按特定顺序排列的键列表的副本
for name in sorted(alien_0.keys()):
print(name)
当然也可以省略.keys(),如for name in sorted(alien_0):
遍历字典中的所有值
values = []
for value in alien_0.values():
print(value)
values.append(str(value))
print(values)
这种做法提取字典中所有的值,而没有考虑是否重复。
涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量的重复项。
为剔除重复项,可使用集合(set)。集合 类似于列表,但每个元素都必须是独一无二的
通过对包含重复元素的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合
values = []
values_1 = []
for value in set(alien_0.values()):
values.append(str(value))
values_1.append(value)
print(values)
print(values_1)
嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
示例
创建一个用于存储外星人的空列表
aliens = []
创建30个外星人
for alien_number in range(30):
new_alien = {'id':alien_number,'color':'yellow','points':5}
aliens.append(new_alien)
print(aliens[:5])
用户输入和while 循环
你使用函数input() 时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息指出用户该输入任何信息的提示都行
name = input("Please enter your name: ")
print("\nHello, " + name + "!")
使用int() 来获取数值输入
age = input("How old are you?")
age = int(age)
print(age)
让用户选择何时退出
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)
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
else:
print("I'd love to go to " + city.title() + "!")
在循环中使用continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
使用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())
删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
使用用户输入来填充字典
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':
polling_active = False
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
函数
定义函数
def greet_user():
print("Hello!")
greet_user()
传递参数
def greet_user(username):
print("Hello," + username.title() + "!")
greet_user("python")
关键字实参
关键字实参是传递给函数的名称—值对
关键字实参无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途
def greet_user(username,age):
print("Hello,"+username.title())
print("And age is " + str(age))
greet_user(age=20,username='zoukeqing')
默认值
def greet_user(username,age = 20):
print("Hello,"+username.title())
print("And age is " + str(age))
greet_user(username='zoukeqing')
greet_user('zoukeqing')
返回值
返回简单值
def get_formatted_name(first_name,last_name):
full_name = first_name + " " + last_name
return full_name.title()
print(get_formatted_name('zou','keqing'))
让实参变成可选的
def get_formatted_name(first_name = '',middle_name = '',last_name = ''):
if first_name and middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name + '1'
elif middle_name:
full_name = middle_name + ' ' + last_name + '2'
else:
full_name = last_name + '3'
return full_name
print(get_formatted_name('zou','ke','qing'))
print(get_formatted_name(middle_name='ke',last_name='qing'))
print(get_formatted_name(last_name='keqing'))
返回字典
def build_person(first_name,last_name,age = ''):
person = {'first':first_name,'last':last_name}
if age:
person['age'] = age
return person
print(build_person('zou','keqing'))
print(build_person('zou','keqing',20))
传递列表
def greet_users(names):
for name in names:
message = "Hello," + name.title() + "!"
print(message)
usernames = ['kkk','Kevin','zoukeqing']
greet_users(usernames)
在函数中修改列表
向函数传递列表的原件
def greet_users(names):
禁止函数修改列表
向函数传递列表的副本而不是原件,这样函数所作的修改都只影响副本,丝毫不影响原件
def greet_users(names[:]):
传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参名*toppings 中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。
一个星号* 创建空元组
两个星号** 创建空字典
使用任意数量的关键字实参
在下面的示例中,函数build_profile() 接受名和姓,同时还接受任意数量的关键字实参
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('zou','keqing',location = 'Gexianshan',age = 20)
print(user_profile)
类
创建和使用类
模拟小狗的简单尝试
class Dog():
# 创建一个实例,并初始化属性
def __init__(self,name,age):
self.name = name
self.age = age
self.color = 'yellow'
def get_description(self):
"""返回整洁的描述性信息"""
long_name = self.name.title() + ' ' + str(self.age) + ' ' + self.color
return long_name
self 指向实例本身的引用,让实例能够访问类中的属性和方法
def sit(self):
"""蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""打滚"""
print(self.name.title() + " rolled over!")
def read_color(self):
"""查看小狗的颜色信息"""
print(self.color)
def update_color(self,color):
"""通过方法修改属性的值"""
self.color = color
根据类创建实例
my_dog = Dog("willie",6)
访问属性
print(my_dog.name)
调用方法
my_dog.sit()
创建多个实例
your_dog = Dog('lucy',3)
print(your_dog.name)
your_dog.sit()
通过方法读取
my_dog.read_color()
直接修改属性的值
my_dog.color = 'white'
my_dog.read_color()
通过方法修改属性
my_dog.update_color('golden')
my_dog.read_color()
继承
子类继承其父类的所有属性和方法,同时还可以定义自己的属性和方法
子类的方法init()
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 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()
my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
导入类
假设在另外一个文件导入整个模块
import hello
my_tesla = hello.ElectricCar('tesla', 'model s', 2018)
导入单个类
from hello import ElectricCar
导入多个类
from hello import Car,ElectricCar
文件和异常
新建一个pi_digits.txt文件,输入:
3.1415926535
8979323846
2643383279
读取文件代码如下
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
说明: / 斜杠 和 \ 反斜杠 的使用是在于文件路径在Linux和OS X中用斜杠而Windows系统中用反斜杠
逐行读取
with open('pi_digits.txt') as file_object:
for line in file_object:
print(line)
去除每行末尾的换行符
print(line.rstrip())
创建一个包含文件各行内容的列表
with open('pi_digits.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
写入文件
写入空文件
with open('program.txt', 'w') as file_object:
file_object.write("I love programing.")
缺省值默认只读模式打开文件
读取模式 r;写入模式 w;附加模式 a;读取和写入模式 r+
如果你要写入的文件不存在,函数open() 将自动创建它。
然而,以写入('w' )模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
写入多行
with open('program.txt', 'w') as file_object:
file_object.write("I love programing.")
file_object.write("I love creating new game.")
file_object.write("\nI love programing.")
附加到文件
with open('program.txt', 'a') as file_object:
file_object.write("\n附加到文件")
异常
try-except代码块
print(5/0)
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
使用异常避免崩溃
通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力
这个示例还包含一个else 代码块;依赖于try 代码块成功执行的代码都应放到else 代码块中
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:print(answer)
处理FileNotFoundError异常
filename = 'example.txt'
try:
with open(filename) as file_object:
contents = file_object.read()
print(contents)
except FileNotFoundError:
message = "Sorry,the file " + filename + " does not exist."
print(message)
分析文本
split() 根据一个字符串创建一个单词列表
title = 'Alice in Wonderland'
print(title.split())
使用多个文件
def count_words(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
# pass语句使发生异常时什么都不做
pass
print("Sorry,the file " + filename + " does not exist.")
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = 'program.txt'
count_words(filename)
# 文件example.txt不存在,但这丝毫不影响这个程序处理其它文件
filenames = ['pi_digits.txt', 'example.ext', 'program.txt']
for filename in filenames:
count_words(filename)
存储数据
先导入json整个模块:import json
json.dump() 接受两个参数:要存储的数据以及可用于存储数据的文件对象
json.load() 返回数据,接受一个参数:存储数据的文件对象
测试代码
测试函数
hello.py文件
def get_formatted_name(first, last):
full_name = first + ' ' + last
return full_name
新建另一个测试文件,导入unittest模块,代码格式如下:
import unittest
from hello import get_formatted_name
class NamesTestCase(unittest.TestCase):
# 测试函数
# 创建一个类,继承unittest.TestCase
def test_first_last_name(self):
# 必须以test开头
formatted_name = get_formatted_name('Zou', 'Keqing')
self.assertEqual(formatted_name, 'Zou Keqing')
unittest.main()
各种断言方法
方法 | 用途 |
---|---|
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 中 |
测试类
hello.py文件
class AddName:
def __init__(self):
self.names = []
def store_name(self, new_name):
self.names.append(new_name)
def show_names(self):
print(self.names)
同样在另一个测试文件,导入unittest模块,代码格式如下:
import unittest
from hello import AddName
class TestAddName(unittest.TestCase):
def test_store_single_name(self):
add_name = AddName()
add_name.store_name('kkk')
self.assertIn('kkk', add_name.names)
def test_store_three_names(self):
add_name = AddName()
add_name.store_name('zou')
add_name.store_name('yu')
add_name.store_name('huang')
names = ['zou', 'yu', 'huang']
for name in names:
self.assertIn(name, add_name.names)
unittest.main()
setUp() 方法
只需创建对象一次,并在每个测试方法中使用它们
import unittest
from hello import AddName
class TestAddName(unittest.TestCase):
def setUp(self):
self.add_name = AddName()
self.add_name.store_name('kkk')
self.add_name.store_name('zou')
self.add_name.store_name('yu')
self.add_name.store_name('huang')
name_1 = 'ooo'
self.add_name.store_name(name_1)
def test_store_single_name(self):
self.assertIn('kkk', self.add_name.names)
def test_store_three_names(self):
names = ['zou', 'yu', 'huang']
for name in names:
self.assertIn(name, self.add_name.names)
print(self.add_name.names)
unittest.main()
网友评论