python基础
1、变量
赋值运算符“=” 初始化赋值语句 变量名 = 表达式
例如 a=1
给多个变量赋予同一内容
例如 a=b=c=100
给多个变量赋予不同内容
例如 a,b,c=1,2,'python' a=0 a=b=c=100 a,b,c=1,2,'python' b+=6 print(a,b,c,"你好!") a+=9 print(a)
2、python的注释:
(1)单行注释符号(#)
(2)批量、多行注释符号
在python中也会有注释有很多行的时候,这种情况下就需要批量多行注释符了,多行注释是用三引号''' '''或者一对三个单引号包含的。
(3)涉及中文
在python编写代码的时候,避免不了会出现或是用到中文,这时候你需要在文件开头加上中文注释。
如果开头不声明保存编码的格式是什么,那么它会默认使用ASKII码保存文件,这时如果你的代码中有中文就会出错了,即使你的中文是包含在注释里面的。所以加上中文注释很重要。
#coding=utf-8
或者:
#coding=gbk
3、数据类型
(1)数字型 int和float和complex复数
num1=6
num2=6.0
print(type(num1),type(num2))
x=91 y=6.0 print(type(x),type(y)) print(x+y,x-y,x*y,x/y) print(x**2,x%y,x//y) print(x>y,x<y) print(x>=y,x<=y) print(x==y) print(x!=y)
(2)字符串
1 s1='Hello' 2 s2='Python' 3 s=s1+s2 4 print(s,s[0],len(s)) 5 print(s.upper()) 6 print(s.lower()) 7 print(s.replace('H','hi')) 8 print(s.find('h')) 9 print(s.count('o')) 10 print(s.isalpha()) 11 print(s.isdigit()) 12 13 num1=input('请输入数字:') 14 print(type(num1)) 15 num=float(num1) 16 print(type(num))
字符串的切片:
st1 = 'abcdefghijklmnopqrstuvwxyz' st2 = '0123456789' print(len(st1),len(st2)) print(st1[1:8],st1[1:8:2],st1[:8],st1[18:]) print(st2[2:9],st2[2:9:2],st2[:9],st2[6:]) print(st1[::-1],st1[23:16:-1],st1[23:16:-2]) print(st2[::-1],st2[10:6:-1],st2[8:1:-2])
字符串的不可变性(不可改变字符串中的任何元素)
字符串的转义
\\ 反斜杠 ,\b退格 ,\n换行 ,\t制表符 ,\000空 ,……
st3 = 'hello\nword' print(len(st3)) print(st3) st4 = 'abc\000d' print(st4,len(st4))
(3)布尔值 True 和 False ,一般用于条件测试中。
逻辑运算符
x=-9 print(x>1 and x<10) print(x>1 or x<10) print(not x<-10)
(4)列表
列表的结构:利用中括号表示列表,列表内的元素用逗号隔开,可以修改列表里的内容。
l01 = [123,'abc',2,True,0.0009] print(l01,type(l01))
获取列表中的某个元素; 获取列表长度用len() ;
修改列表中的元素 ; 向列表后添加元素 .append()
删除列表元素 用 del+待删除元素 。
.pop()把列表中的最后一个元素取出来给某变量
l1 = [123,'abc',2,True,0.0009,"good",100,"加油",100] print(l1,type(l1)) print(l1[0],l1[1]) print(len(l1)) l1[4] = 0.019 l1.append("你好") print(l1) del l1[9] print(l1) l2 = [1,2,3,'ok',100] a = l2.pop() print('a =',a)
两个列表相加,直接用加号,或用.extend()
l3=l1+l2 print(l1+l2,l3) l1.extend(l2) print(l1)
判断某个元素是否在列表中,用in;
获取列表中某元素重复的次数 ,用 列表.count() ; 获取列表中某元素第一次出现的位置,用 列表.index()
;
l4 = [1,2,3,1,2,100,1,2,100,2,1] a=l4.count(1) print(a) b=l4.index(2) print(b)
列表的切片:
l4 = [0,1,2,3,4,5,6,7,8,9] print(l4[:],l4[1:8:2],l4[6::2],l4[:8:2]) print(l4[:6:-1],l4[9:4:-2])
字符串转列表用list() ,下面示例结果为['o', ' ', 'p', 'y']:
s = 'hello python' l5 = list(s[4:8]) print(l5)
列表的分片赋值:
s = 'hello python' l5 = list(s) l5[6:] = [7,8,9] l5[1:4] = [] print(l5) #结果为['h', 'o', ' ', 7, 8, 9] l5[1:1] = ['2'] print(l5) #结果为['h', '2', 'o', ' ', 7, 8, 9]
(5)字典 字典结构{ key:value,key2:value2 } ;访问字典里的数据 ; 更新字典里的元素 ;字典的删除 ;
math_score = {'李理':100,'赵赵':99,'张张':98,"王品":97} print(math_score) print(math_score['王品']) math_score['王品'] = 100 print(math_score) math_score['杨杨'] = 90 math_score["刘陆"] = 94 print(math_score) del math_score['李理'] print(math_score) math_score.clear() print(math_score) del math_score print(math_score)
使用dict函数创建字典:
ys = [('liud',98),("guof",97)] dys = dict(ys) print(dys) #结果为{'liud': 98, 'guof': 97} sx = dict(muf=98,cheny=99,liy=96,kongw=80) print(sx) #结果为{'muf': 98, 'cheny': 99, 'liy': 96, 'kongw': 80}
字典结构——嵌套字典(字典存储在列表中,列表存储在字典里,字典存储在字典里)
student1 = {'name':"leil",'age':18,'score':80} student2 = {'name':'lil','age':17,'score':81} student3 = {'name':'las','age':19,'score':100} dict_studentscore = [student1,student2,student3] print(dict_studentscore) student4 = ['score', {'yuwne':100,"shuxue":100}] print(student4) studentscore = {"zhaol":{'yuwen':100,'math':99,'english':80}, 'lik':{'yuwen':99,'math':90,'english':70}} print(studentscore)
用.copy()克隆一个数据
student4 = ['score', {'yuwne':100,"shuxue":100}]
student5 = student4.copy()
student5[0] = '分数'
print(f'student4:{student4}')
print(f'student5:{student5}')
(6)元组
a = [6,18,'jl',6] b = (18,'jl',6,666) print(a) print(b) print(b[0]) print(b[0:2])
(7)集合
创建集合,用大括号{ } ,或者用set( ),集合里的元素不重复(唯一性);集合之间也有交集 & 及并集 | 和差集 - 及对称差集 ^
set0 = {18,6,'jl','nfcf','ws',666}
set1 = set([1,1,2,2,6,6,"nfcf"])
set2 = set([18,6,'jl','nfcf','ws',666])
print(set0)
print(set1)
print(set2)
print(set1 & set2)
print(set1 | set2)
print(set1 - set2)
print(set2 - set1)
print(set1 ^ set2)
print((set1 | set2) - (set1 & set2)) # 实现对称差集
print((set1-(set1 & set2)) | (set2-(set1 & set2))) #实现对称差集
print((set1 - set2) | (set2 - set1)) #实现对称差集
4、条件、循环和其他语句
(1)IF条件判断 语句
注意:单等号是赋值,双等号是判断相等。
x = input("请输入你的数学成绩:")
x = float(x)
if x >= 0 and x <= 120:
if x >= 108 and x < 120:
print("优秀")
elif x == 120:
print('满分!')
elif x < 108 and x >= 90:
print("良好")
elif x >= 72 and x<90:
print("及格")
else:
print('不及格')
elif x > 120:
print('您输入有误,超过试卷总分了')
else:
print("您输入有误,分数不能为负数")
(2)while循环语句
i =1 while i <= 10: print(i) i += 1 j = 1 while j <= 10: j += 1 if j%2 > 0: continue print(j) k = 1 while True: print(k) k += 1 if k >= 10: break
(3)for循环
students_list = ['a','b','c','d'] for student in students_list: print(student) s0 = {'good',1,8,'jl'} for s in s0: print(s) for i in range(10): print(i) print(type(range(10))) s1 = list(range(10)) print(s1) print(range(1,18,2))
s2 = [6,'jl','w',666] for id in range(len(s2)): print(s2[id]) for index,value in enumerate(s2): print(index,value)
z1 = {'d1':90,'c2':91} for k in z1: print(k,z1[k]) zs = 'goodpython' for x in zs: print(x)
5、函数的分类和使用
import random a = random.randint(0,10) print(a) def hello_user(user_name): print('Hello! '+user_name) hello_user('wang') def test_grade(name,grade): print(name+'的成绩是'+grade+'。') test_grade('小王','98') test_grade(grade='99',name='小亮') def add(a,b): sum_number = a + b return sum_number c = add(99,99) print(c) x = 1 def hello(): global x print(x) x = 2 hello() print(x)
6、格式化输出:
7、类
class Student(): def __init__(self,user_input_name): self.name = user_input_name def say_hi(self): print('Hello!I\'m {}.'.format(self.name)) lilei = Student('lilei') lilei.say_hi() xiaoliang = Student('xiaoliang') xiaoliang.say_hi()