bicyle=['cannondale','trek']
bicyle[0]
#只返回元素,不包括方括号和引号
bicyle[-1]
#-1返回最后一个,-2返回倒数第二个
bicyle.append()
#添加至末尾
bicyle.insert(0,'ducati')
#将元素添加至索引0 的位置
del bicyle[0]
#删除,任意位置的
bicyle.pop()
#删除末尾元素,并且返回该元素
bicyle.pop(1)
#删除指定位置元素,并且返回该元素
bicyle.remove('trek')
#根据值删除元素,并且返回该元素(只删除第一个指定的值,如果一个值重复出现很多次,用循环判断是否删除完)
bicyle.sort()
#安字母表排序,顺序是永久的
message = ['a', 'b', 'v', 'A', 'B', 'G', '1', '2', '5', '36', '-3', '-21']
message.sort()
print(message)
# result: ['-21', '-3', '1', '2', '36', '5', 'A', 'B', 'G', 'a', 'b', 'v']
message.sort(reverse=true)
#按与上面方法相反排列
sorted(bicyle)
#临时排序打印
bicyle.reverse()
#将列表倒着打印
len(bicyle)
#返回bicycle的长度
for bike in bicyle:
print(bike)
for number in range(1,5):
print(number)
#打印1~4(左含右不含)
number = list(range(1,6))
# [1, 2, 3, 4, 5]
number2 = list(range(2,11,2))
#指定步长 [2, 4, 6, 8, 10]
min(number)
max(number)
sum(number)
squares = [value**2 for value in range(1,11)]
number[0:3]
#返回一个列表,3个元素,左含右不含
number[:3]
#从开头到索引为3
number[3:]
#从索引为3到结尾
number[-3:]
#返回最后3个
元组不可以修改,列表可以修改
dimension = (200,50)
if bike in bicyle :
if bike not in bicyle:
if age < 4:
print()
elif age < 18 :
print()
elif age < 38 :
print()
else : #else 可以省略
print()
bicyle = []
if bicyle:
print()
#如果不是空,true
alien_0 ={'color':'green','points':5}
print(alien_0['color'])
#通过key 找到value
alien_0['name']='JinZY'
print(alien_0)
#{'color':'green','points':5,'name':'JinZY}
alien_0['color']='red'
del alien_0['name']
可声明任意两个变量用于存储
for k , v in alien_0.items()
# items() 返回键-值对列表。
#返回的顺序可能与存储的顺序不同 ,键—值对的存储顺序,而 只跟踪键和值之间的关联关系
for k in alien_0.keys():
#顺序可能不同 keys()方法可以不写,是默认遍历key的
#key()返回一个列表,可用于确认某个键是否在keys中
for k in sorted( alien_0.keys() ):
for v in alien_0.values():
for v in set( alien_0.values() ):
#剔除重复的value,set集合不能重复
将字典存在列表中,或将列表做为值存在字典中
将字典存在列表中
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]
列表做为值存在字典中
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
message = input("Enter your name : ")
# 里面文字为提示内容, message 值为键盘输入值
#有时提示超过了一行,则:
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
输入的所有为字符串
int("21")
while True:
if city == 'haha':
break
else:
print()
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
# 打印奇数
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')
#等号两边不要有空号
#防止传递参数时混淆
def describe_pet(animal_type, pet_name='dog'):
#等号两边不要有空号
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='harry')
describe_pet(animal_type='hamster',pet_name='harry')
#默认是 dog,也可以指定
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!" print(msg)
usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)
function_name(list_name[:])
通过形参 *toppings 来传递所有实参
def make_pizza(*toppings):
def make_pizza(size, *toppings):
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)
将函数保存在name.py 的文件中,使用时导包
def make_pizza(size ,*toppings):
#将其保存在pizza.py z中
#导入整个模块
import pizza
pizza.make_pizza(16,'','','')
#导入特定函数
from pizza import make_pizza
make_pizza(16,'','','')
#函数指定别名
from pizza import make_pizza as mp
mp(16,'','','')
#模块指定别名
import pizza as p
p.make_pizza(16,'','','')
#根据约定,在python中,首字母大写的指类
class Dog():
#每次Dog类创造实例时,都会自动运行该方法
#形参self
#每个属性都必须要有初始值,哪怕是0或空字符串,如果设定了默认值,则无需形参。
def __init__(self,name,age):
self.name = name
self.age = age
self.type = dog
# 以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量。self.name = name 获取存储在形参name中的值,并将其存储到变量 name 中,然后该变量被关联到当前创建的实例。
def sit(self):
print()
def roll_over(self):
print()
为什么在方法定义中包含形参self?
因为Python调用 这个__init__() 方法来创建实例时,将自动传入实参self 。每个与类相关联的方法调用都自动传递实参self ,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。
以self 为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量,而这个变量称为属性
#创键实例
#主动调用__init__()方法,使用我们提供的值来设置属性,自动返回表示这条小狗的实例
my_dog = Dog('willie',6)
#访问属性
print(my_dog.name)
print(my_dog.age)
#使用方法
my_dog.sit()
直接修改
my_dog.name = 'JinZY'
通过方法修改属性的值
def update_name(self,name):
self.name = name
通过方法对属性的值进行递增
def add_name (self,oname):
self.name += oname
#父类必须包含在当前文件中,且位于子类前面
class Dog():
def __init__(self,name,age):
self.name = name
self.age = age
self.type = dog
def sit(self):
print()
def roll_over(self):
print()
class otherDog(Dog):
def __init__(self,name,age):
#调用父类的方法
super().__init__(self,name,age)
#定义自己的属性
self.weight = 70
class Dog():
def __init__(self,name,age):
self.name = name
self.age = age
self.type = dog
def sit(self):
print()
def roll_over(self):
print()
#可以描述这个类的细节,而不影响OtherDog
class weight():
def __init__(self,weight):
self.weight = weight
def describe_weight(self):
print()
class OtherDog(Dog):
def __init__(self,name,age):
#调用父类的方法
super().__init__(self,name,age)
#定义自己的属性
self.weight = weight()
my_dog = OtherDog('mike',9)
my_dog.describ_weight()
my_dog.sit()
from ** import ****
可以在一个模块中导入另一个模块
with open("filename.txt") as file_object:
contents = file_object.read()
print(contens.rstrip())
#rstrip()消除空白行
with open("filename.txt") as file_object:
for line in file_object;
#用with 关键字时,open()返回的对象,只在with代码块内可用。
with open("filenam.txt") as file:
#readlines()返回一个列表
lines = file.readlines()
for line in lines:
print()
with open(filename,'w') as file_object:
file_object.write("hahahah")
#open( ,"") 有多个参数 : 读取模式(r),写入模式(w),附加模式(a),读取和写入模式(‘r+’)
#open() 的对象如果存在,则清空文件再写入,不存在就创建新的文件
#只能写入字符串,用str()装成字符串
#附加模式(‘a’) : 将写入的行添加到文末,而不会覆盖原本内容
异常是使用try-except代码块处理的,
try:
print(5/0)
#tell python what to do rather than stop the program
except ZeroDivisonError:
print("can't be 0")
print("ahahhah")
# result:
# Can't be 0
# hahahahha
使用else:
while True:
first_name = input("Enter the first name")
if first_name == 'q':
break
second_name = input("Second name")
#可能发生异常的代码块放在try中
try:
ansewer = int(first_name)/int(second_name)
#有错误应该怎做
except ZeroDivisionError:
print("you can't dived by 0")
#如果没有报错改怎么样
else:
print(answer)
try:
except ******Error:
pass
else:
:以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。
try:
with open("test.txt") as t:
lines = t.readlines()
except FileNotFoundError:
print("The file is not found")
word=[]
for line in lines:
word +=line.split()
print(len(word))
模块json 让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
import json
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
with open("Tryjson.json", 'w') as T:
json.dump(number, T)
#Tryjson.json 内的内容:
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
with open("Tryjson.json") as T:
number = json.load(T)
print(number)
#result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
模块unittest 提供了代码测试工具,
import unittest
#导入被测试的方法
from name_function import get_formatted_name
#创造类用于包含一系列针对某一方法的单元测试,要继承unittest.TestCase类
class NameTestCase(unittest.TestCase):
#在运行时,所有以test打头的方法都自动运行
def test_firstname(self):
#判断得到的与期望的是否相同
self.assertEqual("The result from method" ,"The except" )
#让python运行这个文件中的测试
unittest,main()
与测试方法的方法相同
import unittest
#导入被测试的类
from survey import AnonymousSurvey
class TestAnonmyousSuivey(unittest.Testcase):
def test_store_single_response(self):
unittest.main()
方法 | 用途 |
---|---|
assertEqual(a,b) | whether a==b |
assertNotEqual(a,b) | whether a!=b |
assertTrue(x) | whether x is True |
assertFalse(x) | whether x is False |
assertIn(item,list) | whether item in list |
assertNotIn(item,list) | whether item not in list |
unittest.TestCase包中有setUp()方法,如果在测试类中先重写setUP(),则先运行setUP()方法,再运行以test开头的方法。
通过setUP()来构造对象,和接收得到的返回值