目录
注释规范
单行注释
- 在代码上方添加:#空格注释内容
- 在代码后面添加:先打至少两个空格#空格注释内容
多行注释
- 连续敲三个双引号
输出
message = "hello word"
print(message)
字符串
字符串可以用单引号也可以用双引号表示
修改大小写
m = "hello woRd"
# 首字母大写
print(m.title())
# 全部大写
print(m.upper())
# 全部小写
print(m.lower())
合并(拼接)字符串
加号连接
a = 'hello'
b = 'world'
c = a + b
print(c)
print(a + b + '!')
添加制表符或换行符
- 制表符:\t
- 换行符:\n
a = 'hello'
b = '\nworld'
c = '\tgood'
d = '\n\twonderful'
print(a + b + c + d)
删除空白
- 去掉全部:strip()
- 去掉左面:lstrip()
- 去掉右面:rstrip()
a = ' python '
print('原:' + a + '1')
# 去掉左面
print('左:' + a.lstrip() + '1')
# 去掉右面
print('右:' + a.rstrip() + '1')
# 去掉所有
print('all:' + a.strip() + '1')
数字转换字符串
a = 13
b = 'hello'
print(b + str(a))
算数运算符
运算符 | 描述 |
+ | 加 |
- | 减 |
* | 乘 |
/ | 除 |
// | 取整除 |
% | 取余数 |
** | 幂 |
“ * ”还可以用来指定字符串重复次数
列表
- 可以存不同类型的数据,方括号([ ])表示,逗号分开
- 索引是从0开始的
输出列表及列表元素
输出整个列表的时候是列表,单个输出才是一个
food = ['ice-cream', 'milk', 'apple', 'hotpot']
# 输出列表
print(food)
# 输出列表第二个元素
print(food[1])
# 把第2个元素首字母大写输出
print(food[1].title())
# 取元素索引
print(food.index("milk"))
修改、添加、删除元素
修改
food = ['ice-cream', 'milk', 'apple', 'hotpot']
# 修改元素 直接修改值就可以
food[3] = "tea"
print(food)
添加
food = ['ice-cream', 'milk', 'apple', 'hotpot']
fruit = ['orange', 'strawberry']
# append()方法在列表末尾添加元素
food.append('cake')
print(food)
# insert()在指定位置加入元素
food.insert(2, 'croissante')
print(food)
# extend()把其他列表的内容添加到末尾
food.extend(fruit)
print(food)
删除
food = ['ice-cream', 'milk', 'apple', 'hotpot', 'orange', 'tea']
print(food)
# pop()弹出元素,默认最后一个,也可以指定元素
# 弹出后可以存到别的变量中接着使用
a = food.pop()
print(food)
print(a)
# remove()通过列表中元素值删除元素,也可以存到别的变量中继续用
# 通过这种方法删除,要把值存到变量里
b = 'hotpot'
c = food.remove(b)
print(food)
# del通过元素的位置删除元素,是不可逆的,从内存中删除,后续不可以使用
del food[0]
print(food)
# clear()清空列表
print(food.clear())
统计元素出现的次数
food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
print(food)
# count()统计元素出现的次数
print(food.count("milk"))
排序
sorted()对列表进行临时排序
food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
print(food)
# sorted()对列表进行临时排序
# 升序
print(sorted(food))
# 降序
print(sorted(food,reverse=True))
# 原列表顺序不变
print(food)
sort()对列表进行永久性排序
food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
print(food)
# sort()对列表进行永久排序,原列表顺序也发生变化
# 升序
food.sort()
print(food)
# 降序
food.sort(reverse=True)
print(food)
对列表进行逆序(反转)
food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
# 逆序
food.reverse()
print(food)
列表长度
food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
# 列表长度
print(len(food))
for循环列表
foods = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
for food in foods:
print(food)
注意:在Python中是用缩进表示大括号的!!不要忘记冒号!!
创建数值列表
range()函数
range(i,j)函数可以生成 i——j-1的连续数字,输出的值不能超过j
for i in range(1, 5):
print(i)
使用range()创建数字列表
函数list()可以将range()的结果值转换成列表
nl = list(range(1, 6))
print(nl)
range()函数指定步长
# 从2开始,到10结束,步长是2
nl = list(range(2, 11, 2))
print(nl)
求1-10平方
squares = []
for value in range(1, 11):
squares.append(value ** 2)
print(squares)
对列表求最大值、最小值、总和
digits = [9,5,3,2,1,4,8,6]
print(min(digits))
print(max(digits))
print(sum(digits))
列表解析
将整个for循环合并成一行
求1-10平方的另一种写法
squares = [value ** 2 for value in range(1, 11)]
print(squares)
使用列表的一部分
切片
foods = ['banana', 'apple', 'milk', 'tea', 'meat', 'hotpot']
# 指定位置进行切片操作
# foods[i:j],注意:i和j是列表的下标,从下标i开始,j-1结束
print(foods[0:3])
print(foods[1:4])
# 从头开始切片
print(foods[:5])
# 切片终止于列表末尾
print(foods[3:])
# 取列表最后几个元素,注意:负数索引可以返回离列表末尾相应距离的元素
print(foods[-3:])
遍历切片
foods = ['banana', 'apple', 'milk', 'tea', 'meat', 'hotpot']
# 遍历切片
for food in foods[1:4]:
print(food)
复制列表
foods = ['banana', 'apple', 'milk', 'tea', 'meat', 'hotpot']
# 复制列表
new_foods = foods[:]
print(foods)
print(new_foods)
元组
元组与列表相似,使用的是圆括号,元素不可以修改,通常保存不同类型的元素
new_tuple = ("张", 18, 1.60, "张")
# 取值和取索引
print(new_tuple[0])
print(new_tuple.index("张"))
# 统计元素的个数
print(new_tuple.count('张'))
# 获取元组长度
print(len(new_tuple))
# 遍历元组
for value in new_tuple:
print(value)
# 元组和列表可以相互转换
new_list = ['food', 'water', 'milk']
print(list(new_tuple))
print(tuple(new_list))
if 语句
比较
不要忘记冒号!!!
num = 18
if num != 30:
print('erro')
逻辑运算
and、or、not
检查值在不在列表中
foods = ['water', 'lake', 'milk']
if 'apple' not in foods:
print('not')
if-else语句
num = 18
if num > 18:
print('over')
else:
print("oui")
if-elif-else结构
else也可以省略掉
num = 18
if num > 18:
print('over')
elif num == 18:
print("oui")
elif num <18:
print(3)
else:
print(4)
字典
通过键值对表示的,键(key)是唯一的
基础
apple = {
'name' : 'apple',
'color' : 'red',
'point' : 'grand'
}
# 取值
print(apple['name'])
# 修改
apple['color'] = 'green'
print(apple)
# 增加
apple['age'] = 3
print(apple)
# 删除
apple.pop('name')
print(apple)
# 统计键值对数量
print(len(apple))
# 合并字典
# 如果被合并的字典中包含已经存在的键值对,会覆盖掉原来的
extra_apple = {'position' : 'west'}
apple.update(extra_apple)
print(apple)
# 循环遍历
# items()方法返回键值对列表
for k,v in apple.items():
print(k , v)
# keys()方法返回键
for k in apple.keys():
print(k)
# values()方法遍历值
for v in apple.values():
print(v)
嵌套
字典列表
apple1 = {'color': 'red', 'mature': 'oui'}
apple2 = {'color': 'green', 'mature': 'non'}
apple3 = {'color': 'yellow', 'mature': 'non'}
apples = [apple1, apple2, apple3]
for apple in apples:
print(apple)
也可以用切片的方式输出
apple1 = {'color': 'red', 'mature': 'oui'}
apple2 = {'color': 'green', 'mature': 'non'}
apple3 = {'color': 'yellow', 'mature': 'non'}
apples = [apple1, apple2, apple3]
for apple in apples[:2]:
print(apple)
在字典中存列表
apples = {'apple1': ['red', 'mature'],
'apple2': ['green', 'pure'],
'apple3':['yellow', 'mature']}
for apple, characters in apples.items():
print(apple)
for character in characters:
print("\t" + character)
在字典中存字典
这种情况就比如存用户的信息
users = {
'andy': {
'age': 18,
'sex': 'f'
},
'bob': {
'age': 20,
'sex': 'm'
}
}
for user, infos in users.items():
print(user)
print('\t', infos['age'])
用户输入和while循环
input()函数
# 普通
food = input("what's your favorite food?")
print(food)
# 使用int()来获取数值输入
age = input("How are you?\n")
age = int(age)
if age > 0:
print(age)
while循环
# 输出偶数
num = 0
while num <= 10:
if num == 8:
break # break跳出循环
elif num % 2 != 0:
num += 1
continue # continue跳出本次循环进行下一次
elif num % 2 == 0:
print(num)
num += 1
函数
# 传任意数量的实参
# *创建元组
def foods(num, *food):
print(num)
print(food)
foods(3, "apple", 'hotpot', 'milk')
# **创建字典
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)