python核心编程-第6章课后习题答案

本篇博客主要探讨Python编程中与字符串和列表相关的练习题,包括字符串标识符检查、排序算法、算术计算、字符串操作以及IP地址与十进制的转换等。通过这些实践题目,读者可以深入理解Python语言的常用操作和数据结构应用。
摘要由CSDN通过智能技术生成

6-2. 字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.

#coding=utf-8

import string
import keyword

alphs = string.letters + '_'
num = string.digits

print 'Welcome to the Identifier Checker V1.0'
print 'Testees must be at least 1 chars long.'

myinput = raw_input('Identifier to test?')

if len(myinput)>=1:    
	if myinput[0] not in alphs:   #如果第一个数不是下划线或字母 
		print 'invalid: first symbol must be alphabetic'     #输出提示信息
	else:                             #如果第一个数是下划线或字母
		for otherchar in myinput[1:]:          #循环检查后面的是否符合要求
			if otherchar not in alphs+num:       #不符合要求输出错误信息
				print "invalid:remaining symboles"
				break
		else:                               
			if myinput in keyword.kwlist:    #符合要求进一步检查是否为python关键字
				print "invalid: symbol is reserved as keyword"
			else:
				print "okys as an identifier"

6-3 排序

(a) 输入一串数字,从大到小排列之.

(b) 跟 a 一样,不过要用字典序从大到小排列之

num = raw_input("Enter a string of numbers,for example (12,14,15):")
num = list(num.split(','))
num.sort(reverse=True)   
print num  

6-4.算术。更新上一章里面你的得分测试联系方案,把测试得分放到一个列表中去。你的代码应该可以计算出一个平均分,见联系2-9和联系5-3


def scoreCalculate(score):
	if 90<= score <= 100:
		print 'you score is A!'
	elif 80<= score <=89:
		print 'you score is B!'
	elif 70<= score <=79:
		print 'you score is C!'
	elif 60<= score <=69:
		print 'you score is D!'
	else:
		print 'you score is F!'
while 1:
	choice = ("1.Grade level \n 2.average:")
	if choice == "1":
		while 1:
			score= raw_input('enter you socre(q is qiut):')
			scoreCalculate(socre)
			if score == "q":
				break
	elif choice == "2":
		yourscore = []
		while True:
			score = raw_input("Enter your score (q for quit)-->")
			if score == 'q':
				break
			else:
				yourscore.append(int(score))
		average = float(sum(yourscore)) / len(yourscore)
		print average
	else:
		print "worry enter!"
		break

6-5字符串

  (a)更新你在练习2-7里面的方案, 使之可以每次向前向后都显示一个字符串的一个字符.

  (b)通过扫描来判断两个字符串是否匹配(不能使用比较操作符cmp()內建函数). 附加题: 在你的方案中加入大小写区分.

  (c)判断一个字符串是否重现(后面跟前面一致), 附加题: 在处理了严格的回文之外,加入对例如控制符号和空格的支持.

  (d) 接受一个字符在其后面加一个反向拷贝,构成一个回文字符串.


(a)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值