python作为一门编程语言,和其他编程语言类似,都是有自己的语法规则,编译器将按照语法规则编写的程序代码转换为计算机可识别的机器码,然后执行。
python的基本语法规则
- 代码逻辑通过缩进区分,一般都是使用4个空格进行缩进。缩进不能Tab键和空格混用,否则报错。
#号之后的语句都是注释,编译器将会忽略;其它每一行为一个语句;以:结尾的语句,其下面的缩进语句识别为代码块。- python大小写敏感。
运算符
数字运算符
数字运算符有+(加)-(减)*(乘)/(除)//(地板除)%(取余),其使用方法和数学中的一致。1
2
3
4
5
61+1
2
2-1
1
2*2
4
除法/的结果是浮点数,不论是否是整除。1
2
3
4
5
6
7
84/2
2.0
5/2
2.5
10/3
3.3333333333333335
11/6
1.8333333333333333
地板除//的结果是整数,不论是否可以除尽(只取整数部分,不是四舍五入)。1
2
3
4
5
6
7
84//2
2
5//2
2
10//3
3
11//6
1
取余%结果是两个整数相除的余数1
2
3
44%2
0
5%2
1
关系运算符
关系运算符主要有==(等于) !=(不等于) >大于() <(小于) >=(大于等于) <=(小于等于),其返回的结果是布尔值。1
2
3
4
5
65 == 1
False
5 != 1
True
5 > 1
True
赋值运算符
赋值运算符主要有= += -= *=。
赋值运算符=需要和前面关系运算符==区分,和数学中的表示方法有区别。
要对变量a赋值为1,则使用a = 1。a += b 等价于a = a + b;a -= b 等价于a = a - b;a *= b 等价于a = a * b。1
2
3
4
5
6
7
8
9
10a = 10
a += 1
print(a)
11
a -= 1
print(a)
10
a *= 2
print(a)
20
注意,python中对变量进行赋值不需要事先声明变量的类型,python会根据变量的值进行动态调整,所以python是动态语言,与之对应的就是静态语言,例如JAVA和C就是静态语言。1
2
3
4
5
6
7
8
9
10a = 1
print(a)
1
type(a)
<class 'int'>
>>> a = "111"
print(a)
111
type(a)
<class 'str'>
如上表示,变量a首先赋值为数字1,此时它是整型;再次给变量a赋值为字符串”111”,此时它变为字符串类型。
但C语言中当声明一个int类型的变量a时,赋值时只能为整型,若有其它类型将报错。
逻辑运算符
逻辑运算符有and(与)、or(或)、not(非)3种,它们用于布尔运算。and表示只有都为True,运算结果才是True。1
2
3
4
5
6True and True
True
True and False
False
False and False
False
or表示只要有一个为True,运算结果就是True。1
2
3
4
5
6True or True
True
True or False
True
False or False
False
not表示只有取反,True运算结果为False,False运算结果为True。1
2
3
4not True
False
not False
True
数据类型
整型 int
整数类型和数学上表示的一样,包括正整数、负整数和零等。
例如0,200,-200等都属于整型。
浮点型 float
浮点数类型就是数学中的小数。
例如2.11,-2.11,3.1415926等都属于小数。
布尔型 bool
布尔类型的值和布尔代数的一样有2种,分别是Ture,False。
布尔值可以通过布尔代数运算得到,也可以使用True和False表示。1
2
3
4
5
6
7
83 > 5
False
3 < 5
True
True
True
False
False
另外需要注意区分大小写,否则在python中将报错。1
2
3
4
5
6
7
8true
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
false
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined
字符串 str
在python中字符串可以使用'或"或'''括起来表示,但是推荐使用"表示。1
2
3
4
5
6
7
8
9b = 'zifuchuan'
type(b)
<class 'str'>
>>> c = "zifuchuan"
type(c)
<class 'str'>
>>> d = '''zifuchuan'''
type(d)
<class 'str'>
字符串中可能会包含很多的字符,此时如何处理呢?
当字符串中包含'时,使用"表示即可。
当字符串中包含特殊字符时,可以使用转义字符\处理,转义字符本身可以使用\\表示,其它的特殊字符有\n(换行符)、\t(制表符)等。1
2
3
4
5
6
7
8
9
10
11
12
13b = "I'm a superman"
print(b)
I'm a superman
>>> b = "I'm a \"superman\""
print(b)
I'm a "superman"
>>> b = "I'm \\a \"superman\""
print(b)
I'm \a "superman"
>>> b = "I'm \na \"superman\""
print(b)
I'm
a "superman"
前面有提到可以使用'''表示字符串,这样有啥好处呢?
当字符串有多行时,使用\n换行符表示会比较麻烦,此时可以使用'''表示多行。1
2
3
4
5
6
7
8
9print('''I'm
a
superman
!''')
I'm
a
superman
!
>>>
上面的...和>>>一样属于提示符,表示此时是接着上一行继续进行输入。
赋值字符串不仅仅是为了赋值,更多的为了对赋值的内容进行处理,在python中内置了很多的字符串处理函数,要了解具体有哪些可以通过在pycharm中定义一个字符串,然后通过str.方式查看。
介绍几个常用字符串方法
find()
检查字符串中是否包含子字符串,如果包含返回索引值(该子字符串在字符串中的起始位置),如果不包含返回-1。1
2
3
4
5
6
7str = "qwertq"
print(str.find('q')) #从下标0开始查找第一个出现的子字符串,返回结果0
0
print(str.find('a')) #查找不到返回-1
-1
print(str.find('q',1)) #从下标1开始查找第一个出现的子字符串,返回结果5
5
replace()
把字符串中的旧字符串替换成新字符串,返回生成的新字符串。1
2
3str = "qwertq"
print(str.replace('q','8'))
8wert8
split()
通过指定分隔符对字符串进行分割,返回分割后的字符串列表。1
2
3
4
5str = "I'm a superman !"
print(str.split( ))
["I'm", 'a', 'superman', '!']
print(str.split('a'))
["I'm ", ' superm', 'n !']
join()
将序列中的元素以指定的字符连接生成一个新的字符串,返回新生成的字符串。1
2
3
4
5
6
7
8str = "Iamasuperman"
print("-".join(str))
I-a-m-a-s-u-p-e-r-m-a-n
str1 = ("n","a","m","e")
print("-".join(str1))
n-a-m-e
print("".join(str1))
name
strip()
移除字符串头尾的字符(默认为空格),返回移除之后的新字符串。1
2
3
4
5
6str = " I'm a superman! "
print(str.strip())
I'm a superman!
>>> str1 = "####I'm a superman!#####"
print(str1.strip("#"))
I'm a superman!
format()
字符串格式化方法,使用传入的参数依次替换字符串中的{0}、{1}、{2}、{3}……、{n}。1
2"这是一只{0},{1}个月大,重{2}千克.".format("猫",5,2)
'这是一只猫,5个月大,重2千克.'
startswith()
检查字符串是否以指定的子字符串开头,如果是则返回True,否则返回False。1
2
3
4
5str = "I'm a superman!"
print(str.startswith("I'm"))
True
print(str.startswith("you're"))
False
endswith()
检查字符串是否以指定的子字符串结尾,如果是则返回True,否则返回False。1
2
3
4
5
6
7str = "I'm a superman!"
print(str.endswith("!"))
True
print(str.endswith("man!"))
True
print(str.endswith("man"))
False
列表 list
列表是一种有序的集合;可以把字符串、数字、字典等任何东西添加到序列,其中的元素无任何关系;列表中可以随时添加和删除元素;列表自带索引,默认从0开始。
列表的创建是将用,(逗号)分隔的不同项使用[](方括号)括起来。1
2
3list = [1,2,3,4,5]
list1 = ["I'm","a","superman","!"]
list2 = ["I'm",1,3,"wu"]
要访问列表中的元素,使用索引即可(索引从0开始)。 当索引超出范围时会报错。1
2
3
4
5
6
7
8
9list = [1,2,3,4,5]
list[0]
1
list[4]
5
list[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
访问列表中的最后一个元素可以使用-1,倒数第二个则是-2,以此类推。1
2
3
4
5
6
7list = [1,2,3,4,5]
list[-1]
5
list[-2]
4
list[-5]
1
下面介绍列表的常用方法
index()
列表中查找指定值第一个匹配的索引位置,若找到则返回查找对象的索引,否则抛出异常。1
2
3
4
5
6
7list = [1,2,3,4,5]
list.index(3)
2
list.index(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 6 is not in list
append()
添加元素至列表末尾。无返回值,但会修改列表。1
2
3
4list = [1,2,3,4,5]
list.append(6)
list
[1, 2, 3, 4, 5, 6]
pop()
删除列表中指定位置的元素,默认为末尾。返回删除的元素。1
2
3
4
5
6
7
8
9list = [1,2,3,4,5] #默认删除末尾元素
list.pop()
5
list
[1, 2, 3, 4]
list.pop(1) #删除指定位置的元素,该位置为索引位置
2
list
[1, 3, 4]
insert()
将指定的对象插入至列表指定的位置。无返回值,但会修改列表。1
2
3
4
5
6
7list = [1,2,3,4,5]
list.insert(1,8)
list
[1, 8, 2, 3, 4, 5]
list.insert(5,10)
list
[1, 8, 2, 3, 4, 10, 5]
remove()
移除列表中指定值的第一个匹配项。无返回值,但会修改列表。1
2
3
4
5
6
7
8list = [1,2,3,4,5]
list.remove(3)
list
[1, 2, 4, 5]
list1 = ["I'm", 'a', 'superman', '!']
list1.remove("a")
list1
["I'm", 'superman', '!']
reverse()
反向列表中的序列。无返回值,但会修改列表。1
2
3
4list = [1,2,3,4,5]
list.reverse()
list
[5, 4, 3, 2, 1]
sort()
对列表进行排序。无返回值,但会修改列表。1
2
3
4
5
6
7
8list = [1,2,3,4,5]
list.sort()
list
[1, 2, 3, 4, 5]
list1 = ["I'm","a","superman","!"]
list1.sort()
list1
['!', "I'm", 'a', 'superman']
元组 tuple
元组和列表类似,也是一种有序序列的集合,但是元组一旦初始化之后就不能修改。
元组的创建是将用,(逗号)分隔的不同项使用()(小括号)括起来。 元组创建的时候元素必须且已经定下来了。1
2
3
4
5
6
7
8t = (1,2,3,4,5)
t
(1, 2, 3, 4, 5)
t = ()
type(t)
<class 'tuple'>
>>> t
()
只含有1个元素的元组,创建的是时候需要加上,(逗号),否则创建的将不是元组。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15t=(1) #该情况下,`()`按照小括号计算
t
1
type(t)
<class 'int'>
>>> t=("1") #该情况下,`()`按照小括号计算
t
'1'
type(t)
<class 'str'>
>>> t=(1,) #该情况下,`()`表示元组
t
(1,)
type(t)
<class 'tuple'>
元组中元素的访问可以按照元素下标访问,也可以按照列表中的-1等访问元组中倒数的元素。
下面介绍列表中可用的方法
index()
查找指定元素在元组中的位置,返回指定元素的索引位置。1
2
3
4
5t = (1,2,3,4,5)
t.index(2)
1
t.index(5)
4
count()
统计元组中指定元素出现的个数。返回元素出现个数。1
2
3
4
5
6
7
8
9t = (1,2,3,4,3,4,3)
t.count('3') #元组中为整型,此处为字符串类型
0
t.count('4')
0
t.count(4) #元组中整数4出现的次数
2
t.count(3)
3