变量和数据类型
注释
- 单行注释:
- 多行注释:单引号或双引号
print('这是执行内容')'''print('这是多行注释')'''# print('这是单行注释')
变量
- 变量:内存中存储数据的空间命名
- 定义变量:变量 = 值
- 标识符命名规则:
- 由数字、字母、下划线组成
- 不能以数字开头
- 不能使用关键字
- 严格区分大小写
'''1.由数字 字母 下划线 组成2.不能有数字开头3.不能是关键字4.严格区分大小写'''str = 'hello world'print(str)
数据类型
- 使用type函数可以得到传入参数的数据类型作为返回值
- 数值型
- int:整型
- float:浮点型
- 字符串 - str
- 布尔型 - bool
- 列表 - list
- 元组 - tuple
- 集合 - set
- 字典 - dict
'''1. 数值型int:整型float:浮点型2. 字符串 - str3. 布尔型 - bool4. 列表 - list5. 元组 - tuple6. 集合 - set7. 字典 - dict使用type函数作用:得到传入参数的数据类型参数:数据返回值:数据类型'''num1 = 1num2 = 1.1str = 'hi'boolean = Truelis = [1,2,3,4]tup = (1,2,3)st = {1,2,3}dic = {'name':'z3','age':18}print(type(num1))print(type(num2))print(type(str))print(type(boolean))print(type(lis))print(type(tup))print(type(st))print(type(dic))
格式化输出
| 常用格式化符号 | 含义 |
|---|---|
| %s | 字符串内容 |
| %d | 具有符号的十进制整型 |
| %f | 浮点型 |
| %u | 不具有符号的十进制整型 |
- 格式化符号
- f格式化字符串 - f’{表达式}’
'''1. %s - 字符串2. %d - 具有符号的十进制整型%03d - 表示显示三位数,不够的用0补上,超出则忽略3. %f - 浮点型%.xf - 表示保留x位小数'''name = 'z3'age = 18stu_id = 1weight = 75.5# 我叫x,今年x岁,明年n岁print('我叫%s,今年%d岁,明年%d岁,我的学号是%03d,我的体重是%.2f' % (name,age,age+1,stu_id,weight))# 输出多个数据时,用元组表示# %s - 可以作为其他类型的格式化符号print('我叫%s,今年%s岁,明年%s岁,我的学号是%s,我的体重是%s' % (name,age,age+1,stu_id,weight))# f'{}'print(f'我叫{name},今年{age}岁,明年{age+1}岁,我的学号是{stu_id},我的体重是{weight}')
转义字符
- \n:换行
- \t:制表符 - 4个空格 - 1个tab
- print默认尾部自带 end = ‘\n’,所以会自动换行
'''1. \n - 换行2. \t - 制表符 = 4个空格 = 1个tab3. print默认尾部自带结束符号 - end = '\n' 可以自定义'''print('hello\nworld')print('hello')print('\thello')print('hello',end ='\t')print('world')
数据类型转换+运算符
input
- input可以接收用户输入的数据作为返回值
- 特点
- 程序遇到input时会暂停执行,等待用户输入
- 可以使用变量接收用户输入的数据
- input默认会把输入的数据定义为字符串类型
'''1. 程序遇到input时会暂定执行,等待用户输入2. 可以使用变量接收input接收到的用户输入的内容3. input接收到的用户输入的内容都会以字符串类型返回'''password = input('请输入您的密码:') # 提示信息print(password)print(type(password))
数据类型转换
| 函数 | 说明 |
|---|---|
| int[x[base]] | 将x转为整数 |
| float(x) | 将x转为浮点数 |
| str(x) | 将对象转为字符串 |
| eval(str) | 用来计算字符串中有效python表达式,并返回一个对象 |
| tuple(s) | 将序列s转换为一个元组 |
| list(s) | 将序列s转换为一个列表 |
'''1. int - 将参数转为整型2. float() - 将参数转为浮点型3. str() - 将参数转为字符串4. list() - 将序列转为列表5. tuple() - 将序列转为元组6. eval() - 根据其python有效内容转为对应的类型'''num1 = 1num2 = 1.1str1 = '10'print(type(int(str1)))print(type(float(str1)))print(type(str(num1)))lis = [1,2,3,4]print(type(tuple(lis)))tup = (1,2,3,4)print(type(list(tup)))# evalstr2 = '1'str3 = '1.1'str4 = '(1,2,3,4)'str5 = '[1,2,3,4]'print(type(eval(str2)))print(type(eval(str3)))print(type(eval(str4)))print(type(eval(str5)))
运算符
- 算术运算符
- 赋值运算符
- 复合赋值运算符
- 比较运算符
- 逻辑运算符
算术运算符
- +:加
- -:减
- *:乘
- /:除
- //:整除 - 9//4 = 2
- %:取余
- **:指数
():小括号,提高优先级
优先级
() > * > / // % > + -
'''+ 加法- 减法* 乘法/ 除法// 整除% 取模** 指数() 提高优先级'''print(1+1)print(1-1)print(2*3)print(5/4)print(5//4)print(5%4)print(2**3)
赋值运算符
- = :赋值 —-> 变量 = 值
- 多个变量赋值
- 多个变量赋相同值
'''1. 单个变量赋值 num = 12. 多个变量赋值 num1,num2 = 1,23. 多个变量赋相同值 num1 = num2 = 1'''num = 1print(num)num1,num2 = 1,2print(num1,num2)str1 = str2 = 'hello'print(str1,str2)
复合赋值运算符
- 优先级低于算术运算符
- +=
- -=
- *=
- /=
- //=
- %=
- **=
# 复合赋值运算符 c += a ==》 c = c + ac=1a=2c+=aprint(c)# 优先级低于算术运算符# 执行流程:先算算术运算符部分,再算复合赋值运算符部分 ==》 10*=3b=10b*=2+1print(b)
比较运算符
- 不同数据类型不能使用> < >= <= 这些运算符
- ==
- !=
- >
- <
=
- <=
a=1b='1'print(a==b)print(a>=b)# 会报错:TypeError: '>=' not supported between instances of 'int' and 'str'
逻辑元素符
- 具有短路效应
- and - &&
- or - ||
- not - !
'''1. and - &&2. or - ||3. not - !'''a=1b=2c=3print((a>b) and (a>c))print((a<b) or (a>c))print(not (a>b))# 短路效应# 返回第一个非零数字 - 找Falseprint(0 and 1)print(1 and 2)# 返回最后一个非零数字 - 找Trueprint(0 or 1)print(1 or 2)
if语句
if语句
if 条件:条件成立执行的代码1条件成立执行的代码2...# if体验age = input('请输入你的年龄:')age = int(age)if age > 18:print(f'你的年龄{age}岁,你可以上网')
if…else…
if 条件:条件成立执行...else:if条件不成立执行...# 网吧上网demoif age >= 18:print(f'You are {age} years old,you can go to the internet cafe')else:print(f'You are {age} years old,you can not go to the internet cafe')
多重判断 - if…elif…else…
# 判断年龄:18岁以下不能工作 - 18到60岁可工作 - 60岁以上需要退休age = int(input('Please input your age:'))if age < 18:print(f'You are {age} years old, you can not work')# 化简# elif (age >= 18) and (age <= 60):elif 18 <= age <= 60:print(f'You are {age} years old, you can work')else:print(f'You are {age} years old, you need to retire')
if嵌套
# 1.有钱能上车# 2.有坐位可以坐下if True:print('有钱')if True:print('有空座位')
三目运算符
- 以if为分界线:if后面的内容为真执行if前面的语句,否则执行else后面的语句
while循环
while 条件:条件成立执行语句...import randomnum = random.randint(0, 99)while num != 50:print(f'{int}')num = random.randint(0, 99)
break continue
- break:退出整个循环
- continue:退出当前一轮循环
- 在continue需要修改计数器,否则容易进入死循环
for循环
for 临时变量 in iterable序列:重复执行的代码1string = 'hello'for i in string:print(i)
for…else…
- else语句执行的情况
- continue和正常结束时执行
- break退出循环时不执行
for 临时变量 in iterable序列:重复执行的代码1...else:循环正常结束时执行
字符串str - 不可变类型
下标
- 下标从0开始
- string[x]:x表示下标,从0开始
切片

- 截取一段数据的操作
- 语法:[开始位置下标:结束位置下标:步长]
- 不包含结束位置下标对应的数据,正负整数均可
- 步长是选取间隔,正负整数均可,默认为1,可省略
- 步长
- 正数:从左往右选
- 负数:从右往左选
- 注意:如果选取方向和步长方向相反,则选取不到任何数据
string = '0123456789'print(string[0:7:2])print(string[0:7])print(string[:7])print(string[::])print(string[-1:-3:-1])
方法
查找子串
- len(str):返回字符串长度
- str.find(‘substr’,起始位置,结束位置):找到返回第一次找到的开始位置,否则返回-1
- str.index(‘substr’,起始位置,结束位置):找到返回第一次找到的开始位置,否则报错
- rfind
- rindex
- str.count(‘substr’,起始位置,结束位置):返回查询到的字数,没有返回0
mystr = 'hello world and python and javascript and react and vue'print(mystr.find('and'))print(mystr.find('and', 20, 40))print(mystr.find('ands'))print(mystr.rfind('and'))print(mystr.index('and'))print(mystr.rindex('and'))# print(mystr.index('ands'))print(mystr.count('and'))print(len(mystr))
修改
- str.replace(旧子串,新子串,替换次数)
- str.split(分割的子串,分割次数)
- ‘符号or子串’.join(多个字符串组成的序列)
'''1. replace2. split3. join'''mystr = 'hello world and python and javascript and react and vue'print(mystr.replace('and', 'or'))print(mystr.replace('and', 'or', 2))new_str1 = print(mystr.split('and'))new_str2 = print(mystr.split('and', 2)) # 砍两刀lis = ['aa', 'bb', 'cc']print('..'.join(lis))print('___'.join(lis))
大小写转换
- str.capitalize():首字符变大写
- str.title():每个单词首字母变大写
- str.lower():大写变小写
- str.upper():小写变大写
'''1. capitalize2. title3. lower4. upper'''mystr = 'hello and hi'MYSTR = 'HELLO AND HI'# new_str = mystr.capitalize() # Hello and hi# new_str = mystr.title() # Hello And Hi# new_str = MYSTR.lower() # hello and hinew_str = mystr.upper() # HELLO AND HIprint(new_str)
strip删除空白
- strip:删除两侧空白
- lstrip:删除左侧空白
- rstrip:删除右侧空白
'''1. strip2. lstrip3. rstrip'''mystr = ' hello and hi 'print(mystr.strip())print(mystr.lstrip())print(mystr.rstrip())
just对齐
- ljust:左对齐
- rjust:右对齐
- center:居中对齐
'''1. ljust2. rjust3. center'''mystr = 'hello'print(mystr.ljust(10, '.'))print(mystr.rjust(10, '/'))print(mystr.center(11))
startwith - endwith
- startwith:以。。。开头
- endwith:以。。。结尾
'''1. startwith2. endwith'''mystr = 'hello'print(mystr.startswith('he'))print(mystr.endswith('lo'))
判断字符串成分
- isalpha:都是字母
- isdigit:都是数字
- isalnum:数字+字母
- isspace:都是空格
'''1, isalpha - 都是字母2. isdigit - 都是数字3. isalnum - 字母+数字4. isspace - 都是空格'''str1 = 'hello'str2 = '123'str3 = 'abc123'str4 = ' 'print(str1.isalpha())print(str2.isdigit())print(str3.isalnum())print(str4.isspace())
列表 - 可变数据
- 一个列表可以存储多个数据,且数据类型可以不同,但是规范化需求存储相同类型
下标
- 从0开始
方法
查找
- index:返回索引值
- count:返回出现的次数
判断是否存在 - 公共操作
- in
- not in
增加数据
- append:在末尾添加
- insert:在任意位置添加
'''1. append - 在末尾添加,如果参数为序列,则将序列整体插入2. extend - 在末尾添加,如果参数是序列,会将序列拆开添加3. insert - 插入指定位置'''lis = ['tom', 'jerry']lis.append(['red'])print(lis)lis.extend(['red'])print(lis)lis.insert(1, 'red')print(lis)
删除数据
- del
- pop
- remove
- clear
'''1. del - 参数为列表或列表某个元素- 可以阐述整个列表- 可以删除指定下标位置元素2. pop - 返回被删除的元素,参数为索引- 可以删除指定位置的元素- 默认删除最后一个元素3. remove - 删除指定元素,返回值为None- 参数为元素4. clear - 清空列表'''lis = ['tom', 'jerry', 'red']del_name = ''# del lis[0]# del lis# del_name = lis.pop() # red# del_name = lis.pop(1) # jerry# lis.remove(lis[1])# lis.clear() # []print(lis)print(del_name)
修改
- reverse
- sort
'''1. 通过下标修改数据2. reverse - 翻转list3. sort(key=None, reverse = bool) - 对list进行排序- True降序- False降序'''num_lis = [1, 2, 3, 4, 5, 9]num_lis.reverse()print(num_lis)num_lis.sort()print(num_lis)
列表复制
- copy
'''1. copy - 复制'''num_lis = [1, 2, 3, 4, 5, 9]new_lis = num_lis.copy()print(new_lis)
