Python how to find the number of characters in the user input
im creating a sort of quiz game on python and one of the questions is 'type a word that has 5 letters in them'.
so basicaly what i want is for the user to type anything that has 5 letters or characters in them.and then p开发者_开发知识库ython checks if it has 5 letters and if it is correct it sends them to the next question.
For your game, i assume you have some while loop that keeps things rolling.
Do this:
word = input("Give me a 5 letter word: ")
The line above will ask the user for the 5 letter word and their input will be stored in the variable word. Then check
if len(word) != 5:
print "that's not 5 letters..."
answer = raw_input("What is a five letter word? ")
if len(answer) == 5:
print "Correct!"
else:
print "Wrong, that has", len(answer), "letters!"
If you are using Python 3 you would need to replace raw_input
with input
and put parentheses around the print expressions (because print becomes a function).
You could try this.
if len(word) is 5
EDIT
Apparently this is bad. I did not know at the time of posting.
Anyway for those who are unaware and curios, here is a little experiment
>>> a = "hello"
>>> len(a) is 5
True
>>> len(a) is 4
False
>>> len(a) is 5.0
False
>>> len(a) == 5
True
>>> len(a) == 4
False
>>> len(a) == 5.0
True
EDIT again Based on a comment by interjay, I further did an experiment.
>>> for i in range(1000):
... a = 'x'*i
... if len(a) is not i:
... print(i)
... break
...
257
If someone could explain why it works up to 256, I'd love to add it here
EDIT Once more
This probably explains the behavior. I am quoting interjay from the comments.
It's an optimization in CPython: Objects for the integers in the range -1 to 256 are preallocated, and each time one of these values is encountered, it is given the same object. For other integers, a new object is created each time. Of course, this is an implementation detail and can change between Python versions.
精彩评论