在Python循环中根据不同范围更新变量

我需要在循环中定期更新变量,在循环中我需要根据这些范围设置变量值(X_state)。例如,如果我有一个从 1 开始到 200 的循环,并且每当范围的开始代表 60 的倍数且结束等于 start+5 时,我需要将变量 X_state 设置为从 0 到 1。因此,我不确定如何在本例中从 60 开始更新到 65,然后从 120 开始更新到 125,从 180 开始更新到 185。


它仅适用于我的第一个范围,即 [60-65]


periodic = 60

for i in range(200):

print(i)

if (i%periodic==0)or (i>=periodic and i<=periodic+5):

    x_state = 1

else:

    x_state= 0

print("x_state= ",x_state)


翻阅古今
浏览 48回答 2
2回答

慕慕森

您的 if 语句仅检查periodic(60),而不检查 的倍数periodic。这应该可以达到你想要的效果:periodic = 60for i in range(200):&nbsp; print(i)&nbsp; x_state = 0&nbsp; if 0 <= i % periodic <= 5:&nbsp; &nbsp; &nbsp; x_state = 1&nbsp; print("x_state= ",x_state)periodic在这里,我可以通过检查数字模数来计算 的任何倍数periodic。

红糖糍粑

periodic = 60for i in range(200):&nbsp; if (i % periodic >= 0) and (i % periodic <= 5):&nbsp; &nbsp; x_state = 1&nbsp; else:&nbsp; &nbsp; x_state = 0&nbsp; print(i, "x_state = ", x_state)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python