How do I use a list from a different function? - python

cards1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v']
def piles(cards1):
print("You must remember what card is yours!")
pile = [[],[],[]]
first = 0
second = 1
third = 2
for i in range (7):
pile[0].append(cards1[first])
pile[1].append(cards1[second])
pile[2].append(cards1[third])
first += 3
second += 3
third += 3
print(pile)
return(pile)
piles(cards1)
def sorting_piles():
sorted_piles = []
final_pile = []
which_pile = int(input("Which card is your pile in, 1,2 or 3?"))
for i in range (2):
while which_pile not in(1,2,3):
which_pile = int(input("Invalid input. Which card is your pile in, 1,2 or 3?"))
if which_pile == (1):
sorted_piles.append(pile[2,0,1])
elif which_pile == (2):
sorted_piles.append(pile[2,1,0])
else:
sorted_piles.append(pile[1,2,0])
print("This is now the new pile:",sorted_piles)
for i in range(7):
final_pile.append(sorted_piles[0][i-1])
for i in range(7):
final_pile.append(sorted_piles[1][i-1])
for i in range(7):
final_pile.append(sorted_piles[2][i-1])
print("Your card is:",final_pile[10])
return(final_pile)
sorting_piles()
Whenever I run this code, the first function runs perfectly and I am able to input which pile my card is in but after I input, I get this error message:
NameError: name 'pile' is not defined
How do I make the second function recognise the list 'pile'? Thanks

You have no variable that is catching the output being returned from the function definition. You need this :
pile = piles(cards1)

pile = piles(cards1)
You can use the return value .
Also pile[2,0,1] does not work with list.You can use (pile[2], pile[0],pile[1]).Append a tuple or list

You need to assign the return value of piles to a variable, then pass that to sorting_piles as an argument:
def sorting_piles(pile):
...
pile = piles(card1)
sorting_piles(pile)

This is a scoping issue. The pile variable defined in your piles function only exists in here, in this scope.
It looks like you're trying to access it from a different scope, inside your other function, where it doesn't exist.
You can simply create a global reference to the return value from your function like the other answers said:
pile = piles(cards1)

Related

How to pass a list between two functions?

I have a list that's been modified in one function, and I want it to go to another function in order to be read and modified further.
def get_cards_player():
deck = Deck()
deck.shuffle()
player1 = []
player2 = []
you_won = False #if u won, var is true, if u lose, var is false
for i in range(5):
player1_cards = deck.get_card()
player1.append(player1_cards.get_name())
player2_cards = deck.get_card()
player2.append(player2_cards.get_name())
print('Your Hand:',', '.join(player1))
print('Opponent Hand:',', '.join(player2))
return player1, player2
def calc_winner():
I want player1 and player2 lists in get_cards_player function to go to the calc_winner function so that I can read the list and do stuff with it.
Thanks.
calc_winner should take these lists as parameters. I purposely changed the names to highlight that parameters don't have to have the same name in different functions.
get_cards_player already creates and returns the lists, so no need to change. Again, to show the different ways you can do this, I'm remembering the tuple containing the two players and using that in the call.
def calc_winner(p1list, p2list):
print(p1list, p2list)
players = get_card_player()
calc_winner(players[0], players[1])

Write a function which squares a number and then use it to write a function which takes three integers and returns the sum of their squares

Im new to python and cant figure out how to get these functions to call themselves. It asks for an input but no matter what gives 0 as the output. Can someone help debug?
userinput = input("Enter three numbers: ")
userinput = userinput.split(',')
finalsum = 0
finaldata = []
def formatinput(x):
sqrdata = []
for element in x:
sqrdata.append(int(element))
return(sqrdata)
def findsquare(x):
return (x*x)
def sumthesquares(y):
for element in y:
temp = findsquare(element)
finaldata.append(int(temp))
finalsum = finalsum + temp
return finalsum
def findthesquares(userinput):
finalsum = sumthesquares(formatinput(userinput))
print(finalsum)
Have you actually tried running your code? From what you've posted, it looks like you never actually call your functions...
They're defined, but you're missing the actual calls, like formatinput(userinput).
For future reference, if you put something like print("Got here!") into your functions, you can test that they're being called.

Checking if index in list exists

I would like to note that I'm using Discord.py and some of it's included libs.
So I'm trying to check if an index in a list exists but I keep getting the ValueError saying that the index does not exist in my list.
Here's my code:
def deal_card(self):
U = self.usedCards
randCard = randchoice(list(self.cards))
if not U: #check if it is empty
#if it is empty, just add the card to used cards
U.append(randCard)
elif U.index(randCard): #check if card is already in the list
#if it is, pick another one
randCard = randchoice(list(self.cards))
U.append(randCard)
else: #check if card is not in list
#if it is not, just add it to the used cards
U.append(randCard)
return randCard
self.cards is full of card names and self.usedCards is a list of cards alredy picked by randCard.
hand is my command and P4 is one of the cards in self.cards
I found some solutions saying that adding a try block will solve the problem but I don't know how to add it in the middle of my if statement.
Thanks in advance!
list.index() should be used for finding the index of a list's member. To check whether an item is in a list, simply use in:
if not U:
# do stuff
elif randCard in U:
# do other stuff
This is probably a terrible way to deal your cards, because then you have the cards both in your discard pile and in your deck.
Why not just move the cards around?
import random
cards = ['H{}'.format(val) for val in range(1, 11)]
print(cards)
discard_pile = []
while cards:
random.shuffle(cards)
card = cards.pop()
print('You drew a {}'.format(card))
discard_pile.append(card)
while discard_pile:
cards.append(discard_pile.pop())
# or
cards.extend(discard_pile)
discard_pile.clear()
You don't need to use the index function:
elif randCard in U:
If you would still like to use the .index function for some reason and not follow the above suggestions you could use the try statement as follows:
try:
c = U.index(randCard)
randCard = randchoice(list(self.cards))
U.append(randCard)
except ValueError:
U.append(randCard)

Function changing the value of argument in Python

I am trying to write a program for Conway's Game of Life, and I came across some really weird problems, so I'm going step by step and trying to debug it. There is some weird stuff going on.
If you are not familiar with Conway's game of Life, the rules for determining the next stage is simply:
Any live cell with fewer than two live neighbours dies, as if caused
by under-population.
Any live cell with two or three live neighbours lives on to the next
generation.
Any live cell with more than three live neighbours dies, as if by
overcrowding.
Any dead cell with exactly three live neighbours becomes a live cell,
as if by reproduction.
I'm keeping a list called squareList that has N_ROWS rows and N_COL columns. I reference each element as squareList[i][j].
My get_next(squareList) function returns another list that counts the number of 'neighbors' in each square, and returns another list with the next stage.
Now, onto my problem. Here is a test case that highlights that a function is changing values it is not supposed to:
squareList = init_list(NUM_ROWS, NUM_COL) #sets all values in squareList to zero.
#here, NUM_ROWS = 12 and NUM_COL = 18
squareList[11][17] = 1
squareList[5][7] = 1
squareList[6][7] = 1
squareList[7][7] = 1
squareList[9][2] = 1
squareList[9][3] = 1
squareList[9][4] = 1
print_list(squareList) #prints squareList
nextList = get_next(squareList) #does NOT change squareList
print '\n--------------------------------------\n'
print_list(squareList) #prints squareList again
sys.exit()
What I get when I use my print_list function is:
As you can see, everything touched by the get_next function is set to zero. This shouldn't happen in my mind for two reasons:
It's not what should happen according to the Conway logic in my get_next function (and I really cannot find why it would not work)
My get_next function is setting a nextList variable, it's not supposed to do ANYTHING to squareList !! What am I missing??
Here's the code for my get_next function:
def get_next(squareList): #gets the next list for the game of life
nextList = squareList
for i in range(1,NUM_ROWS - 1):
for j in range(1,NUM_COL-1):
#num of neighbors:
counter = sum( [squareList[i+x][j+y] for x in range(-1,2) for y in range(-1,2) if not (x==y and x == 0)])
#logic for changing:
if squareList[i][j] == 1 and counter < 2: nextList[i][j] = 0
elif squareList[i][j] == 1 and counter > 3: nextList[i][j] = 0
elif squareList[i][j] == 0 and counter == 3: nextList[i][j] = 1
return nextList
My original thought is that it's changing a global variable, but it's not the case. First, python needs to declare global variables it uses within the function, and second, I tried changing the names of the lists, and got the same results.
EDIT: reply to lanzz suggestion:
The first thing you do in your get_next function is to make nextList a reference to the same list that squareList points to. Assignment does not imply copying — nextList = squareList makes both names point to the same actual structure in memory, so any change to nextList will affect squareList as well.
You should use copy.deepcopy to obtain an actual copy of your squareList list.

Global list doesn't contain value at another function

I want to make a global list and I saved a value in my global list (def rand()).
Whatever I save, my saved value doesnt include at another function except rand().
What am I missing?
sayi = []
def rand():
global sayi
initial = 1000
for i in range(1000,10000):
initial +=1
sayi.append(initial)
print sayi[43]
def main():
rand()
print len(sayi) # Shows 0 but I have added value at rand funct. with append funct.
main()
I'm going to assume you're new to python. INDENTATION MATTERS. Not trying to be mean, but I've noticed that trips a lot of people up. Here's your modified code.
sayi = []
def rand():
global sayi
initial = 1000
for i in range(1000,10000):
initial +=1
sayi.append(initial)
print sayi[43]
def main():
rand()
print len(sayi) # Shows 0 but I have added value at rand funct. with append funct.
main()
you have everything working, your indentation is just a little off.

Categories

Resources