python的一道题目

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 in
the example below (where the user’s input is indicated in bold):
Enter a name: Chester
Enter a name: Pixel
Enter a name: Laptop
Enter a name: Whiskers
Enter a name:
The sum of all name lengths is 26
You may assume that a name does not contain any space characters.
谢谢了~

慕慕森
浏览 534回答 3
3回答

慕工程0101907

如果只需要非空格名字的话就这样:#-*- coding: utf-8 -*-import redef sum_name_length():sumLen=0while True:s=raw_input("Enter a name:")if s=="":breakelif re.search(r"\s",s):print "Contains should not contains spaces!"continueelse:sumLen+=len(s)print "The sum of all name lengths is %d"%sumLenif __name__=="__main__":sum_name_length()改良版(名字只能是字母):#-*- coding: utf-8 -*-import redef sum_name_length():sumLen=0while True:s=raw_input("Enter a name:")if s=="":breakelif re.search(r"\s",s):print "Contains should not contains spaces!"continueelif re.search(r"[^a-zA-Z]",s):print "Name should only contains alphabet!"continueelse:sumLen+=len(s)print "The sum of all name lengths is %d"%sumLenif __name__=="__main__":sum_name_length()

鸿蒙传说

def sum_name_length():print 'Enter your names, I will displays the sum of the lengths of all names entered'length = 0while True:s = raw_input('Enter a name: ')if s == '': breaklength += len(s)print 'The sum of all name lengths is', lengthif __name__ == '__main__':sum_name_length() 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python