1

正在做一个猜字游戏。

为什么在以下示例中,当我将变量“userGuessPosition”的值硬编码为 2 时,代码按预期工作。

secretWord = ('music')
userGuessPosition = 2 
slice1 = (secretWord.__len__()) - userGuessPosition - 1  
print (secretWord[slice1:userGuessPosition])

但是当我依赖 input() 函数并在提示符下输入 2 时,什么都没有发生?

secretWord = ('music')
userGuessPosition = 0
userGuessPosition == input()
slice1 = (secretWord.__len__()) - userGuessPosition - 1  
print (secretWord[slice1:userGuessPosition])

我认为这是因为我的键盘输入“2”被视为字符串而不是整数。如果是这种情况,那么我不清楚转换它的正确语法。

4

2 回答 2

5
userGuessPosition = int(input())

(Single =; int converts a string to an int)

于 2013-04-05T04:00:29.893 回答
5

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

EDIT

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.

于 2013-04-05T04:01:21.747 回答