简化if语句时遇到问题

时间:2020-07-21 02:29:43

标签: python

使用Python。 我想创建一个非常简单的系统,告诉python如果将满容量减少1,则弹药消耗为真,而当以后弹药消耗为真时,我会让python知道弹药被消耗了。我的代码的问题在于弹药的消耗量始终为True。

如果您不了解,请看以下代码:

# fc means full capacity, and that number will tell the player for an example how much arrows they have
fc1 = 10
fc2 = 20
fc3 = 30
fc4 = 40
fc5 = 50
fc6 = 60
fc7 = 70
# If Wanted to use capacities in a list
full_capacity = [fc1, fc2, fc3, fc4, fc5, fc6, fc7]
# It is false because it did not get consumed yet
ammo_consumption = None
# it means that if r_approval is True then in the defined later reload system it can get reloaded if the player
# of course press a specific button
r_approval = False
# just to clean an error
o_o_o_o_o_o_o_o_o = r_approval
# checking
print(fc1, ammo_consumption)
# here I tell python how it works
if fc1 > 9:
    ammo_consumption = True
    r_approval = True
if fc2 > 19:
    ammo_consumption = True
    r_approval = True
if fc3 > 29:
    ammo_consumption = True
    r_approval = True
if fc4 > 39:
    ammo_consumption = True
    r_approval = True
if fc5 > 49:
    ammo_consumption = True
    r_approval = True
if fc6 > 59:
    ammo_consumption = True
    r_approval = True
if fc7 > 69:
    ammo_consumption = True
    r_approval = True
shot1 = fc1 - 1
print(shot1, ammo_consumption)
shot2 = fc2 - 1
print(shot2, ammo_consumption)
shot3 = fc3 - 1
print(shot3, ammo_consumption)
shot4 = fc4 - 1
print(shot4, ammo_consumption)
shot5 = fc5 - 1
print(shot5, ammo_consumption)
shot6 = fc6 - 1
print(shot6, ammo_consumption)
shot7 = fc7 - 1
print(shot7, ammo_consumption)
# but here ammo_consumption is still true
print(ammo_consumption)

2 个答案:

答案 0 :(得分:0)

该代码未重复。但是,如果您期望以下行之后ammo_consumption为假:

# shot{i} = fc{i} - 1

这不会发生,因为:

1-顺序读取Python代码,并且分配后不会更新变量。

2-您没有更改任何变量fc1,...,fc7的值。

答案 1 :(得分:0)

您可以通过将其更改为循环来替换许多代码。试试这个

您可以使用一行创建该变量,而不是定义7个变量来存储值10至70,然后将其存储到列表中。请参阅full_capacity的定义。

此外,您无需遍历每个条件,而只需遍历列表以检查值即可。

最后,您可以基于full_capacity中的值将镜头分配为列表。

就像提供反馈的其他人一样,我仍然不确定您要做什么。所有条件都为真,因为您没有更改值。

full_capacity = [i for i in range(10,80,10)]

for i in range (7):
    if full_capacity[i] > (i*10 + 9):
        ammo_consumption = r_approval = True

shot = [(i - 1) for i in full_capacity]
print(shot)

此外,如果您可以定义实际的问题说明,我们也许可以为您提供帮助。让我们知道您要如何使用您的代码。解决这个问题的方法可能更简单。