Kruzzzzy
Kruzzzzy

Reputation: 11

Returned variable are not defined in python

import random
cards = ["Red 1", "Red 2", "Red 3", "Red 4", "Red 5", "Red 6", "Red 7", "Red 8", "Red 9", "Red 10", "Blue 1", "Blue 2", "Blue 3", "Blue 4", "Blue 5", "Blue 6", "Blue 7", "Blue 8", "Blue 9", "Blue 10", "Black 1", "Black 2", "Black 3", "Black 4", "Black 5", "Black 6", "Black 7", "Black 8", "Black 9", "Black 10"]
#Acts as a deck
def card_draw():
   player_1_card = cards[random.randint(0,29)]
   player_2_card = cards[random.randint(0,29)]
   while player_1_card == player_2_card:
       player_2_card = cards[random.randint(0,29)]
   return (player_1_card, player_2_card)
#Defines player 1 and 2's cards
player_1 = input("Please enter your name.")
player_2 = input("Please enter your name.")
#Names the players
card_draw()
print(player_1 + " is now drawing a card from the top of the deck.")
print(player_1 + " drew a " + player_1_card)
print(player_2 + " is now drawing a card from the top of the deck.")
print(player_2 + " drew a " + player_2_card)
#Tells the players what cards they drew 

After running this code is says that the variables player_1_card and player_2_card are undefined even after returning them, why would this be?

Upvotes: 1

Views: 249

Answers (3)

dspr
dspr

Reputation: 2433

These variables are defined as local variables inside a function. So they are not visible outside that function. You could solve that problem by making them global instead :

player_1_card = None
player_2_card = None

def card_draw():
   global player_1_card, player_2_card
   player_1_card = cards[random.randint(0,29)]
   player_2_card = cards[random.randint(0,29)]
   while player_1_card == player_2_card:
       player_2_card = cards[random.randint(0,29)]
   

Now the variables are visible and can be used in the global scope without needing to return them from the function.

Upvotes: 0

Paitor
Paitor

Reputation: 271

print(player_1 + " drew a " + player_1_card)
print(player_2 + " drew a " + player_2_card)

there is an error in these lines. The variables player_1_card and player_2_card are declared inside the card_draw function, and you access them outside the function.

Upvotes: 0

E. Gertz
E. Gertz

Reputation: 241

instead of just running the function card_draw() you need to define the param's by:

player_1_card, player_2_card = card_draw()

thats because the function you wrote returns those chosen variables.

In addition, you should read a bit about local vs global variables.

Upvotes: 1

Related Questions