3 回答
TA贡献1887条经验 获得超5个赞
如果只需要非空格名字的话就这样:
#-*- 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()
TA贡献1865条经验 获得超7个赞
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()
添加回答
举报