lundi 11 novembre 2019

Else statement causing an infinite loop in basic word counting program?

I'm trying to create a basic word/character counting program for fun. I'm trying to do it without checking my notes or anything, and I'm a rather new self-taught programmer.

I have a while loop that contains an if-else chain. The else statement is being used to check for invalid inputs, as I only want the user input to be able to equal "characters" or "words". I want it to print that the input is invalid, and then return to the beginning of the while loop.

However, whenever the else statement is used, it causes an infinite printing loop, and does not return to the beginning of my while loop.

(General criticisms of my code are appreciated as well!)

I've tried using: continue, break (i don't want it to break, as I want to return to the beginning of my while loop), and a couple of other things, like setting my flag to False, and then back to True again.

import time

wordcounter_active = True

char_or_words = input("Would you like to count characters or words?" + 
" \nEnter 'characters' or 'words': " );

while wordcounter_active == True:
  #count characters or quit
  if char_or_words.lower() == ('characters'):
    count_char = input("\nEnter something to count it's characters: " + 
    "\nYou can also type 'quit' to exit the program. ");

    if count_char.lower() == ('quit'):
      print("Quitting...");
      wordcounter_active = False;
    else:
      char_input_len = len(count_char);
      print("\nThis input contains " + str(char_input_len) + " characters.");

  #count words or quit
  elif char_or_words.lower() == ('words'):
    count_word = input("\nEnter something to count it's words: " + 
    "\nYou can also type 'quit' to exit the program. ");

    if count_word.lower() == ('quit'):
      print("Quitting...");
      wordcounter_active = False;
    else:
      word_input_len = len(count_word.split())
      print("\nThis input contains " + str(word_input_len) + " words.");

  #invalid input
  else:
    print("Invalid input.");
    continue

Aucun commentaire:

Enregistrer un commentaire