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.
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.
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')
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.
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')
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
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