I’m trying to design a card game with a ‘shuffle’ function and a ‘deal’ function. The problem I’m encountering is that every time I pass the results of ‘shuffle’ to ‘deal’, the cards are shuffled. I’m new to local variables… how can I pass the local variable from ‘shuffle’ to ‘deal’ when I only want the ‘shuffle’ effect calculated once?
Here is a simplified example of what I’ve tried:
import random
def shuffle():
x = random.randrange(1, 11)
return x
def deal():
x = shuffle()
print('\nx =', x)
inpt = input('\nEnter anything to deal again, or x to quit: ')
if inpt == 'x':
quit()
while True:
deal()
I want ‘deal’ to print out a consistent value of x, but instead it is shuffled for every iteration. How can I shuffle x just once so that x is printed as a consistent value?
*note: I know I could simplify this code by making it just one function, but I need help understanding how local variables move between functions. Thanks
>Solution :
It is because you have called shuffle from the deal method. Something like this should give you what you’re looking for.
import random
def shuffle():
x = random.randrange(1, 11)
return x
def deal(x):
# x = shuffle()
print('\nx =', x)
inpt = input('\nEnter anything to deal again, or x to quit: ')
if inpt == 'x':
quit()
x = shuffle()
while True:
deal(x)
Alternatively you could move the while True: into the deal method.
import random
def shuffle():
x = random.randrange(1, 11)
return x
def deal():
x = shuffle()
while True:
print('\nx =', x)
inpt = input('\nEnter anything to deal again, or x to quit: ')
if inpt == 'x':
quit()
deal()