How can I make it where it will print the longest name/string that was inputed by the user

拥有回忆 提交于 2021-01-07 02:55:11

问题


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)

how can I make it print the longest name that was inputted by the user for example: out of Samantha and John it would say that Samantha was the longest name


回答1:


longestName = ""
for name in myNames:
    if len(name) > len(longestName):
        longestName = name
        
print("The longest name is", longestName)

This will check the length of each username, and if the name of that username is longer than the current longest username, it will replace it.




回答2:


You already have the function for it. Just need to call the function longestWord().

Write longestWord(myNames()) at the end of the program. Right after,

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)

Update: Since, you don't want the function to ask for names again, you can move the function calling longestWord()inside the above function where it calculates average, with the parameter as myNames i.e.

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


来源:https://stackoverflow.com/questions/65239433/how-can-i-make-it-where-it-will-print-the-longest-name-string-that-was-inputed-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!