Rapha Nash
Rapha Nash

Reputation: 13

Storing all the results from a FOR LOOP in an array

I have created an array called Player1_Cards. Each card needs to have a number and a colour. Player1 should have 15 cards, which can be numbered from 1 to 30.

I have used a for loop to do this:

using random.randint (1,30), I have found the number of the card.

using random.randint(1,3), I allocate number 1,2 or 3 to colours RED, YELLOW or BLACK.

How do I store all my results from the for loop as an array?

Here is my code:

Player1_Cards = [0]

import random
for i in range(1,16):
    i = random.randint(1,30)
    i_colour = random.randint(1,3)
    i_colour = str(i_colour)

    if i_colour == "1":
        i_colour = "RED"

    if i_colour == "2":
        i_colour = "YELLOW"

    if i_colour == "3":
        i_colour = "BLACK"



    Player1_Cards[i,i_colour]

If I print(i,i_colour), ignoring the array, examples of what it may execute is:

6 YELLOW
28 YELLOW
8 RED
3 BLACK
22 RED
2 BLACK
26 RED
25 YELLOW
8 RED
20 RED
16 BLACK
12 YELLOW
4 RED
20 BLACK
1 YELLOW

Upvotes: 0

Views: 60

Answers (2)

Alfe
Alfe

Reputation: 59596

Try this:

Player1_Cards = []

in the beginning. then at the end of the loop:

Player1_Cards.append((i, i_colour))

And after the loop:

print(Player1_Cards)

You also have a bug in your code:

for i in range(1,16):
    i = random.randint(1,30)

Both will set the variable i to a value. It doesn't make sense this way. If you just want to do your loop fifteen times, better use the _ instead:

for _ in range(1,16):

Upvotes: 0

Merig
Merig

Reputation: 2011

An easier way to implement this is using list comprehensions:

import random

colours = ['RED', 'BLUE', 'YEllOW']
player_hand = [(random.randint(1, 30), random.choice(colours)) for _ in range(15)]

Output:
# 21 BLUE
# 22 BLUE
# 25 YEllOW
# 11 BLUE
# 4 RED
...

Upvotes: 1

Related Questions