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

Time:09-23

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.

CodePudding user response:

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
  • Related