[Python] Is there a way to do this so I don't have to repeat myself 10 times [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I want to code minesweeper (using pygame, but that's not important) using a 10x10 grid by having 10 different rows using this code:

    import pygame
    import sys
    import random

    def make_row():
    return [0,0,0,0,0,0,0,0,0,0]

    row1 = make_row()
    row2 = make_row()
    row3 = make_row()
    row4 = make_row()
    row5 = make_row()
    row6 = make_row()
    row7 = make_row()
    row8 = make_row()
    row9 = make_row()
    row10 = make_row()
    mines_maker = 10

    while not mines_maker == 0:
    random_row = random.randint(0,9)
    random_colum = random.randint(0,9)
    if random_row == 1:
    if row1[random_colum] == 0:
    row1[random_colum] = 1
    mines_maker -= 1
    else:
    pass


    However I do not want to repeat this piece of code 10x:

    if random_row == 1:
    if row1[random_colum] == 0:
    row1[random_colum] = 1
    mines_maker -= 1
    else:
    pass


    Is there a way I could change this so I don't have to repeat myself?

    I also don't want to repeat this 10x:

    row1 = make_row()
    row2 = make_row()
    row3 = make_row()
    row4 = make_row()
    row5 = make_row()
    row6 = make_row()
    row7 = make_row()
    row8 = make_row()
    row9 = make_row()
    row10 = make_row()


    I've tried doing a def function but I can't seem to get anything to work.

    Continue reading...

Compartilhe esta Página