Data Hiding | Sololearn: Learn to code for FREE!

0

Data Hiding

Data Hiding We are working on a game. Our Player class has name and private _lives attributes. The hit() method should decrease the lives of the player by 1. In case the lives equal to 0, it should output "Game Over". Complete the hit() method to make the program work as expected. class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): #your code goes here if self._lives == 0: print('Game Over') else: return self._lives-=1 p = Player("Cyberpunk77", 4) p.hit() p.hit() p.hit() File "<ipython-input-298-8696dd8489ab>", line 11 return int(self._lives)-=1 ^ SyntaxError: invalid syntax

4/13/2021 2:31:43 PM

Mukhammad Sadriddinov

6 Answers

New Answer

+2

You should not return decreased lives. Even if you need it, Python interpreter sees it as invalid syntax; then you need to do decreasing of/assigning to _lives and returning it as different statements. Hint: the problem is in `return self._lives-=1`.

+3

Thank you so much. Now I got the answer here is the correct answer: class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): self._lives -= 1 if self._lives == 0: print('Game Over') #your code goes here p = Player("Cyberpunk77", 3) p.hit() p.hit() p.hit()

+1

I don't understand why it couldn't be: def hit(self): if self._lives > 0: self._lives -= 1 else: print('Game Over')

0

Mukhammad Sadriddinov, correct! You even fixed a mistake I did not spot!

0

class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): # your code goes here if self._lives == 0: print('Game Over') else: self._lives -= 1 return self._lives p = Player("Cyberpunk77", 4) print(p.hit()) print(p.hit()) print(p.hit())

0

class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): self._lives -= 1 if self._lives <= 0: print('Game Over') return self._lives p = Player("Cyberpunk77", 3) p.hit() p.hit() p.hit()