python - 如何将变量减少为零?
问题描述
我有一个由任何用户输入到我的程序的变量。我无法开始工作的任务是我希望变量在可变时间的过程中从输入值减小到 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()
这是我到目前为止的代码。它似乎遗漏了一些东西,但我无法弄清楚。
解决方案
在大多数情况下,代码的逻辑是正确的,但是没有迹象表明 pythonhealth
是一个全局变量。这必须在health_decrease
方法中明确完成,以便它使用现有的全局变量,而不是创建一个新的局部变量。
除此之外,某些格式(更具体地说,缩进)已关闭。
最后,我max()
在减去时添加了一个组件decrement
,health
以确保由于浮点舍入错误,该值永远不会低于 0。
这是一个功能代码示例(没有线程):
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()
推荐阅读
- python - 无法传递字符串变量以从 python 函数返回数据,以便在 Python 脚本或程序中的任何地方全局使用
- python - 格式化德语日期导致未转换的数据仍然存在:am
- sql - 为什么 Docker 中的 MSSQL 在 sql 查询中返回“最后一个操作已终止,因为用户按下了 CTRL+C”?
- html - 如何复制文件夹并更改名称?
- ios - swift enum 在单个 switch-case 中获取具有相同参数的多个 case 的关联值
- javascript - eslint vars-on-top 在 const 和 let 声明上给出警告并且不能被禁用
- java - 我怎样才能让我的按钮工作?爪哇
- javascript - 如何使用 Puppeteer 在 div 内滚动?
- c# - 绑定到 XAML 中的子 ViewModel 集合
- python - Python排序无忽略(或稳定)