码迷,mamicode.com
首页 > 编程语言 > 详细

Python核心编程课后习题-第六章

时间:2016-05-10 23:13:01      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

1. 字符串, string模块中是否有一种字符串方法或者函数可以帮我鉴定一下一个字符串是否是另一个大字符串的一部分?  

1 str1 = abcdefghijklmnopqrstuv
2 print str1.find(abcd) #若找到则返回子串的起始index, 若未找到则返回-1
3 print str1.count(abd) #若count数量大于0 则表示子串是str1的一部分.
4 print str1.index(abc) #若未找到返回异常, 找到则返回相应的index.

 

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

 1 import string
 2 import keyword
 3 
 4 alphas = string.letters + _
 5 nums = string.digits
 6 kw = keyword.kwlist
 7 
 8 print Welcome to the Identifier Checker v1.0
 9 print "Testees must be at least 2 chars long."
10 myInput = raw_input(Indetifier to test --> )
11 
12 if len(myInput) == 1:
13     if myInput[0] not in alphas:
14         print "invalid: first symbol must be alphabetic"
15     else:
16         print "Ok as an identifier length 1"        
17 
18 elif len(myInput) > 1:    
19     if myInput[0] not in alphas:
20         print "invalid: first symbol must be alphabetic"
21     elif myInput in kw:
22         print "Invalid: it a python keyword"
23     else:
24         for otherchar in myInput[1:]:
25             if otherchar not in alphas + nums:
26                 print "invalid: remaining symbols must be alphanumeric"
27                 break
28         else:
29             print "Okay as an identifier"

3. 排序

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

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

 

 

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

 1 def scoreCalculate(score):
 2     if score < 60:
 3         rank = F
 4     elif score < 70:
 5         rank = D
 6     elif score < 80:
 7         rank = C
 8     elif score < 90:
 9         rank = B
10     else:
11         rank = A
12     return rank
13 
14 yourscore = []
15 while True:
16     score = raw_input("Enter your score (q for quit)-->")
17     if score == q:
18         break
19     else:
20         yourscore.append(int(score))
21 average = float(sum(yourscore)) / len(yourscore)
22 print average

 

5. 字符串

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

  

Python核心编程课后习题-第六章

标签:

原文地址:http://www.cnblogs.com/chen0427/p/5479644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!