我在python代码上遇到问题。我试图在if语句后增加和减少两个值。但是,这无法实现(错误:语法无效)。知道当我仅增加一个值(例如A_p)时,它会很好地工作。错误是否来自and运算符?是否可以在if语句后执行多种操作?
谢谢。
Omer
k1 = 0.2
k2 = 0.2
Delta_t = 2
A_p = 4
B_p = 3
list_nm = [0.800, 0.801, 0.752, 0.661, 0.169, 0.956, 0.949, 0.003, 0.201, 0.291, 0.615, 0.131, 0.241, 0.685, 0.116, 0.241, 0.849]
for i in range(7):
if list_nm[i] < (A_p/7):
print("Particle A was choosen")
if list_nm[i] < k1*Delta_t:
A_p -= 1 and B_p += 1
else:
A_p = A_p and B_p = B_p
elif list_nm[i] < (B_p/7):
print("Particle B was choosen")
if list_nm[i] < k2*Delta_t:
A_p +=1 and B_p -=1
else:
A_p = A_p and B_p = B_p
else:
print("No choice was made")
A_p = A_p and B_p = B_p
print(B_p)
A_p -= 1 and B_p += 1
不是有效的Python,and
是用于组合布尔值的特定关键字,例如:
if a > 3 and a < 7:
pass
您想要的是两个单独的语句:
A_p -= 1
B_p += 1
或者,如果您必须放在一行上(并且我会问为什么,您认为这是必要的),请根据您的喜好选择以下选项之一:
A_p -= 1 ; B_p += 1
(A_p, B_p) = (A_p - 1, B_p + 1)
此外,该行:
A_p = A_p and B_p = B_p
即使将其拆分为两个语句,实际上也无济于事。如果这是else:
块中唯一的内容,您也可以将其与前面的else
行一起完全删除。
换句话说,从以下内容开始:
(k1, k2, Delta_t) = (0.2, 0.2, 2)
(A_p, B_p) = (4, 3)
list_nm = [0.800, 0.801, 0.752, 0.661, 0.169, 0.956, 0.949, 0.003, 0.201, 0.291, 0.615, 0.131, 0.241, 0.685, 0.116, 0.241, 0.849]
for i in range(7):
if list_nm[i] < (A_p / 7):
print("Particle A was choosen")
if list_nm[i] < k1 * Delta_t:
A_p -= 1
B_p += 1
elif list_nm[i] < (B_p / 7):
print("Particle B was choosen")
if list_nm[i] < k2 * Delta_t:
A_p += 1
B_p -= 1
else:
print("No choice was made")
print(B_p)