1
def distribute(mylist):
    player_1=[]
    player_2=[]
    
    a=10
    
    for i in range(0,a):
        if i%2==0:
            player_1.append(mylist.append(i))
        else:
            player_2.append(mylist.append(i))

Result

mylist=[1,2,3,4,5,6,7,8,9,10]
distribute(mylist)
player_1

NameError                                 Traceback (most recent call last) <ipython-input-124-1c0f0ed63597> in <module>
----> 1 player_1
 
NameError: name 'player_1' is not defined
ppwater
  • 2,315
  • 4
  • 15
  • 29
darkknight
  • 19
  • 1
  • Can you show us your expected output? – mhhabib Jan 08 '21 at 05:48
  • You tried to evaluate `player_1` in your main program. There is no such variable in the main. – Prune Jan 08 '21 at 05:57
  • `player_1` is local to `distribute()` and cant be accessed outside of it. That is why when it tried to look it up, it cant find it. Also unrelated but probably an error: `mylist.append(i)` returns `None` which is probably not what you wanted to append to `player_1`. If you want to have access to it afterwards, `return player_1` at the end. ``` def distribute(mylist): player_1=[] player_2=[] a=10 for i in range(0,a): if i%2==0: player_1.append(mylist[i]) else: player_2.append(mylist[i]) return player_1 ``` – Coder Jan 08 '21 at 05:59

1 Answers1

1

You can set the variable as global. And append doesn't return anything, so you will get None. Just append i into the list.

Like this:

def distribute(mylist):
    global player_1, player_2 #Anything you need to set
    player_1=[]
    player_2=[]
    a=10
    for i in range(0,a):
        if i%2==0:
            player_1.append(mylist[i])
        else:
            player_2.append(mylist[i])
mylist=[1,2,3,4,5,6,7,8,9,10]
distribute(mylist)
print(player_1)

Or you can return the result.

def distribute(mylist):
    player_1=[]
    player_2=[]
    a=10
    for i in range(0,a):
        if i%2==0:
            player_1.append(mylist[i])
        else:
            player_2.append(mylist[i])
    return player_1
mylist=[1,2,3,4,5,6,7,8,9,10]
print(distribute(mylist))

Returning is recommended.

Coder
  • 1,175
  • 1
  • 12
  • 32
ppwater
  • 2,315
  • 4
  • 15
  • 29