【问题标题】:Each rank repeats itself over and over again每个等级一遍又一遍地重复自己
【发布时间】:2021-11-22 10:50:15
【问题描述】:

我希望在每次运行循环时继续执行 totalxp 并将其相加,但是我希望每次达到更高等级时停止打印等级 1。

import math
totalxp = 0
rank = 1
while totalxp < 2000:
  xpearned = int(input('Enter xp earned last game'))
  totalxp = xpearned + totalxp
  if totalxp >= 100:
    rank = 1
    print('You have been promoted to Corporal', rank)
    totalxp = totalxp - 100
    print(totalxp)
  if totalxp >= 300:
    rank = rank + 1
    print('You have been promoted to Sergeant', rank)
    totalxp = totalxp - 300
  if totalxp >= 700:
    rank = rank + 2
    print('You have been promoted to Staff Sergeant', rank)
    totalxp = totalxp - 700
  if totalxp >= 1500:
    print('You have been promoted to Warrant Officer', rank)
  print(totalxp)

【问题讨论】:

    标签: python while-loop iteration


    【解决方案1】:

    发生这种情况的原因是,如果一个值大于 300,则它必须大于 100,并且将执行第一个 if 语句。为避免这种情况,只需将检查上述较高值的 if 语句放在您的代码中,并将检查较小值的 if 语句放在下面。另外,对其他 if 块使用 elif。

    import math
    totalxp = 0
    rank = 1
    while totalxp < 2000:
      xpearned = int(input('Enter xp earned last game'))
      totalxp = xpearned + totalxp
      if totalxp >= 1500:
        print('You have been promoted to Warrant Officer', rank)
      elif totalxp >= 700:
        rank = rank + 2
        print('You have been promoted to Staff Sergeant', rank)
        totalxp = totalxp - 700
      elif totalxp >= 300:
        rank = rank + 1
        print('You have been promoted to Sergeant', rank)
        totalxp = totalxp - 300
      elif totalxp >= 100:
        rank = 1
        print('You have been promoted to Corporal', rank)
        totalxp = totalxp - 100
      print(totalxp)
    

    【讨论】:

    • 非常感谢。我的计算机科学老师没有正确回答我,我向社区寻求帮助!
    • 谢谢,你能把答案标记为正确吗?
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2020-07-16
    相关资源
    最近更新 更多