Reputation: 1903
Working on a letter-guessing game.
Why is it that in the following example, when I hardcode the value of the variable, "userGuessPosition" to 2, the code works as expected.
secretWord = ('music')
userGuessPosition = 2
slice1 = (secretWord.__len__()) - userGuessPosition - 1
print (secretWord[slice1:userGuessPosition])
But when I rely on the input() function and type in 2 at the prompt, nothing happens?
secretWord = ('music')
userGuessPosition = 0
userGuessPosition == input()
slice1 = (secretWord.__len__()) - userGuessPosition - 1
print (secretWord[slice1:userGuessPosition])
I assume this is because my keyboard input of "2" is being seen as a string and not an integer. If this is the case, then I'm unclear on the proper syntax to convert it.
Upvotes: 1
Views: 450
Reputation: 3994
The problem is not that the input is recognized as a string, but rather in the syntax: you're doing a comparison operation where you should be doing an assignment operation.
You have to use
userGuessPosition = input()
instead of
userGuessPosition == input()
The input()
function actually does convert the input number into the most appropriate type, sp that should not be an issue. If however you need to convert a string (say, my_string
) to an integer, all you need to do is my_int = int(my_string)
.
As mentioned below by @HenryKeiter, depending on your Python version, you may in fact need to convert the return value of input()
to an integer by hand, since raw_input()
(which always takes in the input as a string) was renamed to input()
in Python 3.
Upvotes: 5
Reputation: 1026
userGuessPosition = int(input())
(Single =
; int
converts a string to an int)
Upvotes: 5