【问题标题】:How to keep a value from resetting in a loop?如何防止值在循环中重置?
【发布时间】:2019-11-29 21:12:35
【问题描述】:

我一直在尝试为我的学校项目建立一个健康系统,但无论 Monster_health 不在循环中,我的朋友和我似乎都无法解决这个问题。

代码:

monster_health = 100
while monster_health > 0:
    playeraction = input('Placeholder beast wants to fight you!!\n1) Basic Attack')
    print(monster_health)
    if playeraction == 1:
        monster_health = monster_health-7
        continue
    if monster_health <= 0:
        print('You killed the monster!! Gain nothing, this is a test you barbarian')
        break

输出:

Placeholder beast wants to fight you!!
1) Basic Attack
100 #should print 97 but fails to

【问题讨论】:

  • 请编辑问题以包含实际输出和预期输出。

标签: loops python-3.7 integer-arithmetic


【解决方案1】:

替换

    if playeraction == 1:

    if playeraction == "1":

或:

    if int(playeraction) == 1:

因为您的输入是字符串格式而不是整数和 1 != "1"。

【讨论】:

    【解决方案2】:

    从您的代码中,您在更新之前打印怪物健康状况,因此第一次它将是“100”(初始值)。

    while monster_health > 0:
      playeraction = input('Placeholder beast wants to fight you!!\n1) Basic Attack')
      print(monster_health) # at this time, it is still 100
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 2021-04-22
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多