3 回答
![?](http://img1.sycdn.imooc.com/54584d9f0001043b02200220-100-100.jpg)
TA贡献1111条经验 获得超0个赞
如果只需要非空格名字的话就这样:
#-*- coding: utf-8 -*-
import re
def sum_name_length():
sumLen=0
while True:
s=raw_input("Enter a name:")
if s=="":
break
elif re.search(r"\s",s):
print "Contains should not contains spaces!"
continue
else:
sumLen+=len(s)
print "The sum of all name lengths is %d"%sumLen
if __name__=="__main__":
sum_name_length()
改良版(名字只能是字母):
#-*- coding: utf-8 -*-
import re
def sum_name_length():
sumLen=0
while True:
s=raw_input("Enter a name:")
if s=="":
break
elif re.search(r"\s",s):
print "Contains should not contains spaces!"
continue
elif re.search(r"[^a-zA-Z]",s):
print "Name should only contains alphabet!"
continue
else:
sumLen+=len(s)
print "The sum of all name lengths is %d"%sumLen
if __name__=="__main__":
sum_name_length()
![?](http://img1.sycdn.imooc.com/5458626a0001503602200220-100-100.jpg)
TA贡献1836条经验 获得超4个赞
def sum_name_length():
print 'Enter your names, I will displays the sum of the lengths of all names entered'
length = 0
while True:
s = raw_input('Enter a name: ')
if s == '': break
length += len(s)
print 'The sum of all name lengths is', length
if __name__ == '__main__':
sum_name_length()
添加回答
举报