Python习题及编码讲解
一、习题讲解:
1.1 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数:
while 1:
strings = input("Please inpur a string(quit will be exit): ")
alpha, dig, space, other = 0, 0, 0, 0
if strings.strip() == "quit":
exit(1)
for i in strings:
if i.isdigit():
dig += 1
elif i.isspace():
space += 1
elif i.isalpha():
alpha += 1
else:
other += 1
print("alpha = {0}".format(alpha))
print("dig = {0}".format(dig))
print("space = {0}".format(space))
print("other = {0}".format(other))
输出结果如下图:
解析:
1、设置一个while循环,如果需要退出则输入quit即可退出程序。
2、设置数字、字母、空格、其他字符的默认取值为0,使用input( )函数并使用for、if循环嵌套遍历计算输入的内容。
3、当输入一段内容后,程序会根据函数判断这段内容中存在的数字、字母、空格、其他字符的数量并打印出来。
4、isdigit( )函数判断是否数字;isalpha( )判断是否字母; isspace( ) 判断是否为空。
1.2 ABCD乘9=DCBA,A=? B=? C=? D=? 答案:a=1,b=0,c=8,d=9 1089*9=9801: