Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How to calculate a local variable in function_1 and send the result to function_2 without running function_1 every time function_2 is called?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

*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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading