I have a variable inputted by any user to my program. The task I cannot get to work is I want the variable to decrease from the input value to 0 over the course of a variable time (also input by the user). In pseudocode that would be something akin to:
x = time_variable
y = decreasing_variable
z = amount_of_decrease_of_y
while i < x:
y = y - z;
I have tried writing the code, but it doesn't work properly:
time_of_activity = float(input('How long should health decrease in hours? '))
time_of_activity = time_of_activity * 60 * 60
health = float(input('How much is starting health? '))
X = health / time_of_activity
def healthdecrease():
i = 1
while i<(time_of_activity):
time.sleep(1)
i =1
health = health - X
decrease_of_health = threading.Thread(target=healthdecrease)
decrease_of_health.start()
That is the code I have so far. It seems to be missing something, but I can't figure it out.
CodePudding user response:
You are not calling the healthdecrease
function correctly. It should be like this:
decrease_of_health = threading.Thread(target=healthdecrease())
I guess you can just do it like this:
def healthdecrease(): while(health): health -= x
CodePudding user response:
For the most part the logic of the code is correct, however there was no indication to python that health
is a global variable. This must be done explicitly in the health_decrease
method so that it uses the existing global variable rather than creating a new, local one.
Other than that, some of the formatting (more specifically, the indentation) was off.
Lastly, I added a max()
component when subtracting decrement
from health
to ensure the value never goes below 0 due to floating point rounding errors.
Here is a functional code sample (without the threading):
import time
time_of_activity = float(input('How long should health decrease for in seconds? '))
health = float(input('What is the starting health? '))
decrement = health / time_of_activity
def health_decrease():
global health
i = 1
while i <= time_of_activity:
time.sleep(1)
i = 1
health = max(health - decrement, 0)
health_decrease()