有。in操作符;find()方法和count()方法和index()均能实现
import string import keyword alphas = string.letters + '_' nums = string.digits print "Welcome to the Identifier Checker v1.0" while True: myInput = raw_input("Identifier to test? ") if len(myInput) < 2: if myInput in alphas: print "Okay as an identifier" else: print '''invalid: first symbol must be alphabetic''' elif len(myInput) >= 2: if myInput in keyword.kwlist: print 'invalid: cannot be keywords!' elif myInput[0] not in alphas: print '''invalid: first symbol must be alphabetic''' else: for otherChar in myInput[1:]: if otherChar not in alphas + nums: print '''invalid: remaining symbol must be alphabetic''' break else: print "Okay as an identifier"
3.
a.
# -*- coding:utf-8 -*- import random print u"请根据提示输入数字" num_list = [] for i in range(random.randrange(2,11)): num = int(raw_input(u'请输入一个数字'.encode('gbk')).strip()) num_list.append(num) i = 0 while i <= len(num_list) - 2: for j in range(i,len(num_list)): if num_list[i] < num_list[j]: num_list[i], num_list[j] = num_list[j], num_list[i] i += 1 print num_list
b.
# -*- coding:utf-8 -*- import random print u"请根据提示输入数字" num_list = [] for i in range(random.randrange(2,11)): num = int(raw_input(u'请输入一个数字'.encode('gbk')).strip()) num_list.append(num) num_list.sort(reverse=True) print num_list
4.
# -*- coding:utf-8 -*- from __future__ import division stu_num = int(raw_input(u"请输入学生个数:".encode('gbk'))) score = [] print u"请依次输入每个学生的分数,Q结束输入" for i in range(stu_num): try: per_score = int(raw_input(u"请输入学生的得分".encode('gbk'))) score.append(per_score) except ValueError: break for k, j in enumerate(score): if 90 <= j <= 100: print u'第 %d 个学生, 你的分数是 %d, 评分是 "A"' % (k+1, j) elif 80 <= j <= 89: print u'第 %d 个学生, 你的分数是 %d, 评分是 "B"' % (k+1, j) elif 70 <= j <= 79: print u'第 %d 个学生, 你的分数是 %d, 评分是 "C"' % (k+1, j) elif 60 <= j <= 69: print u'第 %d 个学生, 你的分数是 %d, 评分是 "D"' % (k+1, j) else: print u'第 %d 个学生, 你的分数是 %d, 评分是 "E"' % (k+1, j) average = sum(score) / stu_num print u"所有学生的平均分是: %.2f" % average
5.
a.
strings = raw_input("Please enter something:") print strings[0], strings[1] for i, j in enumerate(strings): if 1 <= i <= len(strings) - 2: print strings[i - 1], j, strings[i + 1] print strings[-2], strings[-1]
b.
# -*- coding:utf-8 -*- str1 = raw_input(u"请输入第一个字符串".encode('gbk')) str2 = raw_input(u"请输入第一个字符串".encode('gbk')) if len(str1) != len(str2): print u"两个字符串不一致!!" else: for i in range(len(str1)): if str1[i] != str2[i]: print u"两个字符串不一致!!" break else: print u"两个字符串完全一致!!"
c.
# -*- coding:utf-8 -*- def if_palindrome(s): if len(s) % 2: print u'输入的字符串不是回文!' else: if s[:len(s)/2] == s[-1:len(s)/2-1:-1]: print u"输入的字符串是回文!" else: print u"输入的字符串不是回文!" a_string = raw_input(u"请输入一个字符串".encode('gbk')) if_palindrome(a_string)
d.
# -*- coding:utf-8 -*- def make_palindrome(): a_string = raw_input(u"请输入一个字符串: ".encode('gbk')) print "BEFORE Palindrome: ", a_string new_string = ''.join((a_string, a_string[::-1])) print "AFTER Palindrome: ", new_string make_palindrome()
6.
# -*- coding:utf-8 -*- def str_strip(s): s_strip = s if s.startswith(' '): i = 0 while i < len(s): if not s[i].isspace(): s_strip = s[i:] break i = i + 1 if s_strip.endswith(' '): j = -1 while j >= -len(s_strip): if not s_strip[j].isspace(): s_strip = s_strip[:j+1] break j = j - 1 return s_strip a_string = raw_input(u'请输入一个字符串:'.encode('gbk')) print str_strip(a_string)
7.
#! /usr/bin/env python # -*- coding:utf-8 -*- # 接收用户输入一个数字 num_str = raw_input('Enter a number: ') #把用户的输入转换成数字格式 num_num = int(num_str) #生成一个从1到用户输入的数字的列表 fac_list = range(1, num_num+1) print "BEFORE:", fac_list #定义i i = 0 #while循环实现删去能被用户输入的数字整除的项 while i < len(fac_list): #检验是否能被整除 if num_num % fac_list[i] == 0: del fac_list[i] i -= 1 #对i自加1,检验下一项 i = i + 1 #打印出最终结果 print "AFTER:", fac_list
8.
a.
# -*- coding:utf-8 -*- while True: num_str = raw_input(u'请输入一个整数:'.encode('gbk')) if num_str.isdigit(): break else: print u"请输入一个整数" num_list = list(num_str) eng_name_list = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] for i, j in enumerate(num_list): num_list[i] = eng_name_list[int(j)] print '-'.join(num_list)
b.
# -*- coding:utf-8 -*- while True: num_str = raw_input(u'请输入一个整数:'.encode('gbk')) if num_str.isdigit(): break else: print u"请输入一个整数" unit_list = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] ten_list = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] decade_list = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] hun = 'hundred' def single_figure(s): return unit_list[int(s)] def double_figures(s): num_list = list(s) num_num = int(s) if num_num in range(10, 20): return ten_list[num_num-10] elif int(num_list[1]) == 0: return ''.join(decade_list[int(num_list[0])-2]) else: num_list[0] = decade_list[int(num_list[0])-2] num_list[1] = unit_list[int(num_list[-1])] return '-'.join(num_list) def three_figures(s): num_list = list(s) num_num = int(s) num_list[0] = ' '.join((unit_list[int(num_list[0])], hun, 'and')) if int(num_list[1]) != 0: num_list[1:] = [double_figures(s[1:])] return ' '.join(num_list) elif int(num_list[1]) == 0 and int(num_list[-1]) != 0: num_list[1:] = single_figure(s[2]) return ' '.join(num_list) else: return ' '.join((unit_list[int(s[0])], hun)) if len(num_str) == 1: print single_figure(num_str) elif len(num_str) == 2: print double_figures(num_str) elif len(num_str) == 3: print three_figures(num_str) else: print u"输入的数字必须在0-1000之间!"
9.
# -*- coding:utf-8 -*- time = raw_input(u"请输入要转换的分钟数".encode('gbk')) result = list(divmod(int(time), 60)) print u"%d分钟等于%d小时加%d分钟。" %(int(time), result[0], result[1])
10.
# -*- coding:utf-8 -*- while True: a_string = raw_input(u'请输入要转换的英文字符串,退出输入Q: '.encode('gbk')) new_string = [] if a_string.lower() == 'q': break for i in a_string: if i.islower(): new_string.append(i.upper()) elif i.isupper(): new_string.append(i.lower()) else: new_string.append(i) new_string = ''.join(new_string) print u"转换前的字符串是:", a_string print u"转换后的字符串是:", new_string
11.
a.
# -*- coding:utf-8 -*- address = [] for i in range(4): per_address = raw_input(u'请依次输入四段IP地址,每段地址是0-255之间的整数:'.encode('gbk')) address.append(per_address) print u'您输入的IP地址是:%s' % '.'.join(address)
b.
# -*- coding:utf-8 -*- import sys address = [] for i in range(4): per_address = raw_input(u'请依次输入四段IP地址,每段地址是0-255之间的整数:'.encode('gbk')) address.append(per_address) print u'您输入的IP地址是:%s' % '.'.join(address) next = raw_input(u"接下来将进行逆转换,继续请回车,否则请输入Q退出".encode('gbk')) if next.lower() == 'q': sys.exit() num = ['一', '二', '三', '四'] for i in address: print u'转换后的四段分是:%s' % i
12.
a.
# -*- coding:utf-8 -*- def findchr(string, char): if char not in string: return -1 else: i = 0 while i < len(string): if string[i] == char: return i break i += 1
b.
# -*- coding:utf-8 -*- def rfindchr(string, char): if char not in string: return -1 else: i = -1 while i >= -len(string): if string[i] == char: return i + len(string) break i -= 1
c.
# -*- coding:utf-8 -*- def subchr(string, origchar, newchar): if origchar not in string: return u"未找到!" else: i = 0 while i < len(string): if string[i] == origchar: return ''.join((string[:i], newchar, string[i+1:])) break i += 1
13.
# -*- coding:utf-8 -*- def atoc(s): error = 'ValueError: atoc() areg is a malformed string' if '+' in s: if s[-1] != 'j' or s.count('j') >= 2: return error else: com = s.split('+') real = float(com[0]) imag = float(com[1][:-1]) return complex(real, imag) else: if s.count('j') == 1: real = 0 imag = float(s[:-1]) return complex(real, imag) elif s.count('j') >= 2: return error else: try: real = float(s[:]) imag = 0 return complex(real, imag) except ValueError: return error
14.
# -*- coding:utf-8 -*- import random print u'欢迎来到石头剪刀布!' choice_list = [u'石头', u'剪刀', u'布'] result = [] for i in choice_list: for j in choice_list: result.append((i, j))
15.
a.
# -*- coding:utf-8 -*- from datetime import datetime print u'这是一个计算两个日期之间天数的小程序' print u'日期的格式是MM/DD/YY' while True: date1 = raw_input(u'请输入第一个日期'.encode('gbk')) date2 = raw_input(u'请输入第二个日期'.encode('gbk')) date_format = '%m/%d/%Y' date1 = datetime.strptime(date1, date_format) date2 = datetime.strptime(date2, date_format) #date1_mm, date1_dd, date1_yy = [int(i) for i in date1.split('/')] #date2_mm, date2_dd, date2_yy = [int(i) for i in date2.split('/')] delta = date2 - date1 print u'两个日期之间相差%d天!' % delta.days
b.
# -*- coding:utf-8 -*- import datetime import time print u'这是一个计算出生至今共有多少天的小程序' print u'输入的出生日期的格式是MM/DD/YY' while True: Birthday = raw_input(u'请输入您的出生日期'.encode('gbk')) date_format = '%m/%d/%Y' today = datetime.datetime.strptime(time.strftime('%m/%d/%Y'), date_format) Birthday = datetime.datetime.strptime(Birthday, date_format) delta = today - Birthday print u'WOW!你出生已经%d天了!' % delta.days
c.
# -*- coding:utf-8 -*- import datetime import time print u'这是一个计算下次生日距今天的天数的小程序' print u'输入的出生日期的格式是MM/DD/YY' while True: Birthday = raw_input(u'请输入您的出生日期'.encode('gbk')) date_format = '%m/%d/%Y' today = datetime.datetime.strptime(time.strftime('%m/%d/%Y'), date_format) Birthday = Birthday.split('/') if '-'.join((Birthday[0], Birthday[1])) > datetime.datetime.now().strftime('%m-%d'): Birthday[2] = datetime.datetime.now().strftime("%Y") else: Birthday[2] = str(int(datetime.datetime.now().strftime("%Y"))+1) Birthday = '/'.join(Birthday) Birthday = datetime.datetime.strptime(Birthday, date_format) delta = Birthday - today print u'WOW!你的下次生日距今还有%d天!' % delta.days
17.
# -*- coding:utf-8 -*- def myPop(Alist): to_pop = Alist[-1] del Alist[-1] return to_pop