lundi 10 mai 2021

Is there a way to create variables with iteration in python?

So Im trying to write code for an online blackjack program and I am having trouble with programming hitting, as I need to calculate using up to 11 variables that are drawn from a list randomly. Right now, my code for that section is:

        while user_card_total_one <= 21:
            user_move = input("Would you like to stand or hit? ")
            user_move = user_move.lower()
            if user_move == "stand":
                break
            elif user_move == "hit":
                user_card_three = random.choice(deck)
                deck.remove(user_card_three)
                a_or_an_one = " a "
                if user_card_three == 8 or user_card_three == "Ace":
                    a_or_an_one = " an "
                print("You were dealt" + a_or_an_one + str(user_card_three) + ".")
                if type(user_card_three) == str and user_card_one != "Ace":
                    user_card_one = 10
                if user_card_three == "Ace":
                    user_card_total_one = user_card_total_one + 1
                    user_card_total_two = user_card_total_two + 11
                    if user_card_total_two > 21:
                        print("Your card total is " + str(user_card_total_one) + ".")
                    else:
                        print("Your card total is " + str(user_card_total_one) + " or " + str(user_card_total_two) + ".")
                else:
                    user_card_total_one = user_card_total_one + user_card_three
                    user_card_total_two = user_card_total_two + user_card_three
                    print("Your card total is " + str(user_card_total_one) + ".")
                if user_card_total_one > 21:
                    print("Unfortunately, you busted and lost.")
                    print("The dealer has collected your bet.")
                    bust = True
                    break
            else:
                print("Sorry, thats not a valid input, please try again.")

Now, I could write this code a bunch more times so that it accounts for what the user decides to do, but the only change in the code would be the variable name. I was wondering if there is some way that I can make this a for loop where perhaps the variable name is dependent on i? I tried using a dictionary:

card = {
1: "Ace",
2: "King",
3: 2
}
card = 1
for i in range (10):
    print(card[card])
    card = card+1

but that didn't seem to help. Is this something I just have to brute force, or is there an easier way that Im missing?

Edit: Sorry, I used some wrong code in the second section, it's updated now




Aucun commentaire:

Enregistrer un commentaire