Home > database >  How can I make it where it doesn't divide by 0?
How can I make it where it doesn't divide by 0?

Time:11-20

I'm trying to get the average of the word length. How can I prevent it from getting a zero division error?

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

CodePudding user response:

The average only makes sense when there is at least one word; when it's empty, you're trying to compute 0 / 0, which doesn't work. So don't compute or display the average when allwords is empty:

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

CodePudding user response:

The easiest option is to check if allwords contains something before continuing:

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