第二章 Python基本语法
2.1基本语法
1、#后的内容为注释
#第一个注释
print("hello world")#输出‘hello world’
2、python中有严格的缩进格式
python使用缩进表示代码块,最好使用4个空格进行悬挂式缩进;
if True:
print("True")
else:
print("False")
同一个代码块的语句必须要有相同的缩进空格数,否则会报错。
例:
if True:
print("Answer:")
print("True")
else:
print("Answer:")
print("False")
注意:在python中使用缩进时,绝对不要使用tab,也不要tab和空格混用。(书上是这么写的,但是我总是用tab,并不觉得有什么问题)
2.2变量与数据类型
2.3标识符和关键字
变量名、函数名都是标识符。
规则:
- 标识符由字母、下划线和数字组成,且不能由数字开头
- 标识符区分大小写
- 标识符不能使用关键字(如果大家想查看关键字,可以输入help()命令进入帮助系统查看实例如下)
>>>help() #进入帮助系统
help>keyword #查看所有的关键字列表
help>return #查看return这个关键字的说明
help>quit #退出帮助系统
2.4简单数值类型
1、整型
十进制
二进制:以“0B”或“0b"开头
八进制:以数字0开头
十六进制:以“0X”或“0x"开头
转换:
bin(20)#把十进制20转换二进制
oct(20)#把十进制20转为八进制
hex(20)#把十进制20转为十六进制
2、浮点型
表示实数。(遵循IEEE 754双精度标准 ,每个浮点数占八个字节 )
3、布尔类型
True和False
分别对应1和0
每个python天生具有布尔值
以下对象bool值为False:
- None
- False
- 0
- 0L
- 0.0
- 0.0+0.0j
- ""(空字符串)
- 空列表
- 空元组
- 空字典
3、复数类型‘
- 复数由实部和虚部构成,表示为real+imag j 或real+imag J
- 实部和虚部都是浮点型
‘4、数字类型转换
函数 | 说明 |
int() | 把x转换为整数 |
float() | 把x转换为浮点数 |
complex() | 创建一个复数 |
2.5运算符
1、算术运算符
运算符 | 相关描述 |
+ | 加 |
- | 减 |
* |
乘 或(返回一个被重复若干次的字符串 |
/ | 除(与c语言中不太一样)20/10=2.0 |
% | 取余 |
** | 幂 |
// | 与c语言中/用法相同 |
2、赋值运算符
只有一个,即=
在python中,可以为多个变量赋同一个值,还可以将多个值赋给多个变量
注意:python不支持C语言中的自增(++)和自减(--)操作符
3、比较运算符
运算符 |
== |
> |
< |
>= |
<= |
!= |
4、逻辑运算符
运算符 |
and |
or |
not |
5、成员运算符
运算符 |
in |
not in |
6、位运算符
运算符 | 说明 |
<< | 按位左移 左移n代表成2的n次方 |
>> | 按位右移 右移n表示除以2的n次方 |
& | 按位与 |
| | 按位或 |
^ | 按位异或 |
~ | 按位取反 |
ps:
7、运算符的优先级
运算符 | 描述 |
** | 指数(最高优先级) |
~+- | 按位取反,一元加号和减号(最后两个的方法名为+@和-@) |
* / % // | |
+- | 加法,减法 |
<< >> | |
& | |
^ | | |
<= < > >= | 比较运算符 |
== != | 等于运算符 |
= += | 赋值运算符,复合运算符 |
in not in | 成员运算符 |
or and | 逻辑运算符 |
笔记:
内置函数pow(2,4)与求幂运算符的区别
pow(2,4)=16.0
2**4=16
第三章python常用语句
3.1判断语句
1、if语句
注意:
- 每个if条件后要使用冒号(:),表示接下来是满足条件需要执行的语句
- 使用缩进来划分语句块,相同缩进数的语句在一起来组成一个语句块
- python中没有switch-case语句
2、if-else语句
3、if-elif语句
4、if嵌套
5、if案例——猜拳游戏
3.2循环语句
1、while循环‘
注意:python中没有do-while循环
2、for循环
for可以遍历任何序列(字符串,列表等)
3、while嵌套案例——九九乘法表
3.3python的其他语句
1、break
用于结束整个循环(当前循环体)
2、continue
用来结束本次循环,紧接着执行下一次循环
注意:
- break/continue只能用在循环中,不能单独使用
- break/continue在嵌套循环中只对最近的一层循环起作用
3、pass语句
为了保持程序结构的完整性,起占位的作用
4、else 语句
python中else语句还可以用在while和for后。在循环中使用时,else只在循环完成后执行,也就是说break也会跳过else语句块。
第四章字符串
4.1字符串介绍
1、什么是字符串
- 单引号包含字符
'a' '123'
- 双引号包含字符
"a" "123"
2、转义字符
4.2字符串的输入与输出
略
4.3访问字符串中的值
1、存储方式
name='abcdef'
2、使用切片截取字符串
指操作对象截取/其中一部分的操作。
切片的语法格式:[起始:结束:步长](注意切片选取的区间属于左闭右开型)
name='abcdef'
print(name[0:3]) #取下标为0~2的字符
print(name[3:5]) #取下标为3、4的字符
print(name[1:-1])#取下标为1到倒数第二个之间的字符
print(name[2:]) #取下标为2到结束的字符
print(name[::-2])#逆序,取步长为二的字符
4.4字符串内置函数
1、find
作用:查找字符串中在指定区间是否包含子串,若包含则返回子串在字符串中的位置,否则返回-1。
string = "hello world itheima and itheimaApp"
index1 = string.find("itheima")#没有指定区间则默认为整个字符串
index2 = string.find("itheima",0,30)
print(index1)
print(index2)
2、index
作用同find,区别是 当查找不到时,会报错而不是返回-1。
3、count
作用:统计字符串中指定区间某个字符出现的次数,返回次数。
string = "hello world itheima and itheimaApp"
index1 = string.count("itheima")#没有指定区间则默认为整个字符串
index2 = string.count("itheima",0,30)
print(index1)
print(index2)
4、replace
把字符串中的求字符串替换成新的字符串
string = "hello world itheima and itheimaApp"
index1 = string.replace("itheima",'miss',1)#将itheima用miss替换,最多一次
index2 = string.replace("itheima",'miss')#没有指定次数则默认为将整个字符串中所有旧的用新的替换
print(index1)#输出的是替换后的字符串
print(index2)
5、split
通过指定分隔符对字符串进行切片,处理过的字符串会变成列表(所有切片会变成元素)
string = "hello world itheima and itheimaApp"
string1 = string.split()#没有指定分隔符则默认为空格
string2 = string.split("itheima")
string3 = string.split(" ",2)#2为分割次数,没给出则表示分割所有
print(string1)
print(string2)
print(string3)
结果如下:
['hello', 'world', 'itheima', 'and', 'itheimaApp']
['hello world ', ' and ', 'App']
['hello', 'world', 'itheima and itheimaApp']
6、capitalize
将字符串的第一个字母变成大写,其他字母变成小写;会返回一个首字母大写的字符串。
7、title
标题化,就是将字符串中所有单词首字母大写。
8、startswith
用于检验在指定范围内字符串是否以指定字串开头,返回True或False。
string = "hello world itheima and itheimaApp"
index1 = string.startswith("hello",1,30)
index2 = string.startswith("hello")#没有指定区间则默认为整个字符串
print(index1)
print(index2)
9、endswith
用于检验在指定范围内字符串是否以指定字串结尾,返回True或False。
10、upper
将字符串中的小写字母转换为大写字母,返回转换过的字符串。
11、lower
将字符串中的大写字母转换为小写字母,返回转换过的字符串。
12、ljust
返回一个左对齐的并且以指定字符(默认为空格)填充至指定长度的字符串
13、rjust
返回一个右对齐的并且以指定字符(默认为空格)填充至指定长度的字符串
string = "hello world itheima and itheimaApp"
str1 = string.ljust(100,"*")
str2 = string.rjust(100)
print(str1)
print(str2)
hello world itheima and itheimaApp******************************************************************
hello world itheima and itheimaApp
14、 center
返回一个居中的并且以指定字符(默认为空格)填充至指定长度的字符串。
15、lstrip
用于删除字符串左边指定字符(默认空格),返回一个新字符串。
16、rstrip
用于删除字符串末尾指定字符(默认空格),返回一个新字符串。
string = " hello world itheima and itheimaApp"
str1 = string.lstrip()
str2 = string.rstrip("p")
print(str1)
print(str2)
hello world itheima and itheimaApp
hello world itheima and itheimaA
17、strip
用于截取字符串首尾指定字符(默认空格),返回一个新的字符串。
笔记:
内置函数 不用在变量后,可以直接使用
- ord(A)->65
- chr(65)->A
- len()
- str()
- type()
- oct()
- hex()
- dir() 显示函数
第五章列表、元组和字典
5.1概述
可以存储不同类型的数据。
5.2列表的循环遍历
1、for循环遍历列表
elems=['H','He','Li','Pi',]
for i in elems:
print(i)
H
He
Li
Pi
2、while循环遍历列表
elems=['H','He','Li','Pi',]
i=0
while i<4:
print(elems[i])
i+=1#记得这步,很容易忘记陷入死循环
H
He
Li
Pi
5.3列表的常见操作
1、在列表中增加元素
- append 向列表添加元素位于列表的末尾//栈
- extend 可以将一个列表中的元素全部添加到另一个列表//合并链表
list1 = [1,2,3,4]
list2 = [6,7]
list1.append(list2)
print(list1)
[1, 2, 3, 4, [6, 7]]
list1 = [1,2,3,4]
list2 = [6,7]
list1.extend(list2)
print(list1)
[1, 2, 3, 4, 6, 7]
- insert 向列表指定位置添加元素//插入
2、查找元素
利用in和not in
与循环语句结合
3、修改元素
通过下标可以修改列表中的元素
4、删除元素
- del 根据下标进行删除元素
movie = ['烈火英雄','哪吒之魔童降世','陈情令']
print(movie)
del movie[2]
print(movie)
['烈火英雄', '哪吒之魔童降世', '陈情令']
['烈火英雄', '哪吒之魔童降世']
- pop 可以删除列表中最后一个元素
movie = ['烈火英雄','哪吒之魔童降世','陈情令']
print(movie)
movie.pop()
print(movie)
['烈火英雄', '哪吒之魔童降世', '陈情令']
['烈火英雄', '哪吒之魔童降世']
- remove 根据元素的值进行删除
movie = ['烈火英雄','哪吒之魔童降世','陈情令']
print(movie)
movie.remove('烈火英雄')
print(movie)
['烈火英雄', '哪吒之魔童降世', '陈情令']
['哪吒之魔童降世', '陈情令']
ps:clear 清空列表
5.4列表的嵌套
案例——将8位老师随机分配到3个教师室
import random
offices= [[],[],[]]
names = ['A','B','C','D','E','F','G','H']
for name in names:
index = random.randint(0,2)
offices[index].append(name)
i=1
for temp in offices:
print('办公室%d的人数为:%d'%(i,len(temp)))
i+=1
for name in temp:
print("%s"%name,end=" ")
print(":)"*20)
5.5元组
元组最大的特点就是不可修改
这也是它与列表的最大区别!
元组的内置函数:
方法 | 描述 |
len(tuple) | 计算元组的元素个数 |
max(tuple) | 返回元组中的最大值 |
min(tuple) | 返回元组中的最小值 |
tuple(list) | 将列表转换成元组 |
5.6字典
- 可以以键来访问修改值
- 通过给新定义的键赋值来添加键值对
- 用del语句删除元素 clear语句清空字典
- 获取键视图keys()
- 获取值视图values()
- 获取元素视图items()