亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么當變量變為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 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號