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

Stop running function when one variable gets to zero

Hope you can help me. Please see the code below. What I am trying to achieve is for code to stop when "x" or "y" gets to 0. At the moment, "x" gets to 0 first, but function_b() is still run after that. I would like that if "x" gets to 0, function_b() would not run afterwards. How do I do that?
Thank you

from random import randint

x = 10
y = 10


def roll_dice():
    random_dice = randint(1, 6)
    return random_dice


def function_a():
    global x
    while x > 0:
        dice = roll_dice()
      
        if dice >= 1:
            x -= 5
        else:
            print('Better luck next time')
            
        if x <= 0:
            break
        else:
            function_b()

def function_b():
    global y
    while y > 0:
        dice = roll_dice()
      
        if dice >= 1:
            y -= 5
        else:
            print('Better luck next time')
           
        if y <= 0:
            break
        else:
            function_a()


def turns():

    if x > 0:
        function_a()
    else:
        print('good game')
    
    if y > 0:
        function_b()
    else:
        print('good game')


turns()

>Solution :

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

I made some adjustement on your code :

from random import randint

x = 10
y = 10


def roll_dice():
    random_dice = randint(1, 6)
    return random_dice


def function_a():
    global x
    while x > 0 and y != 0:
        dice = roll_dice()
      
        if dice >= 1:
            x -= 5
        else:
            print('Better luck next time')
            
        if x <= 0:
            break
        else:
            function_b()

def function_b():
    global y
    while y > 0 and x !=0:
        dice = roll_dice()
      
        if dice >= 1:
            y -= 5
        else:
            print('Better luck next time')
           
        if y <= 0:
            break
        else:
            function_a()


def turns():

    if x > 0:
        function_a()
    else:
        print('good game')
    
    if y > 0:
        function_b()
    else:
        print('good game')


turns()
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