0

so I'm making a dice rolling game for some homework and I was adding a feature so you could have as many players as you want but I've come to a problem. I want to be able to change the name of the variable it prints in every iteration. e.g guess0 then guess1 etc but I can't work out how to do it. I expect it to print the value of each variable every iteration of the for loop.

for dice in range(player_no):
     exec(f'guess{dice}=random.randint(1,7)')

for i in range(player_no):
    print(guess,{i})

I've tried looking for answers on lots of different sites but none of them seemed to fix the problem I hoped some of you could help.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    You should avoid using dynamic variables, they are not necessary for this. You probably just want to use a `list` – juanpa.arrivillaga Nov 12 '19 at 19:57
  • 3
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – c2huc2hu Nov 12 '19 at 19:59
  • 1
    Welcome to Stack Overflow! Check out the [tour]. I'm not quite sure what you mean. Could you give some example output? Also check out [ask] and [mre] if you want more tips. **Edit** Whoops, I misread the `exec` as `print`. I agree with Juanpa and c2huc2hu. – wjandrea Nov 12 '19 at 19:59

3 Answers3

0

Assuming you are talking about the second for loop, you can try something like below:

for i in range(6):
    print('guess%d' % i)

A better way is to use the format function in Python 3:

for i in range(6):
    print ("guess{}".format(i))

Hope this is what you are looking for. Cheers!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0
player_no = 10    
for i in range(player_no):
        print("guess{}".format(i))

this will output:

guess0
guess1
guess2
guess3
guess4
guess5
guess6
guess7
guess8
guess9

is this what you wanted?

Thomas Briggs
  • 119
  • 1
  • 11
-1

Use a list instead of dynamic variables. For more details see How do I create a variable number of variables?

guesses = [random.randint(1, 7) for _ in range(player_no)]

for guess in guesses:
    print(guess)

Though if you don't need the list for anything else, don't bother.

for _ in range(player_no):
    guess = random.randint(1, 7)
    print(guess)
wjandrea
  • 28,235
  • 9
  • 60
  • 81