【Python基础】Python基础语法14个知识点大串讲
Python基础语法大串讲
1、print 函数
print('hello')
print('world!')
print('hello',end='')
print('world!')
2、变量与基本数据类型
int_var = 2
float_var = 3.13
str_var = 'hello'
3、标识符
# 正确标识符
a_1 = 1
#错误标识符
1_a = 1
#直接使用中文标识符
变量1 = 5
print(变量1)
4、保留字
5、数据类型
数字数据类型
var1 = 2 + 1.2j
var2 = complex(2,1.2)
布尔类型
T = True
F = False
6、基本运算
算数运算
比较运算
赋值运算
逻辑运算
7、List 列表
List 列表介绍
list1 = [1,2,3,'hello',[4,5,6]]
print(list1)
列表元素访问
list2 = [1,2,3,4,5,6]
list2[0] #1
list2[-1] #6
list2[6] #访问越界!!
list3 = [1,2,3,4,5,6]
list3[0:3] #[1,2,3]
list3[::2] #[1,3,5]
8、Tuple 元组
tuple1 = (1,2,3,'hello',[4,5,6],(7,8,9))
print(tuple1)
tuple2 = (1,2,3,'hello',[4,5,6],(7,8,9))
print(tuple1[0]) #1
print(tuple1[-1]) #(7,8,9)
print(tuple1[-1][-1]) #9
9、Set 集合
set1 = {1,2,2,3}
print(set1)
set2 = {1,2,3}
set3 = {2,3,4}
3 in set2 #True
4 in set2 #False
set2 | set3 #{1,2,3,4,5}
set2 & set3 #{2}
10、Dictionary 字典
dict1 = {'name':'a','height':170,'weight':60}
dict1['height'] #170
dict1.keys() #['name','height','weight']
dict1.values() #['a',170,60]
dict1.clear() #{}
11、流程控制
if 条件语句
循环语句
while 循环
for 循环
# 例:使用for和range来枚举列表中的元素
for i in range(10)
print(i)
12、列表推导式
list1 = [1,2,3]
list2 = [3,4,5]
[ x * y for x in list1 for y in list2]
[ x for x in list1 if 4 > x > 1] #[2,3]
13、函数
def functionname(parameters):
'函数_文档字符串'
function_suite
return [expression]
14、文件
#写文件
with open('a.txt','wt') as out_file:
out_file.write('写下要写的内容')
#读文件
with open('a.txt','rt') as in_file:
text = in_file.read()
print(text)