# 二、列表# 2.1 列表排序和列表翻转# 列表排序:# sort():永久排序
studentNames =["wangjunkai","wangyuan","yiyangqianxi"]
studentScores =[98,85,99]
studentNames.sort()print(studentNames)
studentNames.sort(reverse=True)print(studentNames)# sorted():临时排序,会返回一个新的列表,不会对原来的列表产生影响
ninepercent =["caixunkun","chenlinong","fanchengcheng","huangminghao","linyanjun","zhuzhengting","wangziyi","xiaogui","youzhangjing"]print(sorted(ninepercent))# 列表翻转:reverse()
ninepercent.reverse()print(ninepercent)# 2.2 多维列表和取得列表长度# 列表长度:len()print(len(ninepercent))# 列表可以包含不同类型的数据
list1 =["sss",123,45.6]# 列表可以包含列表(多维列表)
list2 =[["a","b"],["c","d"],["e","f"]]print(list2[0])print(list2[0][1])# 2.3 for循环遍历列表# for 临时变量名 in 列表名: 循环体for name in ninepercent:print(name)# 2.4 生成有规律的数字列表# list(range(3,10)) ——生成[3,10)# range(第一个数,最后一个数,每次增加多少)
listNumber =list(range(3,10,2))print(listNumber)# list4 = list(range(1,11))# newListNum = []# for num in list4:# newListNum.append(num ** 2)# print(newListNum)# newListNum = []# for num in range(1, 11):# newListNum.append(num ** 2)# print(newListNum)
newListNum =[num **2for num inrange(1,11)]print(newListNum)# 2.5 利用索引遍历列表for index inrange(0,len(ninepercent)):
ninepercent[index]= ninepercent[index].title()print(ninepercent[index])# 2.6 数字列表的简单统计# min(列表名):获取列表中的最小值# max(列表名):获取列表中的最大值# sum(列表名):获取列表中所有值的和print(min(studentScores))print(max(studentScores))print(sum(studentScores))# 2.6 复制列表# (1)newNine = ninepercent[:] ——newNine赋值了ninepercent的值,其中一个发生变化,不会影响另一个# (2)newNine = ninepercent ——newNine引用了ninepercent,其中一个发生了变化,另一个也会变化
newNine = ninepercent[:]# newNine = ninepercent * 2 # 复制两遍
newNine[0]="有长进"print(ninepercent)print(newNine)# 2.7 元组(不可修改的列表,访问方法同列表相同)
four =("caixukun","fanchengcheng","justin","zhuzhengting")for name in four:print(name)
三、if语句
# 三、条件语句ifimport random
age =24if age >40:print("old")else:print("young")# python的布尔值为True和Falseprint("youzhangjing"=="Youzhangjing")# 3.1 多条件判断# (1) and# (2) or
level =3if age >=18and age <=40and level ==3:print("青年")else:print("非青年")# 3.2 判断值是否在列表里面# (1) in# (2) not in
names =["wangjunkai","wangyuan","yiyangqianxi"]print("youzhangjing"in names)# 3.2 if的嵌套# (1) if……else的嵌套# (2) if……elif……else
num =11# if num <= 4:# print("免费进入")# else:# if num <= 12:# print("半价进入")# else:# print("全价进入")# if num <= 4:# print("免费")# elif num <=12:# print("半价")# else:# print("全价")# 3.2 if的其他形式# 一个条件判断中,可以有0到多个elif,0到一个else# if num <= 4:# print("免费")# elif num <=12:# print("半价")# elif num <= 60:# print("全价")# else:# print("免费")if num <=4or num >=60:print("免费")elif num <=12:print("半价")else:print("全价")# 3.3 猜数# random.randint(1, 20) ——[1,20]# break:退出循环import random
number = random.randint(1,20)print("猜猜1-20之间的一个数:")for i inrange(1,6):
userIn =int(input())if userIn < number:print("猜小了")elif userIn > number:print("猜大了")else:print("猜对了")breakprint("游戏结束")
四、字典
# 四、字典# 4.1 字典的定义与访问# 字典的定义:键值对# 字典名 = {'键':'值'} ——创建时键值对可为空 stu1={}
stu1 ={'name':"王俊凯",'age':18,'gender':"male"}print(stu1)# 字典的访问:# 字典名['键']print(stu1['name'])# 4.2 字典的增删改# 增加:字典名['键']=值
stu1['rank']=1print(stu1)# 修改:字典名['键']=值
stu1['age']=19print(stu1)# 删除:del(字典名['键'])del(stu1['rank'])# del stu1['rank']print(stu1)# 4.2 一行与多行定义# (1)对于列表,在逗号后直接换行# (2)对于连续字符串,用连接符\
ninepercent =["caixunkun","chenlinong","fanchengcheng","huangminghao","linyanjun","zhuzhengting","wangziyi","xiaogui","youzhangjing"]print(ninepercent)
str1 = "eeeeeeeeeeeeeeeeeeeeeeeeeee\
wwwwwwwwwwwwwwwwwwwwwwwww\
cccccccccccccccccccccccccccccc"
print(str1)# 4.3 列表与字典的嵌套使用
students =[{'name':"王俊凯",'age':23,'gender':"male"},{'name':"王源",'age':22,'gender':"male"},{'name':"易烊千玺",'age':21,'gender':"male"}]print(students[1]['name'])
stu2 ={'name':"王俊凯",'age':18,'gender':"male",'hobby':['唱歌','跳舞','吉他']}print(stu2['hobby'][2])# 4.4 判断两个字典是否相等# 列表有序,字典无序
list1 =['w','e']
list2 =['e','w']print(list1 == list2)
dic1 ={'name':"王俊凯",'age':18}
dic2 ={'age':18,'name':"王俊凯"}print(dic1 == dic2)# 4.5 用key和value获取键集合与值集合# (1)遍历键:字典名.keys() ——得到的是一个关于键的集合print(stu1.keys())for i in stu1.keys():print(i)print(list(stu1.keys()))# (2)遍历值:字典名.values() ——得到的是一个关于值的集合print(stu1.values())for i in stu1.values():print(i)print(list(stu1.values()))# (3)遍历键值对:字典名.items() ——得到的是一个关于键值对的集合print(stu1.items())for i in stu1.items():print(i)print(i[0], i[1])print(list(stu1.items()))for k, v in stu1.items():print(k, v)# 4.6 判断键是否存在和设置键的默认值# (1)判断键是否存在: in not inprint('name'in stu1.keys())# print('name' in stu1) # 仅有字典名,判断的是键是否存在print(19in stu1.values())# (2)设置键的默认值: 字典名.setdefault('键', 值)
stu1.setdefault('age',18)# 如果此处的键M是字典中不存在的键A,则会为该字典添加键M及相应的值print(stu1)
五、while循环
# 五、while循环# 当条件为True时,才会执行while循环# i = 1# while i < 11:# print(i)# i = i + 1# total = 0# n = 1# while n < 101:# total = total + n# n = n + 1# print(total)# 5.1 三种跳出循环的方法# (1)通过判断标志位来设置终止循环的条件 ——此处为flag
total =0
flag =Truewhile flag:
num =int(input("please input an integer:"))
total = total + num
if num ==0:
flag =Falseprint(total)# (2)直接通过条件来设置终止循环的触发点 ——此处为i=-1
total =0
i =-1while i !=0:
num =int(input("please input an integer:"))
total = total + num
if num ==0:
i =0print(total)# (3)break:跳出当前循环
total =0whileTrue:
num =int(input("please input an integer:"))
total = total + num
if num ==0:breakprint(total)whileTrue:
num =int(input("please input an integer:"))if num %2==0:print(num)if num ==0:break# 5.2 利用while遍历列表与字典# (1)遍历列表
three =["王俊凯","王源","易烊千玺"]
i =0while i <len(three):print(three[i])
i = i +1# (2)遍历字典
stu ={'name':"王俊凯",'age':18,'gender':"male"}
index =0
keys =list(stu.keys())while index <len(keys):
key = keys[index]
value = stu[key]print(key, value)
index = index +1# 5.3 使用while循环移动列表的数据和删除某个值# (1)移动列表的数据
studentNames =["王俊凯","王俊凯","王俊凯","王源","易烊千玺"]
newNames =[]while studentNames:# 当列表为空时,while后面的条件值变为false
newNames.append(studentNames.pop())print(studentNames)print(newNames)# (2)删除某个值while"王俊凯"in newNames:
newNames.remove("王俊凯")print(newNames)# 5.3 使用while循环给字典添加数据和print不换行输出# (1)给字典添加数据
dic ={}whileTrue:
key =input("请输入键:")
value =input("请输入值:")
dic[key]= value
answer =input("是否继续添加(yes/no):")if answer =="no":breakprint(dic)# (2)print不换行输出# 当print默认end='\n',即换行# 令print的end='',就可以不换行输出for i inrange(1,11):print(i, end='')print(123, end='\n\n\n')print("456\n\n\n")
六、函数
# 六、函数# 6.1 函数定义(先定义后使用)deftest():print("test1")print("test2")
test()# 6.2 函数的参数(形参和实参)defhello(name):# 此处的name为形参print("hello "+ name)
hello("王俊凯")# 王俊凯为实参# 6.3 函数的返回值和none值defadd(a, b):return a+b
print(add(1,2))# None NoneTypedefmulti(a, b):print(a * b)
res = multi(2,3)print(res)print("hello","world")print("hello","world", sep=",")# sep用于设置分隔符# 6.3 通过关键字参数修改某个参数的默认值defadd2(a, b=10, c=20):print(a + b + c)
add2(1,c=2)
add2(1,1,1)# 6.4 局部变量&全局变量
name ="全局变量"deftest():
name ="局部变量"print(name)
test()print(name)
name2 ="全局变量"deftest2():global name2 # 生命接下去是对全局变量做更改
name2 ="全局变量更改"print(name2)
test2()print(name2)# 6.5 函数与字典列表结合使用deftestDic(n, a):
dic ={'name':n,'age':a}return dic
print(testDic("王俊凯",18))
l =["wjk","wy","yyqx"]deftestList(list):dellist[2]returnlistprint(testList(l[:]))# 使得testList方法的使用不对原列表l产生影响print(l)# 6.6 可变个参数的使用:形参前加*deftestNum(a,*n):print(n)
testNum(1)
testNum(1)
testNum(1,2,3)# 6.7 创建模块并导入import test # 导入整个模块 ——文件名一般以小写开头
test.test5()# 导入的文件名.方法名
test.test6()# import test# from test import * ——这两句加起来,就可以直接调用方法,不需要文件名.方法名# 6.8 模块其他用法# (1)仅使用模块中的一个方法:from 导入的文件名 import 导入文件中存在的方法 ——as用于起别名(一样可以给模块取别名)from test import test5 as othername, test6
othername()
test6()# 6.8 函数的递归调用deff(n):if n ==1:return1else:return f(n-1)+ n
print(f(5))