简化if语句时遇到问题

2024-04-29 21:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果您不理解,以下是代码:

# 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)

Tags: trueifitprintapprovalconsumption弹药fc1
2条回答

通过将代码更改为循环,可以替换大量代码。试试这个

不需要定义7个变量来存储值10到70,然后将其存储到列表中,您可以使用一行来创建它。请参阅完整容量的定义

此外,您可以迭代列表来检查值,而不是检查每个条件

最后,您可以基于满容量的值将快照指定为列表

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

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)

此外,如果您能定义实际的问题陈述,我们可能会帮助您。让我们知道您试图对代码执行什么操作。也许有一个更简单的方法来解决这个问题

代码没有被重复。但是,如果您希望在这些行之后弹药消耗量为假:

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

这种情况不会发生,因为:

1-Python代码是按顺序读取的,变量在赋值后不会更新

2-您没有更改任何变量fc1、…、fc7的值

相关问题 更多 >