【发布时间】:2016-12-03 19:33:07
【问题描述】:
我正在编写一个简单的数字猜谜游戏,但我无法让我的代码在 SublimeREPL 或我的控制台中执行。我可以让它在 Team Treehouse 的 Workspaces 程序中执行的唯一方法,它完全按照它应该的方式工作。但是在我的控制台和 SublimeREPL 中,它都说有多个缩进错误。是什么赋予了??我知道 python 对它的缩进很挑剔,所以我确保更改我的 sublime 设置,以便每个选项卡都是四个空格,但它仍然无法运行 - 引发大约十个缩进错误,但据我所知,一切都是缩进的应该是。我尝试了多次搜索,但没有结果,我束手无策,无法运行这么简单的程序!我的意思是为什么代码会在一种环境中工作,而在另一种环境中却不行?我正在复制和粘贴代码,所以它没有什么不同......
代码如下:
import random
#safely make an int
#limit guesses
#too high, too low, messages
#play again
def game():
#generate number
secret_number = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
#get num guess from user
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("That's not a valid number, try again.")
else:
#compare guess to secret number
if guess == secret_number:
#print hit/miss
print("You got it! My number was {}".format(secret_number))
break
else:
print("That's not it! Guess again!")
guesses.append(guess)
game()
请注意,此代码在 Team Treehouse 上完美运行。 这是我在 SublimeREPL 和我的终端中收到的错误:
Guess a number between one and ten: Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 1
if guess == secret_num:
^
SyntaxError: invalid syntax
>>> File "<stdin>", line 1
print("You got it!")
^
IndentationError: unexpected indent
>>> File "<stdin>", line 1
break
^
IndentationError: unexpected indent
>>> File "<stdin>", line 1
else:
^
IndentationError: unexpected indent
>>> File "<stdin>", line 1
print("That's not it!")
^
IndentationError: unexpected indent
>>> >>>
我真的更喜欢使用 Workspaces 以外的工具,这样我就可以在我的机器上拥有自己的代码,但我不知道这段代码是否真的可以工作,或者我只是在浪费时间学习垃圾......
【问题讨论】:
-
这可能意味着您将空格和制表符混合到缩进中,这是您不应该做的。有些 IDE 可以很好地处理这个问题,有些则不能。
-
我知道 pycharm 可以自动为您解决很多问题。我认为许多其他编辑也会这样做。
-
在它工作的 IDE 中,查看它是否具有将所有缩进转换为空格或制表符的选项。然后,确保缩进的内容保持一致。
-
现在我很困惑。我应该用制表符或空格缩进吗?因为有人告诉我这两种情况。
-
我已经完全删除了程序中的缩进,并将其重新添加为制表符和空格,但都没有成功。相反,他们在 Team Treehouse 上工作,但不在我的控制台或 SublimeREPL 中。
标签: python console sublimerepl