[Python] Modifying a list while iterating over it in a for loop; code is working but looking...

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a blackjack program and I'm stuck on splitting cards. According to the rules, if both cards have the same value, the player can split it into 2 separate hands, upto a maximum of 4 hands.

    I have solved this, but it involves changing a for loop while iterating over it and I know this should be avoided as a general rule of thumb. The code is working, though.

    I was hoping for an alternative direction or suggestion for solving this. Please be gentle... I'm new to both programming as well as Stack Overflow and am teaching myself Python.

    Extract of my code. I've tried to include everything relevant.

    import random

    def create_deck():
    """Create a deck of 52 cards and a dictionary to store its points"""
    suits = ["Hearts", "Clubs", "Diamonds", "Spades"]
    ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
    points = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    deck_of_cards = [f"{rank} of {suit}" for suit in suits for rank in ranks]
    dict_of_cards = {key:val for (key, val) in zip(deck_of_cards, points*4)}
    return deck_of_cards, dict_of_cards

    def deal_a_card():
    """Deal a card from the deck; deck reduces with each deal"""
    global card_deck
    new_card = random.choice(card_deck)
    card_deck.remove(new_card)
    return new_card

    def split_hand(cards):
    """Takes the player's hand of 2 cards and returns 2 sets of hands"""
    split_cards = [[cards] for i in range(2)]
    for card in split_cards:
    card.append(deal_a_card())
    return split_cards

    def is_splitable(cards):
    """Retrieves the point value of each card and compares them"""
    if card_dict[cards[0]] == card_dict[cards[1]]:
    return True
    else:
    return False

    # Create a deck of 52 cards and a dictionary with corresponding points
    card_deck, card_dict = create_deck()

    # Deal two initial cards
    player_cards = [deal_a_card() for i in range(2)]

    # This is the iffy code:
    final_hands = []
    hands = [player_cards]
    split_counter = 0
    for hand in hands:
    if is_splitable(hand) is False:
    final_hands.append(hand)
    else:
    if split_counter < 3:
    split = input("Split? y/n: ")
    if split == "y":
    split_counter += 1
    result_of_split = split_hand(hand)
    for each_set_of_cards in result_of_split:
    hands.append(each_set_of_cards)
    else:
    final_hands.append(hand)
    else:
    final_hands.append(hand)


    In the interest of conciseness, I haven't included print statements and such like but I can post the unedited version if needed. Don't know if I should attempt to explain my code line by line. Using Python 3.13.

    Thanks in advance.

    Continue reading...

Compartilhe esta Página