3 回答

TA貢獻1887條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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()
添加回答
舉報