我不能为此做一个for循环 所有那些while循环都应该在一个for循环中 (这是课程的一部分,这就是为什么使用self的原因)
self.task1 = ""
self.task2 = ""
self.task3 = ""
self.task4 = ""
self.task5 = ""
self.tasks = [self.task1, self.task2, self.task3, self.task4, self.task5]
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
self.task1 = "{} + {} =".format(num1, num2)
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
self.task2 = "{} + {} =".format(num1, num2)
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
self.task3 = "{} + {} =".format(num1, num2)
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
self.task4 = "{} + {} =".format(num1, num2)
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
self.task5 = "{} + {} =".format(num1, num2)
我试图做这样的事情:
for task in self.tasks:
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
task = "{} + {} =".format(num1, num2)
但这不起作用
答案 0 :(得分:0)
您需要在循环内缩进代码:
for task in self.tasks:
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
task = "{} + {} =".format(num1, num2)
答案 1 :(得分:0)
您可以创建一个单独的方法:
for task in self.tasks:
task = randomTask()
...
def randomTask():
while True:
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
if num1 + num2 <= 10:
break
return "{} + {} =".format(num1, num2)