为了账号安全,请及时绑定邮箱和手机立即绑定

为什么当变量变为0时,while循环不停止?(Python)

为什么当变量变为0时,while循环不停止?(Python)

温温酱 2023-08-15 16:43:02
我有一个名为“lives”的变量,位于 while 循环中。我希望它在变为 0 时停止该函数。这不会发生,当我打印变量时,它说该值是负数,并且它不会停止循环。还有一个条件就是玩家。当我消除这个条件时,它就起作用了。这确实令人困惑。有人可以向我解释一下吗?(请记住,我经验不足,我刚刚开始学习 python)import randomglobal playersglobal livesplayers = 10lives = 5def getRandom():    players = 10    lives = 5    print("There are 9 people around you. You and the computer will both guess a number from 1 to 5. If your numbers are the same, that amount of players will be out, but if your answers are different, you lose a life. You have 5 lives and you get an extra one if you both guess the same number. Good Luck!")    while(lives > 0 or players > 0):          myGuess = input("What number do you choose")          compGuess = random.randint(1,5)          myGuess = int(myGuess)          print(f"Computer chose {compGuess}")          if compGuess == myGuess:              players = players - compGuess              if myGuess == 1:                  print(f"You took out {compGuess} player")              else:                print(f"You took out {compGuess} players")          else:              lives -= 1              print(f"You lost a life! You now have {lives} lives remaining")              print(f"There are {players} players left")getRandom()
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

首先,删除这些全局变量并在函数中使用参数。其次,您需要在 while 循环中使用and而不是使用。or


import random

number_of_players = 10

number_of_lives = 5


def getRandom(lives, players):

    print("There are 9 people around you. You and the computer will both guess a number from 1 to 5. If your numbers are the same, that amount of players will be out, but if your answers are different, you lose a life. You have 5 lives and you get an extra one if you both guess the same number. Good Luck!")

    while(lives > 0 and players > 0):

          myGuess = input("What number do you choose")

          compGuess = random.randint(1,5)

          myGuess = int(myGuess)

          print(f"Computer chose {compGuess}")

          if compGuess == myGuess:

              players = players - compGuess

              if myGuess == 1:

                  print(f"You took out {compGuess} player")

              else:

                print(f"You took out {compGuess} players")

          else:

              lives -= 1

              print(f"You lost a life! You now have {lives} lives remaining")

              print(f"There are {players} players left")

              

getRandom(number_of_lives, number_of_players)


查看完整回答
反对 回复 2023-08-15
  • 1 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信