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

While a variable is greater than zero, how do I activate 2 definitions at once?

import time

health = 100
kidsHP = 10

def kidsenemyattack():
    global health
    print('The enemy deals damage!')
    health -= 4
    print(health)
    print('==========')
    time.sleep(3)
    kidsenemyattack()

def kidfight():
    global kidsHP
    ready = input('You can attack!')
    if ready in ['1','one','One']:
        kidsHP -= 1
    time.sleep(2.5)

 while health > 0:
            kidsenemyattack() and kidfight()
        if kidsHP <= 0:
            print('You've defeated the evil kids")

Instead of both of the definitions doing what I want (Which is draining my health over time and informing me that I can attack) kidsenemyattack() just overrides kidfight() and vice versa.
I want both of them to be able to be do their functions without one overriding the other.

>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

You’re executing kidsenemyattack recursively in the function definition. Remove it from there and logically the code will make sense. There were some formatting issues I had to fix too before the code ran. Here’s a working example:

import time

health = 100
kidsHP = 10

def kidsenemyattack():
    global health
    print('The enemy deals damage!')
    health -= 4
    print(health)
    print('==========')
    time.sleep(3)
    # kidsenemyattack() <- this is causing your repeating issue

def kidfight():
    global kidsHP
    ready = input('You can attack!')
    if ready in ['1','one','One']:
        kidsHP -= 1
    time.sleep(2.5)

while health > 0:
    kidsenemyattack()
    kidfight()
    if kidsHP <= 0:
      print("Youve defeated the evil kids")
      exit(0)
      
print("Youre defeated")

Running it resulted in a working scenario:

$ python kidsf.py
The enemy deals damage!
96
==========
You can attack!1
The enemy deals damage!
92
==========
You can attack!3
The enemy deals damage!
88
==========
You can attack!12
The enemy deals damage!
84
==========
You can attack!
# this goes on
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