一、变量
1. 变量是标签,注意命名规则:①下划线、字母、数字组成 ②数字不能开头
2. 字符串变量,有很多函数,本身不会改变具有返回值。如title()、upper()、lower()、rstrip()、lstrip()、strip().
3. f 字符串:在字符串中使用变量,f"{ }"
二、运算
1. 加(+)、减(-)、乘(*)、除(/)、乘方(**)、求模(%)
2. 浮点数参与运算小数位数可能是不确定的,两数相除结果总是浮点数,若一个操作数是浮点数结果也是浮点数
3. 大数可使用下划线将数字分组
三、列表
1. 增:append('变量') 在末尾增加;insert('索引')
2. 删:del 索引直接删除;pop() 将最后一个弹出去;remove('变量')
3. 永久排序:sort([reverse=True])、reverse()
4. 临时排序:sorted()
5. 获取长度:len()
6. 遍历:for i in range(1,6) <左闭右开>
for square in squares:
squares = [value**2 for value in range(1,6)]
7. 创建:numbers = list(range(1,6)) 等价于 numbers = [ ]
8. 切片:squares[1:11:2] <左闭右开,步长>
squares[:] <相当于复制作用>
四、元组
定义:dimensions = (8, )
五、条件、选择、判断
1. if、elif、else
2. ==、!=、<、>、in、not in、and、or、True、False
3. while、break、continue
六、字典
1. alien = {'color': 'green','points': 5}、 .get('key') 获取值、 del 删除
2. for key, value in names.items():
for key in names.keys() 等价于 for key in names
for value in names.values()
3. 嵌套
列表[字典1,字典2,...]
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)
字典{'key': '[value1,value2,...]'}
favorite_languages = {
'jen': ['python','ruby'],
'sarah': ['c'],
'edward': ['ruby','go'],
'phil': ['python','haskell']
}
for name,languages in favorite_languages.items():
for language in languages:
字典 {'key1': {}
'key2': {}
'key3': {}
...
}
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton'
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
}
}
for username, user_info in users.items():
location = user_info['location']
七、集合
set(),{}
八、函数
1. 输入:message = input(' ') <输入字符串>
2. 位置实参、关键字实参
def make(* topping) -------任意数量实参,封装成元组
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
---------------------------------------------------------
('pepperoni',)
('mushrooms','green peppers','extra cheese')
def build-profile(first, last, **user_info) --------user_info空字典,接收任意键值对
def build_profile(first,last,**user_info):
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
---------------------------------------------------------------------------------------
{'location':'princeton', 'field':'physics',
'first_name':'albert', 'last_name':'einstein'}
3. import model_name
from model_name import function_name
from model_name import function_name as fn
4. 类:def __init__():
子类:def __init__():
super().__init__()
self.battery = Battery()
九、文件
with open('filename') as file_object:
lines = file_object.readlines()