Python快速版

目录

注释规范

单行注释

多行注释

输出

字符串

修改大小写

合并(拼接)字符串

添加制表符或换行符

删除空白

数字转换字符串

算数运算符

列表

输出列表及列表元素

​编辑修改、添加、删除元素

统计元素出现的次数

排序

列表长度

for循环列表

创建数值列表

range()函数

使用range()创建数字列表

range()函数指定步长

求1-10平方

对列表求最大值、最小值、总和

列表解析

使用列表的一部分

切片

遍历切片 

复制列表

元组

if 语句

比较

逻辑运算

检查值在不在列表中

if-else语句

if-elif-else结构

字典

基础

嵌套

用户输入和while循环

input()函数

while循环

函数


注释规范

单行注释

  • 在代码上方添加:#空格注释内容
  • 在代码后面添加:先打至少两个空格#空格注释内容

多行注释

  • 连续敲三个双引号

e078d5d314584f7b848ea9151cee884b.png


输出

message = "hello word"
print(message)

字符串

字符串可以用单引号也可以用双引号表示

修改大小写

m = "hello woRd"
# 首字母大写
print(m.title())
# 全部大写
print(m.upper())
# 全部小写
print(m.lower())

8ef8ae1bf1dc4494a532a83a12cbf0cd.png

合并(拼接)字符串

加号连接

a = 'hello'
b = 'world'
c = a + b
print(c)
print(a + b + '!')

97e4b35fcb5f48f8a456a54b28bbb31c.png

添加制表符或换行符

  • 制表符:\t
  • 换行符:\n
a = 'hello'
b = '\nworld'
c = '\tgood'
d = '\n\twonderful'
print(a + b + c + d)

b5d1ab24883b4866b378e78daf47724f.png

删除空白

  • 去掉全部:strip()
  • 去掉左面:lstrip()
  • 去掉右面:rstrip()
a = '  python   '
print('原:' + a + '1')
# 去掉左面
print('左:' + a.lstrip() + '1')
# 去掉右面
print('右:' + a.rstrip() + '1')
# 去掉所有
print('all:' + a.strip() + '1')

297de21a00f74073aa7904b09a7249f7.png

数字转换字符串

a = 13
b = 'hello'
print(b + str(a))

e403ba1a67d041068ef2196177a4c30f.png


算数运算符

运算符描述
+
-
*
/
//取整除
%取余数
**

“ * ”还可以用来指定字符串重复次数


列表

  • 可以存不同类型的数据,方括号([ ])表示,逗号分开
  • 索引是从0开始的

输出列表及列表元素

输出整个列表的时候是列表,单个输出才是一个 

food = ['ice-cream', 'milk', 'apple', 'hotpot']
# 输出列表
print(food)
# 输出列表第二个元素
print(food[1])
# 把第2个元素首字母大写输出
print(food[1].title())
# 取元素索引
print(food.index("milk"))

e23a74a7324d4266b81042bb3022d2bd.png修改、添加、删除元素

修改

food = ['ice-cream', 'milk', 'apple', 'hotpot']
# 修改元素 直接修改值就可以
food[3] = "tea"
print(food)

eac98b9da1dc4d82b48b5da6de36648c.png

添加

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)

8063c25945034c029ec7fd5c7d073e64.png

删除

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())

edaf15b0129b4e928400a648f9af8ba3.png

统计元素出现的次数

food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
print(food)
# count()统计元素出现的次数
print(food.count("milk"))

eab0364673d9421991955854363ed95a.png

排序

sorted()对列表进行临时排序

food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
print(food)
# sorted()对列表进行临时排序
# 升序
print(sorted(food))
# 降序
print(sorted(food,reverse=True))
# 原列表顺序不变
print(food)

4308847a9967446ab3c86803092a4198.png

sort()对列表进行永久性排序

food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
print(food)
# sort()对列表进行永久排序,原列表顺序也发生变化
# 升序
food.sort()
print(food)
# 降序
food.sort(reverse=True)
print(food)

937018a3ffe1497eadb7c03c7b81d13c.png

对列表进行逆序(反转)

food = ['ice-cream', 'milk', 'apple', 'hotpot', 'milk', 'tea']
# 逆序
food.reverse()
print(food)

6334e8fd51b947fd9be4b2159d1ae58d.png

列表长度

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)

9a46ffb4e18641b7bbadaf570674ef7a.png

注意:在Python中是用缩进表示大括号的!!不要忘记冒号!!


创建数值列表

range()函数

range(i,j)函数可以生成 i——j-1的连续数字,输出的值不能超过j

for i in range(1, 5):
    print(i)

490cd40a9aba47f5b9cc83650bebe4d0.png

使用range()创建数字列表

函数list()可以将range()的结果值转换成列表

nl = list(range(1, 6))
print(nl)

61abc75a4d464c77b8046aff97569d41.png

range()函数指定步长

# 从2开始,到10结束,步长是2
nl = list(range(2, 11, 2))
print(nl)

11f7e2e438b14d019e9888eadb309cd5.png

求1-10平方

squares = []
for value in range(1, 11):
    squares.append(value ** 2)
print(squares)

275fe797a58d45eda339bd4a10833689.png

对列表求最大值、最小值、总和

digits = [9,5,3,2,1,4,8,6]
print(min(digits))
print(max(digits))
print(sum(digits))

e92ece25ec4c4a12bbd6e2e05d089808.png

列表解析

将整个for循环合并成一行

求1-10平方的另一种写法

squares = [value ** 2 for value in range(1, 11)]
print(squares)

8b7182dae78b4835be589be5c27f0d84.png

使用列表的一部分

切片

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:])

09e9c43b024c4ec98ec0d8a5dce2d955.png

遍历切片 

foods = ['banana', 'apple', 'milk', 'tea', 'meat', 'hotpot']
# 遍历切片
for food in foods[1:4]:
    print(food)

4b5f05efc85a4394872c8c60f43b1a9b.png

复制列表

foods = ['banana', 'apple', 'milk', 'tea', 'meat', 'hotpot']
# 复制列表
new_foods = foods[:]
print(foods)
print(new_foods)

6ecf92550e6d4300813f54ab698c024d.png

元组

元组与列表相似,使用的是圆括号元素不可以修改,通常保存不同类型的元素

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))

c3e6848ef9ce4d44992edd11b1fdbaca.png


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)

3400ee26311d48bea9f57b4abc6476ac.png

也可以用切片的方式输出

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)

f1c35fb272d0443788c5a99dd1051ba7.png

 在字典中存字典

这种情况就比如存用户的信息

users = {
    'andy': {
        'age': 18,
        'sex': 'f'
    },
    'bob': {
        'age': 20,
        'sex': 'm'
    }
}
for user, infos in users.items():
    print(user)
    print('\t', infos['age'])

7db26db836774347a160428e30e4f060.png


用户输入和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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值