0

How to make word inputs in Python I want to be able to have the computer to ask a question to the user like

test = int(input('This only takes a number as an answer'))

I want to be able to have 'test' not be a number, rather a word, or letter.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Joe Van Wonderen
  • 37
  • 1
  • 2
  • 4
  • Can that helps? [Python - How to check if input is a number](http://stackoverflow.com/questions/5424716/python-how-to-check-if-input-is-a-number-given-that-input-always-returns-stri). – mins Mar 18 '15 at 21:09

5 Answers5

3

Just remove the int call! That is what makes the statement accept integer numbers only.

I.e, use:

test = input('This takes any string as an answer')
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
2

Remove the type cast to int

test = input('This only takes a word as an answer :')

A demo

>>> test = input('This only takes a word as an answer :')
This only takes a word as an answer :word
>>> test
'word'

Note - From the docs

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that

Therefore input automatically converts it to a str and there is no need of any explicit cast.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

This should work:

test = str(input('This only takes a string as an answer:  '))

BUT

Because Python works with String by default, actually you don't need any casting like int or str

Also, if you were using version prior to 3.x, it would be raw_input instead of input. Since your solution seem to have been accepting input, I can be safe assuming that your Python is OK. test = input('This only takes a string as an answer')

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
0
 test = input("This only takes a number as an answer")
 test = raw_input("This only takes a number as an answer")

Either one should work

cizwiz
  • 15
  • 3
0

If you are using python 2.7, just use raw_input function.

test = raw_input('This only takes a string as an answer:  ')

I.e.:

>>> test = raw_input('This only takes a string as an answer:  ')
This only takes a string as an answer:  2.5
>>> type (test)
<type 'str'>

If you use input, you can have only a number: Right input:

>>> test = input('This only takes a number as an answer:  ')
This only takes a string as an answer:  2.5
>>> type (test)
<type 'float'>

Wrong input:

>>> test = input('This only takes a number as an answer:  ')
This only takes a number as an answer:  word
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'word' is not defined
overcomer
  • 2,244
  • 3
  • 26
  • 39