我正在阅读“绝对初学者的 Python 编程(第 3 版) ”一书。我在介绍自定义模块的章节中,我相信这可能是书中编码的错误,因为我已经检查了 5 或 6 次并完全匹配它。
首先我们有一个自定义模块games.py
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
""" Ask a yes or no question. """
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
""" Ask for a number within a range """
response = None
while response not in range (low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit.")
现在是SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
所以这正是代码在书中出现的方式。当我运行程序时,我IndentationError
在for i in range(num):
. 我预计会发生这种情况,所以我对其进行了更改,并从for i in range(num)
to删除了每行前面的 1 个制表符或 4 个空格again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
。
在此之后,输出就是"Welcome to the world's simplest game!"
这样。
我想知道是否有人可以让我知道为什么会这样?
此外,import games
在我将路径添加到 PYTHONPATH 后,Eclipse 会识别该模块。