[英]How can I make it so that instead of weed divide 100 it would be weed divide by the total weeds everyone pulled?
[英]How can I make it where it doesn't divide by 0?
我正在尝试获得单词长度的平均值。 如何防止它出现零除错误?
def main():
allwords = []
while True:
words = input("Enter a line of words, press Enter to stop: ")
if not words:
break
allwords.extend(words.split())
average = sum(len(words) for words in allwords) / len(allwords)
print("There were {:.2f} words".format(len(allwords)))
print("Average word length {:.2f}".format(average))
main()
仅当至少有一个词时, average
才有意义; 当它为空时,您正在尝试计算0 / 0
,这是行不通的。 因此,当allwords
为空时,不要计算或显示average
:
def main():
allwords = []
while True:
words = input("Enter a line of words, press Enter to stop: ")
if not words:
break
allwords.extend(words.split())
# Moved average computation lower so only one if needed
print("There were {} words".format(len(allwords)))
if allwords: # Only run contents when you got at least one word
average = sum(len(words) for words in allwords) / len(allwords)
print("Average word length {:.2f}".format(average))
if __name__ == '__main__':
main()
最简单的选择是在继续之前检查allwords
是否包含某些内容:
def main():
allwords = []
while True:
words = input("Enter a line of words, press Enter to stop: ").strip()
if not words:
break
allwords.extend(words.split())
print("There were {:.2f} words".format(len(allwords)))
if allwords:
average = sum(len(words) for words in allwords) / len(allwords)
print("Average word length {:.2f}".format(average))
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.