列表
插入
删除
bicycle=['treck','cannonale','redline','specialized']
print(bicycle[-1])
mesage = f"My first bicycle was a {bicycle[0].title()}"
print(mesage)
#添加
bicycle.append("ducati")
print(bicycle)
#插入
bicycle.insert(2,"suziki")
print(bicycle)
#删除
del bicycle[2]
print(bicycle)
#删除方法pop从末尾删除
pop_motorcycle = bicycle.pop(0)
print(f"the last bicycle I owned was a {pop_motorcycle.title()}")
#根据值删除元素 remove只删除第一个指定的值
bicycle.remove('redline')
print(bicycle)
# 排序方法 sort() 永久保存 和sorted() 临时保存
bicycle.sort(reverse=True)
bicycle.sort(reverse=True)
# 倒着打印列表
bicycle.reverse()
# 确定列表长度
length = len(bicycle)
print(length)
循环
只有要在for循环中对每个元素执行的代码需要缩进
## range函数 从指定的第一个位置开始数,直到你指定的第二个值结束
for item in range(1,5):
print(item)
# 使用range船舰数字列表 从2开始数,不断加2,直到达到或者超过11
numbers = list(range(2,11,2))
print(numbers)
#10个数的平方放入数组中
square = []
for item in range(1,11):
vaule = item**2
square.append(vaule)
print(square)
squares = [item**2 for item in range(1,11)]
print(squares)
# 对数字进行简单的统计
min(square)
max(square)
sum(square)
# 切片
players = ['charls','kuli','qiaodan','kebi']
print(players[1:3])
print(players[:2])
print(players[2:]) # 提取到最后
print(players[-3:]) # 始终是提取最后三个人的名字
#遍历切片
for player in players[-3:]:
print(player.title())
#复制列表
favorite_player = players[:]
favorite_player.append("fufu")
print(favorite_player)
#如果直接favorite_player = players,这样的话两个副本就是一样的,而不是两个不同的副本了
# 元组 不可改变的值 用圆括号
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
#创建只有一个值的元组,也要加逗号
my_t= (3,)
# 遍历
for item in dimensions:
print(item)
# 修改元组变量,修改变量是可以的,但是不可以dimensions[0]这样改
dimensions = (400,100)
if语句
#and并列两个条件 or或者
age_0 = 22
age_1 = 18
if age_0>18 and age_1<=21:
print("yes")
if age_0>18 or age_1<=21:
print("yes")
# 检查特定值是否在列表中
request_toppings = ['mushroom','onlins','pineapple']
if 'mushroom' in request_toppings:
print("yes")
# 检查特定值不在列表中
request_toppings = ['mushroom','onlins','pineapple','greenpaper']
if 'mushrodom' not in request_toppings:
print("no")
# if-elif-else
age = 12
if age<4:
print("4")
elif age<18:
print("18")
elif age<25:
print("18")
else:
print("30")
# for和if的综合训练
for item in request_toppings:
if item == 'greenpaper':
print("sorry,we out of green apple right now")
else:
print(f"adding {item}")
字典
#定义字典
alien_0 = {'color':'green','point':5}
print(alien_0['color'])
print(alien_0['point'])
# 添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 删除键值对
del alien_0['x_position']
#大字典
favorite_language = {
'jen':'python',
'smash':'c',
'edward':'ruby',
'phill':'python',
}
language = favorite_language['smash'].title()
print(f"smashs favorite langeage is {language}")
# get访问值_没有则返回默认值
point_vaule = alien_0.get("points",'no point value assigned')
print(point_vaule)
#遍历字典
for key,item in favorite_language.items():
print(f"key is {key}\n")
print(f"item is {item}\n")
#遍历字典中的所有键和值
for key in favorite_language.keys():
print(f"key is {key}\n")
for key in favorite_language:
print(f"key is {key}\n")
for key in favorite_language.values():
print(f"values is {key}\n")
#按特定顺序遍历所有的键
for name in sorted(favorite_language.keys()):
print(f"{name.title()},thankyou foe taking the poll")
# 使用set集合剔除重复值
for key in set(favorite_language.values()):
print(f"values is {key}\n")
#集合
language = {"python",'c','java'}
#多个嵌套
aliens = []
alien_1 = {"color":'green','point':10}
alien_2 = {"color":'green','point':10}
alien_3 = {"color":'green','point':10}
alien_4 = {"color":'green','point':10}
alien_5 = {"color":'green','point':10}
for item in range(1,30):
new_alien = {"color":'green','point':10}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
#将前三个改为黄色
for item in aliens[:3]:
item['color'] = 'yellow'
#在字典中存储列表
pizza = {
'crust':'thick',
'topping':['mushroom','rxtra cheese']
}
for item in pizza['topping']:
print(item+"\n")
favorite_language = {
'jen':['python','c'],
'smash':['c','java'],
'edward':['ruby','bvbv'],
'phill':['python','jada'],
}
for item,key in favorite_language.items():
print(f"{item.title()}'s favorite language are:")
for vaule in key:
print(f"\n{vaule.title()}")
#在字典中嵌套字典
users = {
'aeinstein':{
'first':'alvert',
'last':'einstein',
'location':'princetion'
},
'mcuie':{
'first':'alvert',
'last':'einstein',
'location':'princetion'
}
}
for item,key in users.items():
print(f"\nUsername:{item}")
fullname = f"{key['first']} {key['last']}"
location = key['location']
用户输入和循环
#input
message = input("tell me something,and i will repeat it back to you:")
print(message)
#提示字段多行
prompt = "if we tell us who you are,we can personalize the message you see."
prompt+='\nwhat is your first name?'
name=input(prompt)
print(f"\nhello,{name}")
#input输入的字符是字符串,怎么将其变成数字,使用int()
age = input("how old are you?")
age = int(age)
#while循环
message = ''
while message !='quit':
message = input(prompt)
if message !='quit':
print(message)
# while循环处理列表和字典
unconfirmed_users = ['alice','brain','candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"verifying user:{current_user}")
confirmed_users.append(current_user)
#删除特定值
while 'alice' in unconfirmed_users:
unconfirmed_users.remove('alice')
#用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
name = input("what's your name?")
response = input("which mountain would you like to climb someday?")
responses[name] = response
repeat = input("would you want to let another person respond the question?")
if repeat = 'no':c
polling_active = False
for name,response in responses.items():
print(f"{name} would like to climb {respond}")
函数
#导入模块
import dictionary as p
#导入特定函数 用as设置别名
from dictionary import build_person as mp
# 导入模块中的所有函数
from list import buli
#函数中设置默认值
def build_person(first_name,last_name,age=None):
person = {'first':first_name,'last':last_name}
if age:
person['age'] = age
return person
build_person('jimi','hendrix',age=27)
#禁止函数修改列表,使用的是副本
upprined_designs=['phome','ddd']
completed_models = 2
build_person(upprined_designs[:],completed_models)
#传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
make_pizza('peeee','fff')
#使用任意数量的关键字实参 键值对
def build_perfile(first,last,**user_info):
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_info = build_perfile('alvert','einstein',
location='peicetoon',field='physics')
print(user_info)
类
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_desciptive_name(self):
return f"{self.make} {self.model} {self.year}"
def read_odometer(self):
print(f"this car has{self.odometer_reading} miles on it")
def update_odometer(self,mileage):
if mileage>=self.odometer_reading:
self.odometer_reading = mileage
else:
print("you cannot roll back an odometer")
def increment_odometer(self,miles):
self.odometer_reading+=miles
class electricCar(Car):
def __init__(self,make,model,year):
super.__init__(make,model,year)
self.battery_size = 5
self.battery = Car('bb','mmm',5)
my_resla = electricCar('bb','mmm',5)
my_resla.battery.get_desciptive_name() #将实例用作属性
从一个模块中导入多个类
from car import Car,ElectricCar
导入整个模块
import car
导入模块中所有的类
from model_name import *
json
json.jump()和json.load()
numbers = [1,2,3,4,5,6]
with open(filename,'w') as f:
json.dump(numbers,f)
json.load(f)