【问题标题】:Why the if statement is being executed yet the condition is false?为什么 if 语句正在执行但条件为假?
【发布时间】:2021-10-14 17:34:19
【问题描述】:

即使变量bullets_fire 包含布尔值False,下面的命令也会被执行。我还在if语句中添加了bullets_fire的print语句,它输出False,为什么会执行呢?

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE and not bullets_fire:
        print(bullets_fire)
        bullets_fire = True
        bullets_x = player_x
        bullets_y = player_y

【问题讨论】:

  • 如果bullets_fire = False 那么not bullets_fire 是什么?
  • 希望我能帮上忙。如果我的回答让你满意,请采纳为正确答案(按旁边的 V 键)
  • @Ram 这不是真的。它以前对我有用

标签: python if-statement printing boolean


【解决方案1】:

您的条件在布尔变量之前包含not。 仅当event.key == pygame.K_SPACE 评估为Truebullets_fire 评估为False 时才会执行,因为not FalseTrue 相同。

【讨论】:

  • 我已经尝试了所有方法:and bullets_fire is Falseand bullets_fire,甚至在该 if 语句中嵌套了另一个 if 语句 if bullets_fire is False:,但没有任何效果。这不是我第一次遇到类似的问题。
  • 首先,您应该使用== 比较布尔值,而不是使用is 关键字。其次,你想完成什么?一个同时拥有bullet_fireevent.key == pygame.K_SPACE 的条件,当其中任何一个为假时将被评估为假?
  • 我按你说的试了操作符,但是不管用。只有当bullets_fire 为假且event.key == pygame.K_SPACE 为真时,嵌套在 if 语句中的代码才应该运行。
  • @SolnLase 我不确定我是否理解,在您的原始问题中,bullets_firefalse 并且 if event.key == pygame.K_SPACEtrue,它进入了状态,那么问题出在哪里?
  • 对不起,我的意思是如果两个条件都为真。我的坏
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 2023-01-03
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多