【发布时间】:2021-10-10 16:36:04
【问题描述】:
我刚刚开始学习,我只学习了基础知识,但这是我当前的代码。我需要把它放在一个循环中,并要求用户将数字放置最多 8 次。
num_list = ['1','2','3','4','5',]
import random
num = random.choice(num_list)
table = [[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ']]
ss = {"W1":[0,0],
"W2":[1,0],
"W3":[2,0],
"W4":[3,0],
"X1":[0,1],
"X2":[1,1],
"X3":[2,1],
"X4":[3,1],
"Y1":[0,2],
"Y2":[1,2],
"Y3":[2,2],
"Y4":[3,2],
"Z1":[0,3],
"Z2":[1,3],
"Z3":[2,3],
"Z4":[3,3]}
ans = input('where would you like to place it: ')
index_ = ss[ans][0]
columns_ = ss[ans][1]
table[index_][columns_] = num
print(table)
下面的这段代码应该确保用户将数字放置在另一个数字旁边。 我如何确保它只在第 2 回合开始检查?如果它不相邻,我如何让它重复转弯?我还想将上面的代码放入函数中,并在最后调用它以使其更整洁,但我不知道该放什么,不放什么。
def moveandclip(n, x, y):
n[0] = max(0, min(n[0] + x, 3))
n[1] = max(0, min(n[1] + y, 3))
return n
above = moveandclip(ss[ans], 0 ,1)
below = moveandclip(ss[ans], 0 ,-1)
left = moveandclip(ss[ans], -1 ,0)
right = moveandclip(ss[ans], 1 ,0)
if above == '' and below == '' and left == '' and right == '':
print('It must be placed adjacent to another number.')
repeat the turn
else:
continue to next turn
【问题讨论】:
-
欢迎来到 Stack Overflow! StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
-
您可以使用 for i in range(8) 将代码的最后一行(来自输入)放入循环中
-
你可以使用
for turn in range(8):迭代8次。您可以检查turn > 0是否是第二个转弯。 -
在我使用它来迭代它 8 次之后,我会在里面放另一个循环吗?如转 > 1,然后我插入我的 if 语句?
-
@cherrynote,我已经添加了一个答案。你可以参考一下
标签: python function loops for-loop if-statement