python零基础入门03(超详细)

17.字典的定义和常用操作

映射的类型:字典
字典包含哈希值和指向的对象
{“哈希值”:”对象”} {‘length’:180, ‘with’:80}
dict1 = {}
print(type(dict1))
dict2 = {‘x’: 1, ‘y’ : 2}
dict2[‘z’] = 3
print(dict2)

chinese_zodiac = ‘猴鸡狗猪鼠牛虎兔龙蛇马羊’
zodiac_name = (u’摩羯座’, u’水瓶座’, u’双鱼座’, u’白羊座’, u’金牛座’, u’双子座’,
u’巨蟹座’, u’狮子座’, u’处女座’, u’天秤座’, u’天蝎座’, u’射手座’)
zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
(7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
cz_num = {}
print(type(cz_num))
for i in chinese_zodiac:
cz_num[i] = 0
z_num = {}
for i in zodiac_name:
z_num[i] = 0
while True:
#用户输入出生年份月份和日期
year = int(input(“请输入出生年份”))
month = int(input(‘请输入月份’))
day = int(input(‘请输入日期’))
n = 0
while zodiac_days[n] < (month, day):
if month == 12 and day >23:
break
n +=1
print(zodiac_name[n])
#输出生肖和星座
print(’%s年的生肖是%s’ % (year, chinese_zodiac[year%12]))
cz_num[chinese_zodiac[year % 12]] += 1
z_num[zodiac_name[n]] += 1

#输出生肖和星座的统计数量
for each_key in cz_num.keys():
    print('生肖%s 有 %d 个'%(each_key, cz_num[each_key]))
for each_key in z_num.keys():
    print('星座 %s 有 %d 个'%(each_key,z_num[each_key]))

18.列表推导式与字典推导式

#输出从1到10所有偶数的平方
alist = []
for i in range(1,11):
if (i%2 == 0):
alist.append(ii)
print(alist)
blist=[i
i for i in range(1, 11) if (i%2) == 0]
print (blist)

z_num = {}
for i in zodiac_name:
z_num[i] = 0
z_num={i:0 for i in zodiac_name}

19.文件的内建函数

open() 打开文件
read() 输入
readline() 输入一行
seek() 文件内移动
write() 输出
close()关闭文件

#将小说的主要人物记录在文件中
file1 = open(‘name.txt’,‘w’)
file1.write(‘诸葛亮’)
file1.close()
file2 = open (‘name.txt’)
print(file2.readline())
file2.close()
file3 = open(‘name.txt’,‘a’)
file3.write(‘貂蝉’)
file3.close()

20.文件的常用操作

file4 = open(‘name.txt’)
print(file4.readline()) #
file5 = open(‘name.txt’) #
for line in file5.readlines(): #
print(line) #
print(’******’)

file6 = open(‘name.txt’)
print(‘当前文件指针的位置%s’ % file6.tell())
print(‘当前读取到了一个字符%s’%file6.read(1))
print(‘当前文件指针的位置%s’ % file6.tell())
file6.seek(0)

print(‘当前文件指针的位置%s’%file6.tell())
print(‘当前读取到了一个字符%s’%file6.read(1))
print(‘当前文件指针的位置%s’%file6.tell())
file6.seek(5,0)
print(‘当前文件指针的位置%s’%file6.tell())
file6.close()

seek(5,0)#第一个参数代表偏移位置,第二个参数0表示从文件开头偏移

21.异常的检测和处理

异常≠错误
异常是在出现错误时采用正常控制流以外的动作
异常处理的一般流程是:检测到错误,引发异常;对异常进行捕获的操作
try:
<监控异常>
except Exception[,reason]:
<异常处理代码>
finally:
<无论异常是否发生都执行>

22.函数的定义和常用操作

Split :分离
Strip :删除
函数是对程序逻辑进行结构化的一种编程方法

函数的定义: 函数的调用:
def函数名称(): 函数名称()
代码
return需要返回的内容

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值