【发布时间】:2016-12-05 14:05:39
【问题描述】:
我正在尝试设置一个程序,在该程序中,用户决定生成多少海龟,然后他们进行比赛。我目前的解决方案是从用户那里获取一个 int 输入并执行下面的代码(代码不断重复较大的数字)。我尝试过循环,但我遇到了麻烦,因为它们最终都需要执行随机动作。有什么帮助吗?
if turtNum >= 1:
turt1 = Turtle()
turt1.color(turtColour[0])
turt1.shape('turtle')
turt1.penup()
turt1.goto(0, -10)
turt1.pendown()
if turtNum >= 2:
turt2Name = input('Enter a name for the second turtle: ')
turt2 = Turtle()
turt2.color(turtColour[1])
turt2.shape('turtle')
turt2.penup()
turt2.goto(0, -25)
turt2.pendown()
这是我尝试过的代码,但出现此错误“列表索引必须是整数或切片,而不是 str”
turtName = []
maxLengthList = turtNum
while len(turtName) < maxLengthList:
name = input('Enter the names for the turtles: ')
turtName.append(name)
for i in turtName:
turtName[i] = Turtle()
turtName[i].color(turtColour[0])
turtName[i].shape('turtle')
turtName[i].penup()
turtName[i].goto(0, -10)
turtName[i].pendown()
【问题讨论】:
-
有什么问题?
-
如果你想你使用随机位置(坐标去)你可以使用
random.random(cordinate_min ,cordinate_max)得到随机cordiante -
@ChrisMueller 好吧,我正在尝试在一个循环中生成所有海龟。我希望用户输入一个整数,而不是当前写出我的代码的方式,它会绘制那么多海龟
-
@user7252321 然后使用
input()获取数字并将文本数字转换为int()-number = int(text_with_number)或number = int(input(...)) -
您可以考虑在类构造函数中调用
.shape、.color、.penup、.goto、.pendown,这样会更好地遵守 DRY 并使其成为从概念上解决更简单的问题...