首页 > 解决方案 > 我怎样才能让它打印用户输入的最长的名称/字符串

问题描述

def myNames():
    names = []
    while True:
        a = input("Enter Name: ")
        if a != "done":
            names.append(a)
        elif a == "done":
            return names

def all_lengths(myNames):
  num_of_strings = len(myNames)
  total_size = 0
  for item in myNames:
     total_size += len(item)
  ave_size = float(total_size) / float(num_of_strings)
  print(ave_size)

all_lengths(myNames())

def longestWord(myNames): 
    count = 0
    for i in myNames:
        if len(i) > count: 
            count = len(i)
            word = I
            print ("the longest string is ", word)

我怎样才能让它打印出用户输入的最长的名字,例如:在 Samantha 和 John 中,它会说 Samantha 是最长的名字

标签: pythonlistfunction

解决方案


你已经有了它的功能。只需要调用函数longestWord()

longestWord(myNames())在程序的最后。紧接着,

def longestWord(myNames): 
    count = 0
    for i in myNames:
        if len(i) > count: 
            count = len(i)
            word = i    # Need to type I in lower case
            print ("the longest string is ", word)

更新:由于您不希望函数再次询问名称,您可以将函数调用移动longestWord()到上面计算平均值的函数中,参数为myNamesie

def myNames():
    names = []
    while True:
        a = input("Enter Name: ")
        if a != "done":
            names.append(a)
        elif a == "done":
            return names

def longestWord(myNames): 
    count = 0
    for i in myNames:
        if len(i) > count: 
            count = len(i)
            word = i
            print ("the longest string is ", word)

def all_lengths(myNames):
  num_of_strings = len(myNames)
  total_size = 0
  for item in myNames:
     total_size += len(item)
  ave_size = float(total_size) / float(num_of_strings)
  print(ave_size)
  longestWord(myNames) # Calling the function with already given names
  
all_lengths(myNames())

推荐阅读