0

I am new to python and trying to figure out how to make this program only take a string or character and then have it spell out said string/character. Unfortunately, when using the lines while word != str() or chr(): word = input("Enter a string or character...") I am constantly prompted to "Enter a string or character" even when I inputted a string/character to begin with. How would I be able to go about fixing this so that the program takes a string and breaks out of the while loop so that it can spell whatever I typed in?

word = input("What is your word? ")

while word != str() or chr():
    word = input("Enter a string or character...")

for char in word:
    print(char)
skad
  • 9
  • 2
  • 5
    There are several problems here. None of them are really relevant, though, because `input` *always* returns a `str` object, so you don't need to check the type of `word`. – chepner Jan 17 '20 at 21:39
  • Thank you! That makes sense now. – skad Jan 17 '20 at 21:42
  • Have you done any research? There are plenty of helpful resources online for this. – AMC Jan 17 '20 at 22:01

2 Answers2

1

Try the following:

word = input("What is your word? ")

while type(word) is not str():
    word = input("Enter a string or character...")

for char in word:
    print(char)

Also, the input will always be a string.

If you want to check for numeric input, then you should do something like:

try:
    int(word)
except ValueError:
    # input is a string
else:
   continue  # input is a number
Daniel Lima
  • 925
  • 1
  • 8
  • 22
  • 2
    The check `while type(word) is not str():` will _always_ be `True`. `type(word)` in this case will always return `` while `str()` will always return `''` (empty string). These two things will never be equal. What you're looking for is `while not isinstance(word, str):`, but again this will always be `True` because `input()` _always_ returns a string. – b_c Jan 17 '20 at 21:56
0

Maybe something like this would work:

word = input("What is your word? ")

while word.isdigit(): # the word contains only digits
    word = input("Enter a string or character...")

for char in word:
    print(char)

Few notes:

  1. In your code word != str() would hold true as long as your input is not empty, as str() is a (very ugly) way of initializing an empty string.
  2. The return type from input() is str. If you want to treat it as an integer or any other type you'd have to cast/parse it
A. Rom
  • 131
  • 6