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