'issue with for loop and display function importing from another file
This code prints the correct outcomes, however when it comes to display.dice it says die1, die2 etc is not defined.
import dice is from another file,
import file is confirmed to be working correctly
if I assign each die in roll manually with it works e.g. die1 = int(random.randint(1,6))
'''
import dice
import random
roll = ["die1", "die2", "die3", "die4", "die5"]
roll = [int(random.randint(1,6)) for i in range(1, 6)]
print(roll)
increments = {3: 2, 5: 4}
petals = 0
for die in roll:
petals += increments.get(die, 0)
print(petals)
dice.display_dice(die1, die2, die3, die4, die5)
'''
Solution 1:[1]
When you first assign a the list like this:
roll = ["die1", "die2", "die3", "die4", "die5"] #------------- 1
roll = [int(random.randint(1,6)) for i in range(1, 6)] #------ 2
You are simply overwriting the list that you defined at (1) with the list you defined at (2).
So you do not have at all any variable with the names that you are trying to use (die1, die2, .. etc).
The method that @Iain Shelvington suggested, unpacks the list that you created at (2) meaning that it will unpack the list into its elements which are basically the values that you were trying to pass with the names of the variables that are not defined. That is why it works.
If you really want to have things with names you can either define each one seperatly or use something like a dictionary for example. You can do something like this:
dies = ["die1", "die2", "die3", "die4", "die5"]
rolls = [int(random.randint(1,6)) for i in range(1, 6)]
roll = dict(zip(dies, rolls))
Then you can call each one of them, for example like this:
roll['die1']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D.Manasreh |
