python - 我怎样才能让它打印用户输入的最长的名称/字符串
问题描述
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 是最长的名字
解决方案
你已经有了它的功能。只需要调用函数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()
到上面计算平均值的函数中,参数为myNames
ie
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())
推荐阅读
- php - 使用 PHP 更新 html 页面值
- python - python中的tkinter在窗口中心对齐网格
- laravel - laravel 分页问题 - 所有链接类型都来了
- c - 在 C 中使用二维数组与一维数组的按位运算符进行乘法
- reactjs - 从 redux-store 在页面上渲染文本
- css - 使用 flexbox 创建列
- java - 再次调用 JavaFX 弹出窗口时抛出异常
- flutter - 如何在 Flutter 容器中设置背景颜色
- mysql - 从用户 id 等于用户电子邮件的另一个表上的 id 的表中删除
- sql-server - 将具有数据透视结构的 SQL 查询从一个表复制到另一个表