第 0 关(涉及的函数有print 和 type)
print函数不加引号才是计算机运行,加了引号计算机不思考直接输出。
type可以帮你查询函数类型
第 1 关(加减乘除,取模,取整余)
print(2**3)
#幂 (这里是2的3次方)
#输出为 8
print(10%3)
#取模 (做除法返回余数)
#输出为 1
print(10//3)
#取整除 (做除法返回商的整数部分)
#输出为 3
第 2 关 if 语句(涉及到的函数有if elif else)
historyscore = 26
if historyscore >= 60:
print('你已经及格')
#前面已经有了一个if所以这里要继续缩进
if historyscore >= 80:
print('你很优秀')
else:
print('你只是一般般')
#这个else时与第一个if相对应的
else:
print('不及格')
**在不同的
if函数中else要顶格其余的if和elif要缩进**
第 3 关(涉及到的函数有 input)
input 函数在用之前要必须先赋值(必须) 例如:
name = input("请输入你的名字")
print("您好" + name)
而且 input 返回的函数一定类型是字符串(str)。
如果想要改变 input 返回的值,可以强制转化 如(需从源头转换):
age = int (input ("请问您今年贵庚了?") )
#将 input 中的类型强制转换为整数类型
print(" 您已经" + age + "啦")
第 4 关 列表和字典(涉及到的函数有 append, del , )
列表的使用:
**左右空,取到头,左要取,右不取。**如:
#输入:
list2 = [5,6,7,8,9]
print(list2[:])
print(list2[2:])
print(list2[:2])
print(list2[1:3])
print(list2[2:4])
#输出:
[5, 6, 7, 8, 9]
[7, 8, 9]
[5, 6]
[6, 7]
[7, 8]
另外,我们要注意一个细节:偏移量取到的是列表中的元素,而切片则是截取了列表的某部分,所以还是列表,请你运行下列代码看一看
#输入:
students = ['小明','小红','小刚']
print(students[2])
print(students[2:])
#
输出:
小刚
【‘小刚’】
append 函数:给列表加入元素 如:
#输入:
students = ['小明','小红','小刚']
students.append("小美")
#加入一个元素且这个元素会出现在末尾
print(students)
#输出:
[“小明”,“小红”,“小刚”,“小美”]
del函数:将元素从列表中删除 事实上del语句非常方便,既能删除一个元素,也能一次删除多个元素(原理和切片类似,左取右不取) 如:
#输入:
students = ['小明','小红','小刚','小美']
del students[1]
print(students)
#输出:
[“小明”,“小刚”,“小美”,]
给字典增加元素:
#输入
scores = {'小明':95,'小红':90,'小刚':90}
del scores['小刚']
scores['小刚'] = 92
#把小刚的成绩赋值为92
scores['小美'] = 85
#加入小美并赋值为85
print(scores)
#输出:
{“小明”:95,“小红”:90,“小刚”:92,“小美”:85}
列表中的数据是有序排列的,而字典中的数据是随机排列的。
列表有序,要用偏移量定位;字典无序,便通过唯一的键来取值。
**列表和字典的第一个共同点:在列表和字典中,如果要修改元素,都可用赋值语句来完成。**如:
#输出:
list1 = ["小红","小明","小刚"]
list1[1] ="小蓝"
#把[1]中小明替换成小蓝
print(list1)
dict1 = {"小明":"男"}
dict1["小明"] = "女"
#把小明的值“男”替换成“女”
print(dict1)
#输出:
["小红","小蓝","小刚"]
{"小明"="女"}
**第二个共同点其实之前已经略有提及,即支持任意嵌套。除之前学过的数据类型外,列表可嵌套其他列表和字典,字典也可嵌套其他字典和列表。**如:
#输入(列表嵌套列表):
students = [['小明','小红','小刚','小美'],['小强','小兰','小伟','小芳']]
print(students[1][3])
#输出:
小芳
#输入(字典嵌套字典):
scores = {
'第一组':{'小明':95,'小红':90,'小刚':100,'小美':85},
'第二组':{'小强':99,'小兰':89,'小伟':93,'小芳':88}
}
print(scores['第二组']['小芳'])
#输出:
88
看看列表和字典相互嵌套的情况
# 最外层是大括号,所以是字典嵌套列表,先找到字典的键对应的列表,再判断列表中要取出元素的偏移量
students = {
'第一组':['小明','小红','小刚','小美'],
'第二组':['小强','小兰','小伟','小芳']
}
print(students['第一组'][3])
#取出'第一组'对应列表偏移量为3的元素,即'小美'
#最外层是中括号,所以是列表嵌套字典,先判断字典是列表的第几个元素,再找出要取出的值相对应的键
scores = [
{'小明':95,'小红':90,'小刚':100,'小美':85},
{'小强':99,'小兰':89,'小伟':93,'小芳':88}
]
print(scores[1]['小强'])
#先定位到列表偏移量为1的元素,即第二个字典,再取出字典里键为'小强'对应的值,即99
第 5 关 for while 循环(上 )(涉及到的函数有 range )
for
①列表循环
#输入
for i in [1,2,3,4,5]:
print(i)
print("事情都做完了最后输出什么?")
#会输出最后的值
print(i)
#输出
1
2
3
4
5
事情都做完了最后输出什么?
5
②字典循环
#输入
dict = {"日本" : "东京","英国" : "伦敦" , "法国" : "巴黎"}
for i in dict :
print(i)
#输出的是键
#输出
日本
英国
法国
#如果想输出字典里的值
dict = {"日本" = "东京","英国" = "伦敦" , "法国" = "巴黎"}
for i in dict :
print(dict[i])
#输出的就是
东京
伦敦
巴黎
③字符串循环
#输入
for i in "吴承恩":
print(i)
#会将字符串一个个的拆解
#输出
吴
承
恩
range 函数:
#输入
for i in range (3):
#range(n)会输出0到n-1
print(i)
#输出
0
1
2
#还可以这样
for i in range (13,17):
#左取右不取
print(i)
#输出
13
14
15
16
#还能这样
for i in range (0,10,3):
#从0数到9(取头不取尾),步长为3
print(i)
#输出
0
3
6
9
while
a = 0
while a < 5 :
#当a<5时执行下面语句
a = a + 1
print(a)
#输出
1
2
3
4
5
number = " "
#将变量赋予一个空值
while number != "47":
#当number不等于47时执行下面与语句
number = input ("请问您什么时候生日?")
print("是你了")
#输出
请问您什么时候生日?47
#只有输入47的时候程序才会结束不然他会一直循环
是你了
a = 0
while a <5 :
a = a +1
print(a)
#输出
5
#有缩进的时候,print(a)也是循环中的“办事流程”,会将数字逐一打印。没有缩进的时候,循环中的“办事流程”就只有做加法,print(a)也就只会打印循环结束时的最后一个数字。
练习
#每换一次座位,第一位变成第三位,后面两位都往前一位
students = ["小明","小红","小刚"]
for i in range (3):
students1 = students.pop(0)
#将students中的第一元素移出并删除,并将其赋值与students1
students.append(students1)
#被删除元素的students再在末尾增加之前所删除的元素
print(students)
第 6 关 for white 循环(下)(bool, in not in, continue, break pass )
布尔值:
除了0,None,"",{},[] 以外的都是真值
#在计算机中判断对错:
print("3<5")
print("3>5")
#引号可以去掉
#输出:
True
False
bool函数(bool函数来查看一个数据会被判断为真还是假):
print(bool(0))
print(bool(""))
print(bool(None))
print(bool(1))
print(bool("随便的东西"))
#输出:
False
False
False
True
True
in 的意思是“判断一个元素是否在一堆数据之中”,【not in 】反之。
list = [1,2,3,4,5]
a=1
print(bool(a in list))
print(bool(a not in list))
#输出:
True
False
#如果涉及到的数据集合是字典的话,【in】和【not in 】就可以用来判断字典中的某个
break语句(必须与if语句连用):
break的意思是“打破”,是用来结束循环的,一般写作if…break
【注】:Tab键和空格键不能同时混用
while True:
number = int(input("请输入您的生日"))
if number = 47:
#如果number等于47终止循环
break
print("是你了")
continue语句(continue的意思是继续这个子句也是在循环内部使用的。当某个条件被满足的时候,触发continue语句,将跳过之后的代码,直接回到循环的开始。)注(必须与if语句连用):
while True:
q1 = input ("我的外号叫什么?")
if q1 != "klm":
#如果q1等于klm跳过这个循环进入之后的代码
continue
print("答对了,下一个问题")
q2 = input("你的外号叫什么?")
if q2 != "mtd":
#如果q2等于mtd就跳过这个循环进入之后的代码
continue
print("就差最后一个问题了")
q3 = input("你的生日是什么时候?")
if q3 != 4.7:
#如果q3等于4.7就终止第一行的while True循环
break
print("是你了")
pass语句(他是跳过的意思,什么都不做)
else语句:
for i in range (5):
a = int(input ("你有五次机会输入正确数字"))
if a == 47:
print("bingo,else语句不会生效")
break
else:
print("你错过了机会,else语句生效了")
#也可以用while语句
i = 1
while i < 5 :
a = int(input("你有五次机会输入正确数字"))
i = i+1
if a == 47:
print("bingo,else语句不会生效")
break
else:
print("你错过了机会,else语句生效了")
练习
#两个认罪都判10年,一个认罪一个不认,前者判1年,后者判20年;两个都不认罪各判3年,只有两个都不认罪程序才会停下来。
#现在做一个实验,一旦遇到都不认罪的情况就停止实验,同时希望程序能记录每一个实验者的选择,以及记录第几组实验者都不选择认罪
n = 0
list_answer = []
while True:
n +=1
a = input("a你是否认罪?回答是或否")
b = input("b你是否认罪?回答是或否")
list_answer.append([a,b])
if a== "是" and b = "否":
print("a判1年b判20年")
elif a=="否" and b = "是":
print("a判20年b判1年")
elif a=="是" and b=="是":
print("ab都判10年")
else :
print("ab都判3年")
break
print("实验第" + str(n) + "组取得最优解")
for i in range(n):
print("第" + str(i+1) "组实验的结果为" + str(list_answer[i]))
第 7 关 小游戏大学问 (善用变量)(涉及到的函数 import time,random %(占位符) format ):
import time #调用time 模块
time.sleep(secs)
#使用time模块下的sleep函数,()里填的是时间间隔的秒数(sconds 简称secs)
#time.sleep(1.5)就表示停留1.5秒后再运行代码
调用random函数:
import random
a = random.randint(1,100)
#随机生成1-100范围内(含1和100)的整数,并赋值给变量a
print(a)
#会输出一个1-100 的随机整数
(需要看第4关的操作代码)
格式符%(先占住一个位置)
%s 表示 字符串显示
%f 表示 浮点数显示
%d 表示 整数显示
占完位置之后,我们要以%的形式在后面补上要填充的内容,如此一来我们就免去了转换类型的烦恼。如果是多个数据,就要把它们放进括号,按顺序填充,用逗号隔开
print("血量:" + str("player_life") + "攻击" + str("player_attack"))
print("血量: %s 攻击:%s" %("player_life","player_attack"))
#因为player_life 和 player_attack 未被定义,不能直接引用
print("我的幸运数字是%d和%d" %(4,7))
#输出
我的幸运数字是4和7
练习:
import time,random
while True:
player_win = 0
enemy_win = 0
for i in range (1,4):
print("现在是第 %s 局" %i )
time.sleep(1.5)
player_attack = random.randint(70,100)
player_life = random.randint(130,150)
enemy_attack = random.randint(70,100)
enemy_life = random.randint(130,150)
#随机赋予玩家和敌人的血量和攻击力
print("玩家的血量为 %s 攻击力为 %s" %(player_attack,player_life))
print("-------------------")
time.sleep(1.5)
print("敌人的血量为 %s 攻击力为 %s" %(enemy_attack,enemy_life))
print("-------------------")
time.sleep(1.5)
#显示出玩家和敌人的血量和攻击力
while player_life >0 and enemy_life>0:
enemy_life = enemy_life - player_attack
player_life = player_life- enemy_attack
print("玩家发起了攻击,敌人的血量剩余 %s" %(enemy_life))
time.sleep(1.5)
print("敌人发起了攻击,玩家血量剩余 %s" %(player_life))
time.sleep(1.5)
if player_life > 0 and enemy_life <= 0:
player_win +=1
print("玩家取一盘得胜利")
print("------------------------------")
time.sleep(2)
elif player_life <= 0 and enemy_life > 0:
enemy_win += 1
print("敌人取得一盘胜利")
print("------------------------------")
time.sleep(2)
else:
print("打平了")
print("------------------------------")
time.sleep(2)
if player_win > enemy_win :
print("玩家获胜")
elif enemy_win >player_win:
print("敌人获胜")
else :
print("平局")
a = input("是否再来一局?请输入是或否")
if a == "否" :
break
format 是用 {} 来进行占位的不用区分代码类型
print("现在是第 %s 局" %i)
print("现在是第 {} 局".format(i))
print("玩家的血量为 %s 攻击力为 %s" %(player_life,player_attack))
print("玩家的血量为 {} 攻击力为 {}".format(player_life,player_attack))
第 8 关 做好笔记(涉及到的函数end,extend,sort)
end函数
print("hello",end="")
print("word")
print("hello",end=" ")
print("word")
print("hello",end="!")
print("word")
#输出:
helloword
hello word
hello!word
print("")用于换行
for i in range(1,3):
print("%d*%d=%d" %(i,2,i*2))
print("")
for i in range(1,4):
print("%d*%d=%d" %(i,3,i*3))
print("")
九九乘法表:
for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%d" %(j,i,j*i), end=" ")
print("")
练习
list1 = [91, 95, 97, 99]
list2 = [92, 93, 96, 98]
# 把 A 组成绩赋值给一个新列表,用来存合并的成绩——这个细节要注意!
list3=list1
list3.extend(list2) #直接在list3后加上list2
print(list3)
list3.sort() #将list3加上list2的列表按从小到大的顺序排列
print(list3)
#输出:
[91,95,97,99,92,93,96,98]
[91,92,93,95,96,97,98,99]
n = 0
scores2 = []
scores1 = [91, 95, 97, 99, 92, 93, 96, 98]
for i in scores1 :
n = n +i
average = n / 8
for i in scores1 :
if i < average :
scores2.append(i)
continue
print("低于平均分的有{}" .format(scores2) )
import numpy as np #导入 numpy 库,下面出现的 np 即 numpy库
scores1 = [91,95,97,99,92,93,96,98]
scores2 = []
average = np.mean(scores1) #一行解决
print("平均成绩是:{}".format(average))
for score in scores1:
if score < average :
scores2.append (score)
continue
print("低于平均成绩的有:{}".format(scores2))
#输出:
低于平均成绩的有:[91,95,92,93]
#下面展示一种numpy数组的操作,感兴趣的可以了解一下
scores3 = np.array(scores1)
print("低于平均成绩的有:{}".format(scores3[scores3<average]))
#输出:
[91 95 92 93]
第 9 关 函数(涉及到的函数有 def return ,sep, end, global, import random choice )
例如像print(),input(),len(),type(),str(),int(),float()这些,括号前面的称之为函数,而括号中的为参数(输入的数据)。
def 函数名(参数):
函数体
return 语句
#定义一个类似与len同样作用的函数
def my_len(word):
number = 0
for i in word :
number += 1
return number
print(my_len("三斤皮带,四斤大豆"))
def menu (appetizer, course):
print('一份开胃菜:' + appetizer)
print('一份主食:' + course)
menu('话梅花生','牛肉拉面')
def menu(appetizer, course):
print('一份开胃菜:' + appetizer)
print('一份主食:' + course + '\n')
menu('牛肉拉面','话梅花生')
menu('话梅花生','牛肉拉面')
#如果采用下面这种形式传递,就不需要理会参数位置
menu(course = '牛肉拉面', appetizer = '话梅花生')
需要注意的是,默认参数要放在位置参数之后。
def menu (appetizer,course,dessert = "绿豆沙"):
print("一份开胃菜:" + appetizer)
print("一份主食:" + course)
print("一份甜品:" + dessert)
menu("话梅花生","牛肉拉面")
#因为已经默认将'绿豆沙'传递给dessert,调用时无须再传递。
#输出
一份开胃菜:话梅花生
一份主食:牛肉拉面
一份甜品:绿豆沙
```python
python
def menu(appetizer, course, dessert = '绿豆沙'):
print('一份开胃菜:' + appetizer)
print('一份主食:' + course)
print('一份甜品:' + dessert)
menu('话梅花生','牛肉拉面')
menu('话梅花生','牛肉拉面','银耳羹')
#银耳羹对应参数dessert,会将原来的绿豆沙给替换掉
def menu (*barbeque):
return barbeque
order = menu ("烤鸡翅","烤茄子","烤玉米")
#括号里的这几个值会传递给参数barbeque
print(order)
print(type(order))
#输出:
烤鸡翅,烤茄子,烤玉米
<class "tuple"> #类型是元组
还可以加入循环减少工作量
def menu(*barbeque):
for i in barbeque:
print('一份烤串:' + i)
menu('烤香肠', '烤肉丸')
menu('烤鸡翅', '烤茄子', '烤玉米')
# 不定长参数可以接收任意数量的值
#输出::
一份烤串:烤香肠
一份烤串:烤肉丸
一份烤串:烤鸡翅
一份烤串:烤茄子
一份烤串:烤玉米
print('金枪鱼', '三文鱼', '鲷鱼')
print('金枪鱼', '三文鱼', '鲷鱼',sep = "+")
# sep控制多个值之间的分隔符,默认是空格
print('金枪鱼', '三文鱼', '鲷鱼',sep = "+",end = "=?")
#输出
金枪鱼 三文鱼 鲷鱼
金枪鱼+三文鱼+鲷鱼
金枪鱼+三文鱼+鲷鱼=?
import random
#引入random模块
appetizer = ['话梅花生','拍黄瓜','凉拌三丝']
def coupon(money):
if money < 5:
a = random.choice(appetizer)
return a
elif 5 <= money < 10:
b = random.choice (appetizer)
return b, '溏心蛋'
#绝对不能用下面这种格式:
#return b
#return "溏心蛋"
print(coupon(3))
print(coupon(6))
#输出:
三种开胃菜之中随机选出一种
<class tuple> #为元组类型
因为取的是元组,所以可以用提取的方法来提取数据
print(result[0])
print(result[1])
global 可以将局部变量转换为全局变量,一般写在局部区域第一行
def egg():
global quantity
quantity = 108
egg()
print(quantity)
rent = 3000
def cost():
utilities = int(input('请输入本月的水电费用'))
food_cost = int(input('请输入本月的食材费用'))
variable_cost = utilities + food_cost
print('本月的变动成本是' + str(variable_cost))
return variable_cost
def sum_cost():
sum = rent + cost()
#cost()函数运行结束后会返回变量variable_cost,而sum_cost()函数内部调用了cost(),所以调用sum_cost()的时候,cost()函数也会执行,并得到返回值variable_cost。sum = rent + cost() 的结果就是sum = rent + variable_cost。
print('本月的总成本是' + str(sum))
sum_cost()
def div(num1, num2):
growth = (num1 - num2) / num2
percent = str(growth * 100) + '%'
return percent
def warning():
print('Error: 你确定上个月一毛钱都不赚不亏吗?')
def main():
while True:
num1 = float(input('请输入本月所获利润'))
num2 = float(input('请输入上月所获利润'))
if num2 == 0:
warning()
else:
print('本月的利润增长率:' + div(num1,num2))
break
main()
练习
def bonus(month):
if month < 6:
money = 500
return money
elif 6<= month <=12:
money = 120*month
return money
else:
money = 180*month
return money
def info (name,month):
gain = bonus(month)
print("%s来了%s个月,获得奖金%s元" %(name,month,gain))
info("大聪",14)
#输出
大聪来了14个月获得奖金2520元
import random
luckylist = ['海绵宝宝','派大星','章鱼哥']
a = random.choice(luckyist) # 从3个人中随机选取1个人。
print(a)
第 10 关 工作量计算器 (涉及到的函数 import math ceil,index)
%f的意思是格式化字符串为浮点型,%.1f的意思是格式化字符串为浮点型,并保留1位小数。
向上取整
import math
number = math.ceil (8/3)
print(number)
#输出:
3
import math
# 工时计算
def estimated_time (size,number):
time = size*80/number
print("项目大小为%.1f个标准项目。使用%d个人完成,则需要工时数量为:%.1f个" %(size,number,time)
#人力计算
def estimated_number(size,time):
number = math.ceil(size*80/time)
print("项目大小为%.1f个标准大小标准项目,如果需要在%.1f个工时完成,则需要人力数量为%d人" %(size,time,number))
estimated_time(1.5,2)
estimeated_number(1,60)
#输出:
项目大小为1.5个标准项目。使用2个人完成,则需要工时数量为60.0
项目大小为1.0个标准项目。如果需要在60.0个工时完成,则需要人数量为2人
import math
# 为函数设置了三个参数,并都带有默认参数)
def estimated(size=1,number=None,time=None):
# 人力计算:如果参数中填了时间,没填人数,就计算人力
if (number == None) and (time != None):
number = math.ceil(size * 80 / time)
print('项目大小为%.1f个标准项目,如果需要在%.1f个工时完成,则需要人力数量为:%d人' %(size,time,number))
# 工时计算:如果参数中填了人数,没填时间,就计算工时
elif (number != None) and (time == None):
time = size * 80 / number
print('项目大小为%.1f个标准项目,使用%d个人力完成,则需要工时数量为:%.1f个' %(size,number,time))
# 调用函数的时候,传递两个参数,会自动计算出第三个参数
estimated(size=1.5,number=2)
estimated(size=0.5,time=20.0)
import math
def estimated(size=1,number=None,time=None):
if (number == None) and (time != None):
number = math.ceil(size * 80 / time)
print('项目大小为%.1f个标准项目,如果需要在%.1f个工时完成,则需要人力数量为:%d人' %(size,time,number))
elif (number != None) and (time == None):
time = size * 80 / number
print('项目大小为%.1f个标准项目,使用%d个人力完成,则需要工时数量为:%.1f个' %(size,number,time))
choice = input('请选择计算类型:(1-人力计算,2-工时计算)')
if choice == '1':
size = float(input('请输入项目大小:(1代表标准大小,可以输入小数)'))
number = None
time = float(input('请输入工时数量:(可以输入小数)'))
estimated(size,number,time)
elif choice == '2':
size = float(input('请输入项目大小:(1代表标准大小,可以输入小数)'))
number = int(input('请输入人力数量:(请输入整数)'))
time = None
estimated(size,number,time)
import math
def myinput():
choice = input ("请输入计算类型:(1-人力计算,2-工时计算)")
if choice == "1":
size = float(input("请输入项目大小:(1代表标准大小,请输入小数)"))
number = None
time = float(input("请输入工时量:(请输入小数)"))
return size,number,time
#这里是一个数组
elif choice =="2":
size = float(input("请输入项目大小:(1代表标准大小,请输入小数)"))
number = int(input("请输入人力数量:(请输入整数)"))
time = None
return size,number,time
#这里返回的数据是一个元组
#完成计算函数
def estimated(my_input):
#把元组中的数据取出来
size = my_input[0]
number = my_input[1]
time = my_input[2]
#人力计算
if (number == None) and (time !=None):
number = math.ceil(size * 80 / time)
print("项目大小为%.f个标准项目,如果需要在%.f个人力数量,这需要人力数量%d人" %(size,time,number))
#工时计算
elif (number !=None) and (time ==None):
time = size * 80 / number
print("项目大小为%.1f个标准项目,使用%d个人力完成,则需要工时数量为:%.1f个" %(size,number,time))
#主函数
def main ():
my_input = myinput()
estimated(my_input)
#调用主函数
main()
import math
# 变量key代表循环运行程序的开关
key = 1
# 采集信息的函数
def myinput():
choice = input('请选择计算类型:(1-工时计算,2-人力计算)')
if choice == '1':
size = float(input('请输入项目大小:(1代表标准大小,请输入小数)'))
number = int(input('请输入人力数量:(请输入整数)'))
time = None
return size,number,time
# 这里返回的数据是一个元组
if choice == '2':
size = float(input('请输入项目大小:(1代表标准大小,请输入小数)'))
number = None
time = float(input('请输入工时数量:(请输入小数)'))
return size,number,time
# 这里返回的是一个元组
# 完成计算的函数
def estimated(my_input):
# 把元组中的数据取出来
size = my_input[0]
number = my_input[1]
time = my_input[2]
# 人力计算
if (number == None) and (time != None):
number = math.ceil(size * 80 / time)
print('项目大小为%.1f个标准项目,如果需要在%.1f个工时完成,则需要人力数量为:%d人' %(size,time,number))
# 工时计算
elif (number != None) and (time == None):
time = size * 80 / number
print('项目大小为%.1f个标准项目,使用%d个人力完成,则需要工时数量为:%.1f个' %(size,number,time))
# 询问是否继续的函数
def again():
# 声明全局变量key,以便修改该变量
global key
a = input('是否继续计算?继续请输入y,输入其他键将结束程序。')
if a != 'y':
# 如果用户不输入'y',则把key赋值为0
key = 0
# 主函数
def main():
print('欢迎使用工作量计算小程序!')
while key == 1:
my_input = myinput()
estimated(my_input)
again()
print('感谢使用工作量计算小程序!')
main()
练习
import random
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('请出拳:(石头、剪刀、布)') # 请用户输入选择
while user_choice not in punches: # 当用户输入错误,提示错误,重新输入
print('输入有误,请重新出拳')
user_choice = input()
print('————战斗过程————')
print('电脑出了:%s' % computer_choice)
print('你出了:%s' % user_choice)
print('—————结果—————')
if user_choice==computer_choice:
print('平局')
elif (user_choice=='石头'and computer_choice=='剪刀')or(user_choice=='剪刀' and computer_choice=='布')or (user_choice=='布' and computer_choice=='石头'):
print('你赢了')
else:
print('你输了')
index() 函数用于找出列表中某个元素第一次出现的索引位置。
语法为:list.index(obj),obj为object(对象)的缩写。
具体可参考右侧的代码和运行结果
import random
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('请出拳:(石头、剪刀、布)') # 请用户输入选择
while user_choice not in punches: # 当用户输入错误,提示错误,重新输入
print('输入有误,请重新出拳')
user_choice = input()
print('————战斗过程————')
print('电脑出了:%s' % computer_choice)
print('你出了:%s' % user_choice)
print('—————结果—————')
if user_choice == computer_choice:
print("平局")
#电脑的选择有3种,索引位置分别是:0石头,1剪刀,2布。
#假设在电脑索引位置上减1,对应:-1布,0石头,1剪刀.皆胜。
elif user_choice == punches[punches.index(computer_choice)-1]:
print("你赢了")
else:
print("你输了")
第 11 关 debug(涉及到的函数有try…except)
SyntaxError指的是语法错误
易犯的错误:
①漏掉了末尾的冒号,如if语句,循环语句,定义函数。
②缩进错误,该缩进的时候没缩进不该缩进的时候缩进
③把英文符号写成了中文符号,如:"",😢)。
④字符串拼接的时候把字符串和数字拼接在一起。
⑤没用定义变量
⑥"==“和”="混用
append函数每次只能接受一个函数
多行注释有两种快捷操作:1、在需要注释的多行代码块前后加一组三引号’’’ 2、选中代码后使用快捷键操作:Windows快捷键是ctrl+/,Mac为cmd+/,适用于本地编辑器
try…except(解决出错问题)
while Ture:
try :
age = input("你今年几岁了?")
break
except ValueError:
print("你输入的不是数字")
if age < 18 :
print("不可以喝酒哦")
num = [1,2,0,3]
for x in num :
try:
print(6/x)
except ZeroDivisionError:
print("0是不能整除的")
except Exception(这个函数代表了大部分错误类型)
第 12 关 类与对象(涉及到 的函数有def init(self))
class Computer: #类的创建:class+类名+冒号,后面语句要缩进
screen = True #类的属性创建:通过赋值语句,(即定义是怎么样的)
def start(self): #实例方法的创建:def + 方法名(self):
print("电脑正在开启") #方法具体执行过程,即定义能做什么
注意:
①类中赋值的变量叫属性,类中定义的函数叫方法(以此和普通函数区分)
②实例方法是指类中参数带self函数,是类方法的一种形式,也是最常用的用法
③课堂中所讲“类的方法”,均指实例方法。
④类名的首字母要大写,以便让我们轻松地辨认出
类的实例化
语法:实例名 = 类名()
例如:my_computer = Computer()
调用属性:实例名.属性
调用方法:实例名.方法()
意义:我们有了一个实例,一个“可以调用所属类的所以属性和方法”的实例
class Computer:
screen = Ture
def start(self):
print("电脑正在开机中")
my_computer = Computer()
print(my_computer.screen)
my_computer.start()
#输出:
True
电脑正在开机中
特殊函数self(self 是所有实例的替身,他只是帮实例占据一个位置,等实例到来他就退位被实例所替代)
如果想在类的内部调用类属性,而实例又还没创建之前,我们就需要有个变量先代替实例接收数据,这个变量就是参数self。
class Chinese:
name = '吴枫' # 类属性name
def say(self):
print(self.name + '是中国人')
#这里不能直接用name,在实例没被创建前需要self来做替身
person = Chinese() # 创建Chinese的实例person
person.say() # 调用实例方法
#当最后一行代码运行时,实例person会像参数一样传给self,替换掉self,第六行的self.name等价于person.name。
同理,如果想在类的方法内部调用其他方法时,我们也需要用到self来代表实例。
class Chinese:
def greeting(self):
print("很高兴认识你")
def say(self):
self.greeting()
print("我来自中国")
person = Chinese()
#创建实例persom
person.say()
#调用方法say
#此时self.greeting()就变成person.greeting()
记住:
①只要在类中用def创建方法时,就必须把第一个参数位置留给 self,并在调用方法时忽略它(不用给self传参)
②当在类的方法内部想调用类属性或其他方法时,就要采用self.属性名或self.方法名的格式。
定义初始化方法的格式是def init(self),是由init加左右两边的【双】下划线组成( initialize “初始化”的缩写)。
初始化方法的作用在于:当每个实例对象创建时,该方法内的代码无须调用就会自动运行。
class Chinese:
def __init__(self):
print("很高兴认识你,我是初始化方法")
person = Chinese()
class Chinese:
def __init__(self):
self.mouth = 1 #self不能忘记
self.eye = 2
def boby(self):
print("我有%s张嘴巴" %self.mouth)
print("我有%s只眼睛" %self.eye)
person = Chinese()
person.boby()
class Chinese:
def __init__(self, name, birth, region):
self.name = name # self.name = '吴枫'
self.birth = birth # self.birth = '广东'
self.region = region # self.region = '深圳'
def born(self):
print(self.name + '出生在' + self.birth)
def live(self):
print(self.name + '居住在' + self.region)
person = Chinese('吴枫','广东','深圳') # 传入初始化方法的参数
person.born()
person.live()
import math
class Project:
def __init__(self):
self.key = 1
def input(self):
choice = input("请选择计算类型:(1-工时计算,2-人力计算)")
if choice == "1":
self.size = float(input("请输入项目大小;(1代表标准大小,请输入小数)"))
self.number = int(input("请输入人力数量:(请输入整数)"))
self.time = None
if choice == "2":
self.size = float(input("请输入项目大小;(1代表标准大小,请输入小数)"))
self.number = None
self.time = float(input("请输入工时数量:(请输入小数)"))
def estimated(self):
#人力计算
if (self.number == None) and (self.time !=None):
self.number = math.ceil(self.size * 80 / self.time)
print("项目大小为%.1f个标准项目,如果需要在%.1f个工时完成,则需要人力数量为:%d人" %(self.size,self.time,self.number))
elif (self.number !=None) and (self.time == None):
self.time = self.size * 80 / self.number
print('项目大小为%.1f个标准项目,使用%d个人力完成,则需要工时数量为:%.1f个' %(self.size,self.number,self.time))
def again(self):
a =input("是否继续计算?继续请输入y,输入其他键将结束程序")
if a !="y":
self.key = 0
def main(self):
print("欢迎使用工作量计算小程序")
while self.key == 1:
self.input()
self.estimated()
self.again()
print("感谢使用工作量计算小程序")
#创建实例
project1 = Project()
project1.main()
class Robot:
def __init__(self):
self.name = input("我现在刚诞生,还没用名字,帮我取一个吧")
self.master = input("对了,我该怎么称呼您呢?")
print("你好%s,我叫%s。很开心,遇见你" %(self.master,self.name))
def say_wish(self):
wish = input("告诉我你的愿望吧")
print(self.master+"的愿望是:")
#这里也可以用字符串的格式化,不过,用循环语句的话,之后改复述会方便一点
for i in rang(3):
print(wish)
robot1 = Robot
robot.say_wish()
第 13 关 类与对象(二)(涉及到的函数isinstance)
类的继承:
class A(B): #A是子类名,是父类名
class Chinese:
eye = "black"
def eat (self):
print("吃饭,选择用筷子")
class Cantonese(Chinese):
#通过继承,Chinese类有的,Cantonese类也有
pass
yewen = Cantonese()
print(yewen.eye)
yewen.eat()
object,是所有类的父类,我们将其称为根类(可理解为类的始祖)。
isinstance()函数:(第一个是实例,第二个是类或类组成的元组)
输出的只为True或False
print(isinstance(1,int))
#判断1是否为整数类的实例
print(isinstance(1,str))
print(isinstance(1,(int,str)))
#判断实例是否属于元组里几个类中的一个
#输出:
True
False
True
各级实例和各级类的关系:(多层继承)
①子类创建的实例,通属于父类;
②父类创建的实例,不属于子类;
③所有的实例,都属于跟类object
④父类可以被无限个子类继承
多重继承:
class A(B,C,D): (会先在左侧的父类中找,找不到才会去右侧的父类找。(可理解为“就近原则,即先在左边找,找不到在去右边找”))
class Su:
born_city = "jiangsu"
wearing = "thinck "
def diet(self):
print("我们爱吃甜。")
class Yue:
settle_city = "guangdong"
wearing ="thin"
def diet(self):
print("我们吃的清淡")
class Yuesu(Yue,Su):
pass
xiaoming = Yuesu()
print(xiaoming.wearing)
print(xiaoming.born_city)
xiaoming.diet()
#输出:
thin
jiangsu
我们吃的清淡
class C0:
name = "C0"
class C2(C0):
mun = 2
class C1:
num = 1
class C3:
name = "C3"
class C4(C1,C2,C3):
pass
ins = C4()
print(ins.name)
print(ins.num)
#输出:
C0
1
可以发现就近原则中的一个细节:多重继承中,若某父类还有父类的话,会先继续往上找到顶。例如代码中的ins.name调用的是C2的父类C0的值而非 C3。
定制:新增代码:
class Chinese():
eye = "black"
def eat(self):
print('吃饭,选择用筷子。')
class Cantonese(Chinese): # 类的继承
native_place = 'guangdong' # 类的定制
def dialect(self): # 类的定制
print('我们会讲广东话。')
yewen = Cantonese()
print(yewen.eye)
# 父类的属性能用
print(yewen.native_place)
# 子类的定制属性也能用
yewen.eat()
# 父类的方法能用
yewen.dialect()
# 子类的定制方法也能用
定制:重写代码
class Chinese:
def land_area(self,area):
print("我们居住的地方,陆地面积是%d万平方公里左右。"% area)
class Cantonese(Chinese):
#直接对方法进行重写
def land_area(self,area):
print("我们居住的地方,陆地面积是%d万平方公里左右。"%int(area*0.0188))
gonger = Chinese()
yewen = Cantonese()
gonger.land_area(960)
yewen.land_area(960)
子类继承父类方法的操作是在def语句后接父类.方法(参数)
class Chinese:
def land_area(self,area):
print("我们居住的地方,陆地面积是%d万平方公里左右。"% area)
class Cantonese(Chinese):
#间接对方法进行重写
def land_area(self,area,rate = 0.0188):
Chinese.land_area(self,area*rate)
#直接继承父类方法,再调整参数。
gonger = Chinese()
yewen = Cantonese()
gonger.land_area(960)
yewen.land_area(960)
class Chinese():
def __init__(self,greeting = "你好",place = "中国"):
self.greeting = greeting
self.place = place
def greet(self):
print("%s!欢迎来到%s。"%(self.greeting,self.place))
class Cantonese(Chinese):
def __init__(self,greeting = "雷猴",place = "广东"):
Chinese.__init__(self.greeting,place)
yewen = Cantonese()
yewen.greet()
class Teacher:
face = "serious"
job = "teacher"
class Father:
face = "sweet"
parenthood = "dad"
class TeacherMore(Teacher,Father):
pass
class FatherMore(Father,Teacher):
face = "gentle"
time3 = TeacherMore()
time4 = FatherMore()
print(time3.face)
print(time4.face)
#输出:
serious
gentle
class Student:
def __init__(self,name,job = None,time = 0.00,time_effective = 0.00):
self.name = name
self.job = job
self.time = time
self.time_effective = time_effective
def count_time(self,hour,rate):
self.time += hour
self.time_effective += hour * rate
class Programmer(Student):
def __init__(self,name):
Student.__init__(self,name,job = None,time = 0.00,time_effective =0.00 )
def count_time(self,hour,rate = 1):
Student.count_time(self,hour,rate)
student1 = Student("韩梅梅")
student2 = Programmer("李雷")
print(student1.job)
print(student2.job)
student1.count_time(10,0.8)
student2.count_time(10)
print(student1.time_effective)
print(student2.time_effective)
第 14 关 流浪图书的旅途(涉及到的函数def str,)
只要在类中定义了__str__(self)方法,那么当使用print打印实例对象的时候,就会直接打印出在这个方法中return的数据。
class Book:
def __init__(self,name,author,comment,state = 0):
self.name = name
self.author = author
self.comment = comment
self.state = state
def __str__(self):
status = "未借出"
if self.state == 1:
status = "以借出"
return "名称:<<%s>> 作者:%s 推荐语:%s\n 状态:%s"%(self.name,self.author,self.comment,status)
class BookManager:
books = []
def __init__(self):
book1 = Book("惶然录","费尔南多.佩索阿","一个迷失方向且频于崩溃的灵魂的自我启示,一首对默默无闻、失败、智慧、困难和沉默的赞美诗。")
book2 =Book("以箭为翅","简媜","调和空灵文风与神宗境界,刻画人间之缘起缘灭,像一条柔韧的绳子,情这个字,不知勒同多少人的心肉。")
book3 = Book("心是孤独的猎手","卡森.麦卡勒斯","我们渴望倾诉,却从未倾听,女孩黑人,哑巴,醉鬼,耶夫的孤独形态各异,却从未退场,",1)
self.books.append(book1)
self.books.append(book2)
self.books.append(book3)
def menu(self):
print("欢迎使用流浪图书管理系统,每本沉默的好书都是一座流浪的岛屿,希望你有缘发现并着陆,为精神家园找到一片栖息地。\n")
while True:
print("1、查询所有书籍\n2.添加书籍\n3.借阅书籍\n4.归还数据\n5.推出系统\n")
choice = int(input("请输入数字选择对应功能:"))
if choice == 1:
self.show_all_book()
elif choice == 2:
self.add_book()
elif choice == 3:
self.lend_book()
elif choice == 4:
self.return_book()
elif choice == 5:
print("感谢使用:愿你我成为爱书之人,在茫茫书海里相遇。")
break
def show_all_book(self):
print("书籍信息如下:")
for book in self.books:
print(book)
print("")
def add_book(self):
new_name = input("请输入书籍名称:")
new_author = input("请输入作者名称:")
new_comment = input("请输入书籍推荐语:")
new_book = Book(new_name,new_author,new_comment)
self.books.append(new_book)
print("书籍录入成功:\n")
def check_book(self,name):
for book in self.books:
if book.name == name:
return book
#这里的else要写在for外面,不然for只会遍历一次就执行else语句
else:
return None
def lend_book(self):
name = input("请输入书籍名称:")
res = self.check_book(name)
if res != None:
if res.state == 1:
print("你来玩了一步,这本书已经被借走了")
else:
print("解阅成功,借了不看会变胖哦~")
res.state = 1
else:
print("这本书暂时没有收录在系通里")
def retunrn_book(self):
name = input("请输入书籍的名称:")
res = self.check_book(name)
#调用check_book方法,将返回值赋值给变量res
if res == None:
#如果返回只是空值,将返回值赋予给变量res
print("没有这本书啊,您恐怕输错了书名~")
else:
#如果返回值是实例对象
if res.state == 0:
#如果实例属性state等于0,即这本书没被借走
print("这本输没有被借走,在等待有缘人的垂青呢!")
else:
print("归借成功!")
res.state = 0
#归还书后借阅状态为0,重置为"未借出"
manager = BookManager()
manager.menu()
练习:
class Book:
def __init__(self,name,author,comment,state = 0):
self.name = name
self.author = author
self.comment = comment
self.state = state
#创建一个Book类的子类 FictonBook
class FictonBook(Book):
def __init__(self,name,author,comment,state=0,type="虚构类"):
Book.__init__(self,name,author,comment,state=0)
self.type=type
#继承并定制父类的初始化方法,增加默认参数 type = "虚构类",让程序能够顺利执行。
def __str__(self):
status = "未借出"
if self.state == 1:
status = "已借出"
return "类型:%s 名称:《%s》 作者:%s 推荐语:%s \n状态:%s" %(self.type,self.name,self.author,self.comment,status)
book = FictonBook("囚鸟","冯内古特","我们都是受困于时代的囚鸟")
print(book)
class Book:
def __init__(self,name,author,comment,state=0):
self.name = name
self.author = author
self.comment = comment
self.state = state
def __str__(self):
status = "未借出"
if self.state == 1:
status = "已借出"
return "名称:《%s》,作者:%s 推荐语:%s\n 状态:%s" %(self.name,self.author,self.comment,status)
class BookManager:
authors = []
def __init__(self):
book1 = Book('撒哈拉的故事','三毛','我每想你一次,天上便落下一粒沙,从此便有了撒哈拉。')
book2 = Book('梦里花落知多少','三毛','人人都曾拥有荷西,虽然他终会离去。')
book3 = Book('月亮与六便士','毛姆','满地都是六便士,他却抬头看见了月亮。')
self.books = [book1,book2,book3]
self.authors.append(book1.author)
self.authors.append(book2.author)
self.authors.append(book3.author)
def menu(self):
while True:
print("1.查询书籍")
choice = int(input("请输入数字选择对应的功能"))
if choice == 1:
self.show_author_book()
else:
print("感谢使用")
break
def show_author_book(self):
author = input("请输入想查询作家的名称")
if author in self.authors:
print(author+ "的作品有:")
for book in self.books:
if book.author ==author:
print(book)
else:
print("我们暂时还没有收录这位作家的作作品")
manager = BookManager()
manager.menu()
第 15 关计算机的"新华字典"
编码表 实用性 特点
ASCLL码 英文大小写,字符,不支持中文 美国人的发明,占用空间小
GB2312码,GBK码 支持了中文 GBK码是GB1312码的升级
Unicode码 支持国际语言 占用空间大,适应性强
UTF-8码 支持国际语言 是Unicode码的升级,两者可以非常容易的相互转换,占用空间小ASCLL码被UTF-8码包含
编码和解码:
·
print("吴枫".encode("UTF-8"))
print("吴枫".encode("GBK"))
print("路径".decode("UFT-8"))
print("路径".decode("GBK"))
将人类语言编码后得到的结果,有一个相同之处,就是最前面都有一个字母b,比如b’\xce\xe2\xb7\xe3’,这代表它是**bytes(字节)**类型的数据。
所谓的编码,其实本质就是把**str(字符串)类型的数据,利用不同的编码表,转换成bytes(字节)**类型的数据。
\x是分隔符,用来分隔一个字节和另一个字节。
文件的读写:
①新建一个txt文档,写点东西,并保存。
②新建一个后缀为py的python文件
③写代码
Windows系统里,常用\来表示绝对路径,/来表示相对路径。别忘了\在Python中是转义字符,所以时常会有冲突。为了避免入坑有以下两种操作:
open(‘C:\Users\Ted\Desktop\test\abc.txt’)
①将\替换成\
open(r’C:\Users\Ted\Desktop\test\abc.txt’)
②在路径前加上字母r
file1 = open(’/Users/Ted/Desktop/test/abc.txt’,‘r’,encoding=‘utf-8’)
第一个参数是路径
第二个参数是打开的模式
第三个参数是采用何种编码
encoding而不是encode噢。
"r"是读,"w"是写,"a"是追加模式
读文件:
file1 = open("路径","r",encoding="utf-8")
filecontent = file1.read()
#读取file1中的内容,写法是file1后面加个.句点,再加个read(),并且把读到的内容放在filecontent里面,这样我们才能拿到文件的内容。
print(filecontent)
file1.close()
#file1后面加个.句点在加上close(),就表示关闭文件。
#为啥要关闭文件呢?原因有两个:1.计算机能够打开的文件数量是有限制的,open()过多而不close()的话,就不能再打开文件了。2.能保证写入的内容已经在文件里被保存好了。
#文件关闭之后就不能再对这个文件进行读写了。如果还需要读写这个文件的话,就要再次 open() 打开这个文件。
写文件:注意,无论是都还是写还是追加都要在路径后添加相应的字母,所以一次只能执行这三者的其中之一。
file1 = open("路径","w",encoding="uft-8")
file1.write("张无忌\n")
file1.write("宋书青\n")
file1.close()
提示:1.write()函数写入文本文件的也是字符串类型。2.在’w’和’a’模式下,如果你打开的文件不存在,那么open()函数会自动帮你创建一个
#普通写法
file1 = open("路径","a")
file1.write("张无忌")
file1.close()
#使用with关键字写法
with open("路径","a","encoding = utf-8") as file1:
#with open ("文件地址","读写模式") as 变量名:
#格式:冒号不能丢
file1.write("张无忌")
#格式:对文件的操作要缩进
#格式:无需用close关闭
readlines():readlines() 会从txt文件取得一个列表,列表中的每个字符串就是scores.txt中的每一行。而且每个字符串后面还有换行的\n符号
file1 = open ("路径","r",encoding = "utf-8")
file_lines = file1.readlines()
file1.colse()
print(file_lines)
#输出:
#["罗恩 23 35 44 \n","哈利 60 77 68 88 90\n"]
split():会按空格把字符串里面的内容分开,看上图第一行的罗恩 23 35 44,它将被分为[‘罗恩’, ‘23’, ‘35’, ‘44’]。
file1 = open("路径","r",encoding="utf-8")
file_lines = file1.readlines()
file.colse()
for i in file_lines:
print(i)
#输出:
#罗恩 23 35 44
#哈利 60 77 68 88 90
file1 = open("路径","r",encoding = "utf-8")
file_lines = file1.readines()
file.colse()
for i in file_lines:
data = i.split()
print(data)
#输出:
#["罗恩","23","35","44"]
#["哈利","60","77","68","88","90"]
join():用法是srt.join(sequence),str代表在这些字符串中你要用什么字符串连接,在这里两个例子,一个是空字符串,一个是横杠,sequence代表数据序列,在这里是列表a。
a = ["c","a","t"]
b = ""
print(b.join(a))
c ="-"
print(c.join(a))
#输出
#act
#c-a-t
第16关 哆啦A梦的百宝箱
模块:".py"为后缀的文件即为模块
类:使用class语句封装一个类
函数:使用def语句封装一个函数
变量:使用赋值语句赋值一个变量
每个单独的py文件本质上就是一个模块
类也可以直接被引用
#text.py
a = "我是模块中的变量a"
def hi():
a = "我是函数中的变量a"
print("hi函数已运行")
class Go2():
a = "我是2中的变量a"
def do2(self):
print("函数do2已运行") 0
#main.py
import text
print(text.a)
text.hi()
A = test.Go2()
print(A.a)
A.do2()
import
当我们导入模块后要使用模块中的变量,函数,类,需要在使用时加上**模块.**的格式
import语句还有一种用法就是import…as…。比如我们觉得import story太长,就可以用import story as s语句,意思是为"story"取个别名叫"s"。
当我们需要同时导入多个模块的时候,可以用逗号隔开。比如import a,b,c可以同时导入“a.py,b.py,c.py”三个文件
from import
from import 语句可以让你从模块中导入一个指定部分到当前模块,
格式:
from (模块名) import (指定模块中的变量名/函数名/类名)
效果:
1.导入模块中的指定部分(变量名/函数名/类名)
2.导入后的部分可以直接使用,无需加上“模块.”前缀
如:
#test.py
def hi()
print("函数hi已运行")
#mian.py
form test import hi #从模块test中导入函数hi
hi() #使用函数hi时无需加“模块.”前缀
当我们需要从模块中导入多个指定内容,也可以用逗号隔开,写成 from xx模块 import a,b,c形式
注意:
没有写作import 后面的内容将不被导入
当我们需要从模块中指定所以内容直接使用,可以直接写成【**from xx模块 import ***】,*代表模块中所以的变量,函数,类
不过,一般情况下,我们不要为了图方便直接使用【from xx模块 import 】的形式
这是因为,模块.xx的调用形式可以通过阅读代码一眼就看出是在调用模块中的变量/函数/类/方法,而去掉模块.*后代码就不那么直观了
if __name=="main"函数
xx.py文件:
代码块①…
if name==“main”
代码块②…
- 当xx.py文件直接被执行时,代码块②将被运行。
- 当xx.py文件作为模块是被其他程序所调用时,代码块②将不执行。
这里的【if name == ‘main’】就相当于是 Python 模拟的程序入口。Python 本身并没有规定这么写,这是一种程序员达成共识的编码习惯。
自学模块:
import random
a = random.sample("abcdefg",3) #随机从字符串列表等对象中抽取多个不重复的元素
print(a)
items = [1,2,3,4,5,6,7] #随机洗牌,比如打乱列表
random.shuffle(items)
print(items)
我们可以用dir函数来查看一个模块,看看里面有什么变量,函数,类,类方法 。
import random
print(dir(random))
这就像是查户口一样,可以把模块中的函数(函数和类方法)一览无余地暴露出来。对于查到的结果"xx"结构的(如__doc__),它们是系统相关的函数,我们不用理会,直接看全英文的函数名即可。
1.这个模块有哪些函数可以用? 对应 (可以通过dir函数查询)
2.有哪些方法或属性可以用? 对应 (去网上看文档或找教程)
3.使用格式是 什么? 对应 (从文档或教程中收集案例)
例如数据分析需要用到pandas和NumPy模块,网页开发要用到Django模块等等,这些大型模块最好还是在课程上系统学习,避免散乱的学习形不成知识体系。
学习csv模块:
学习的网站:https://docs.python.org/3.6/library/csv.html
https://yiyibooks.cn/xx/python_352/library/csv.html#module-csv
读取csv中的内容:
import csv
with open ("test.csv,newline="",encoding = utf-8")as f :
reade = csv.reader(f)
for row in reade:
print(row)
在csv中追加数据
import csv
with open("test.csv","a",newline="")as f : #a代表追加文件
writer = csv.writer(f) #实例化对象writer(可以是其他的名字)
writer.writerow([1,2,3,4,5]) #调用writer.writerow()方法写入一行数据
import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为",localtime)
#打印出Wed(星期几) Jan(几月) 27(多少号) 00:11:39(时间,时分秒) 2021(年份)
import time
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
#打印出2021-01-27 00:11:39(年月日,时分秒)
练习:
import time
input("欢迎使用“时间管理器”请按回车继续")
while True:
task_name = input("请输入任务名")
task_time =int(input("你觉得自己至少可以专注这个任务多少分钟?输入N分钟"))
input("此次任务信息:\n我要完成的任务:%s\n我至少要专注%d分钟\n按回车开始计时;" %(task_name,task_time))
start = time.time() #计时开始
start_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) #格式化日期
#实际代码:分钟转化成秒要乘以60,用-1来计时
#for t in range(task_time*60,0,-1):
for t in range(task_time,0,-1):
info = "请专注任务,还要保持专注" + str(t) + "秒哦"
print(info,end="")
print("\b"*(len(info)*2,end="",flush=True)
#https://jingyan.baidu.com/article/48a420571dfd70a925250410.html
#"\b" * (len(mystr)*2)这句话的意思是,打印'\b'这个转义字符,然后打印len(info)*2次。len得到字符串长度,
#为什么要*2呢?要知道,我们用的字符串是中文,而1个中文字符 = 2个英文字符(占位),所以,如果字符串是英语,我们完全可以不*2,flush = True则是开启缓冲区.\b转义字符起了退格的功能,
#相当于在编辑文件的时候按下BackSpace键,从光标位置往前删掉一个字符
time.sleep(1)
print("你已经专注了%d分钟,很棒~再加吧劲完成任务!%task_time") #倒计时后,才继续运行之后的代码
#询问任务是否已完成
task_status = input("请在任务完成后输入y:")
if task_status =="y":
end =time.time() #用户一定按下了y,就记下结束的时间
end_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) #日期格式化
actual_time = int((end-start)/60) #始末时间相减,从秒换成分,除以60
start_end = start_time+"--"+end_time+"\n"
with open("timelog3.txt","a",encoding="utf-8") as f :
f.write(task_name+"的预计时长为:"+str(task_time)+"分钟\n")
f.write(task_name+"的实际时长为"+str(actual_time)+"分钟,具体的时间为:"start_end)
again = input("建立一个新的任务请按y,退出时间日志记录器请按q:")
if again == "q":
break
else:
print("抱歉,您的输入有误,请重新启动时间记录器")
print("愿被你善待的时光,予你美好的回赠")
第17关 邮件还能这么发
发送邮件的参数说明:
sendnail()方法的使用说明
①connect(host,post)方法参数说明
host:指定链接的邮箱服务器
post指定服务器链接端口
②login(user,password)方法参数说明
user:登录邮件用户名
password:登录邮箱密码
③sendmail(from_addr,to_addr,msg…)方法参数说明
from_addr:邮件发送者地址
to_addr:字符串列表,邮件发送地址
msg:发送信息
④quit()结束当前对话
import smtplib
server = smtpnil.SMTP()
server.connect(host,post)
server.login(username,password)
server.sendmail(sender,to_addr,msg.as_string())
server.quit()
SMTP是一个类,要想调用 smtplib 模块下、SMTP 类下的方法,应该这样写:smtplib.SMTP.方法为了减少代码冗余,已经将需要重复出现的smtplib.SMTP赋值给了变量
我们需要通过SMTP指定一个服务器,这样才能把邮件送到另一个服务器
msg.as_string()是一个字符串类型:as_string()是将发送的信息msg变为字符串类型。
from email.mime.text import MIMETexr #内容形式为纯文本、HTML页面
from email.mime.image import MIMEmage #内容形式为图片
from email.mime.multipart import MIMEMultipart #多形式组合,可包含文本和附件
请你按住ctrl同时点击mime,你会看到一个名为init.py的空文件,这说明 email是其实是一个“包”。
这就要谈到“模块”和“包”的区别了,模块(module)一般是一个文件,而包(package)是一个目录,一个包中可以包含很多个模块,可以说包是“模块打包”组成的。
但为什么看到那个空文件,就能知道email是包呢?这是因为Python中的包都必须默认包含一个init.py的文件。
init.py控制着包的导入行为。假如这个文件为空,那么我们仅仅导入包的话,就什么都做不了。所以直接import email是行不通的
所以,我们就需要使用from … import …语句,从email包目录下的【某个文件】引入【需要的对象】。比如从email包下的text文件中引入MIMEText方法。中文说起来有点复杂,看代码就懂了
#smtpliab 用于邮件的发信动作
import smtplib
#email 用于构建邮件内容
from email.mime.text import MIMEText
#用于构建邮件头
from email.header import Header
#发信方的信息:发信邮件,QQ邮箱的授权码
from_addr =input("请输入登录邮箱") #"2911922647@qq.com"
password =input("请输入邮箱授权码") #"igysteexksenddha"
#收信方邮件
to_addr =input("请输入收件方的邮件") #"3263862119@qq.com"
text = """现在
上大
阿斯顿阿三
阿斯顿哇
"""
#发信服务器
smtp_server = "smtp.qq.com"
msg = MIMEText(text,"plain","utf-8")
#邮件头部(头部函数中的发件人,收件人,主题)
msg["From"] = Header(from_addr)
msg["To"] = Header(to_addr)
msg["Subject"] = Header("python test")
#开启发信服务,这里使用的是加密传输
server = smtplib.SMTP_SSL(smtp_server) #因为python的版本是3.7的所以需要在后面添加host
server.connect(smtp_server,465) #这里的smtp_server里是host
#登录发信邮件
server.login(from_addr,password)
#发送邮件
server.sendmail(from_addr,to_addr,msg.as_string())
#关闭服务器
server.quit()
①如果报错可能是版本出现了冲突
#改动这句
server = smtplib.SMTP_SSL()
#在括号内加入host参数
server = smtpilb.SMTP_SSL(smtp_server)
②如果是使用qq邮箱以外的邮箱出现报错,可以在登录之前调用starttls()方法就可以了
server.starttls()
③还有一种可能是端口出现了问题,可以试着更改一下端口的数值
加入头部文件
主要Header接受的第一个参数类型必须是字符串或者字节,列表不能解码,我们可以用join来解决这一问题
to_addrs = ["wufeng@qq.com","jialli@qq.com"]
print(",".join(to_addrs))
群发邮件
①设置一个列表形式的变量
注意收件人要将to_addr改为to_addrs
②用while循环
③调用csv模块
练习
制作二维码
from MyQR import myqr
myqr.run(
words = "www.baidu.com"
#扫描二维码后显示的内容或是跳转的链接
version = 5
#设置容错率
level = "H"
#控制纠错水平,范围是L,M,Q,H从左到右依次升高
picture = r "图片路径"
#图片所在目录
colorized = True
#黑白(False)还是彩色(True)
contrast = 1.0
#用以调节图片的对比度,1.0表示原始图片,默认1.0
brightness = 1.0
#用来调节图片的亮度,用法同上
save_name = r"二维码需要放在的地方"
#控制输出文件名,格式可以是.jpg,.png,.bmp,.gif
)
求绝对值
import math
#方法一:条件判断
def abs_value1():
a = float(input("1.请输入一个数字"))
if a>=0:
a = a
else:
a=-a
print("绝对值为%f" %a)
#方法二:内置函数abs()
def abs_value2():
a = float(input("2.请输入一个数字"))
a = abs(a)
print("绝对值为%f" %a)
#方法三:内置模块 math
def abs_value3():
a =float(input("3.请输入一个数字"))
a = math.fabs(a)
print("绝对值为%f" %a)
abs_value1()
abs_value2()
abs_value3()
第18关需求(培养思维)
流程图的三种:
①顺序结构
②条件结构
③触发结构
练习:
# 帮你做选择之我要吃什么
import random
# 将需要用到的表格和变量放在开头
list_food = ['KFC', '蒸菜馆', '楼下快餐店', '桂林米粉', '东北饺子', '金牌猪脚饭', '三及第汤饭'] # 备选菜单,可自定义。
list_choice = []
# 由于两个原因都包含判断过程,所以,为了让代码更简洁,可将其封装成函数。
def choose(list):
while True:
food = random.choice(list)
judgement = input('去吃【%s】好不好啊?同意的话输入y,不想吃直接回车即可。'%(food))
if judgement == 'y':
print('去吃【%s】!就这么愉快地决定啦!'%(food))
break
# 判断环节
reason = int(input('你不知道吃什么的原因是:1.完全不知道吃什么;2.在几家店之间徘徊(请输入1或2):'))
if reason == 1:
choose(list_food)
elif reason == 2:
add = True
while add:
choice = input('请输入让你犹豫的店名(注:一家一家输,完成后输入y):')
if choice != 'y': # 这个判断语句,是为了不将 y 也添加到菜单里。
list_choice.append(choice)
if choice == 'y':
add = False
choose(list_choice)
else:
print('抱歉,目前还不支持第三种情况——不过,你可以加代码哦。')
# 运行前可将第8行改为 for i in range(20) 控制一下循环次数。
# 或者,可以直接运行,然后用“刷新网页”这种方法强行打断程序。
import os, time
def main(): # 用函数封装,可复用性会高一些(可在其他的.py文件里调用该函数。)
content = ' 风变编程,陪你一起学Python ' # 广告词可自定义。
while True:
# linux/os x系统【清除屏幕】代码(线上使用本代码)
os.system('clear') # 清屏和打印结合起来,形成滚动效果。
# windows系统【清除屏幕】代码
'''
os.system('cls')
'''
print(content)
content = content[1:] + content[0] # 这行代码相当于:将字符串中第一个元素移到了最后一个。
time.sleep(0.25) # 你可以改下时间,体会“循环周期”和“滚动速度”之间的关联。
if __name__ == '__main__': # 类里面学到的检测方法,在函数中其实也可以用。
main()
第19关高效偷懒的正确姿势
在制作表格的时候要清楚那些数据是比较固定的可以只输入一次的(如:小区的地址,建造的年份),哪些是变量需要多次输入的(小区用户的楼层,楼号)。
用csv写入表头
import csv
with open(“assets.csv”,“a”,newline="")as csvfile:
#调用open()函数打开csv文件,传入参数:文件名“assets.csv”、追加模式“a”、newline=""
writer = csv.writer(csvfile,dialect=“excel”)
用
pow >>>>乘幂 等用于**
ord计算ASCII码
abs >>>>返回数字的绝对值
print("1".center(20))
print(format("121","^20"))
print(format("12321","^20"))
print("1".rjust(20,"*"))
print(format("121","*>20"))
print(format("12321","*>20"))
name = "jay"
print("he is {name}")
#输出:
he is jay
import getpass
username = input("用户名")
passwd = getpass.getpass("密码:")
if username == "恐龙妹" and passwd =="password":
print("登录成功")
else:
print("登录失败")
try:
f = open(file,mode)
except:
#发生异常时执行的操作
finally:
f.close()