Reputation: 59
I have a variable called lives in a while loop. I want it to stop the function when it becomes 0. This doesn't happen and when I print the variable it says the value is in the negatives and it doesn't stop the loop. It also has another condition which is players. When I remove that condition, it works. This is really confusing. Can someone explain it to me? (Keep in mind I am not very experienced and I just started learning python)
import random
global players
global lives
players = 10
lives = 5
def 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()
Upvotes: 0
Views: 518
Reputation: 247
First of all, remove those global variables and use arguments in your function. Second, you need to use and
instead of or
in your while loop.
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)
Upvotes: 1