我有一个由任何用户输入到我的程序的变量。 我无法完成的任务是,我希望变量在一段可变时间内(也由用户输入)从输入值减少到0。在伪代码中,类似于:
x = time_variable
y = decreasing_variable
z = amount_of_decrease_of_y
while i < x:
y = y - z;
我已尝试编写代码,但无法正常工作:
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()
这就是我目前掌握的代码。它似乎遗漏了什么,但我想不出来
您没有正确调用
healthdecrease
函数。应该是这样的:在大多数情况下,代码的逻辑是正确的,但是python没有指出
health
是一个全局变量。这必须在health_decrease
方法中显式完成,以便它使用现有的全局变量,而不是创建新的局部变量。除此之外,某些格式(更具体地说,缩进)已关闭。
最后,我在从
health
中减去decrement
时添加了一个max()
组件,以确保该值不会由于浮点舍入错误而低于0下面是一个功能代码示例(不带线程):
相关问题 更多 >
编程相关推荐