为了账号安全,请及时绑定邮箱和手机立即绑定

python的一道题目

python的一道题目

慕慕森 2019-04-14 11:08:00
Write a function sum_name_length that consumes no parameters and produces no value.The function will repeatedly ask the user to enter names until the empty string is entered.The function then displays the sum of the lengths of all names entered. This is illustrated inthe example below (where the user’s input is indicated in bold):Enter a name: ChesterEnter a name: PixelEnter a name: LaptopEnter a name: WhiskersEnter a name:The sum of all name lengths is 26You may assume that a name does not contain any space characters.谢谢了~
查看完整描述

3 回答

?
慕工程0101907

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()



查看完整回答
反对 回复 2019-04-15
?
鸿蒙传说

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()

 


查看完整回答
反对 回复 2019-04-15
  • 3 回答
  • 0 关注
  • 533 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信