+ 1

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

13th Apr 2021, 2:31 PM
Mukhammad Sadriddinov
Mukhammad Sadriddinov - avatar
7 ответов
+ 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`.
13th Apr 2021, 3:02 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 7
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()
13th Apr 2021, 3:53 PM
Mukhammad Sadriddinov
Mukhammad Sadriddinov - avatar
0
Mukhammad Sadriddinov, correct! You even fixed a mistake I did not spot!
13th Apr 2021, 3:55 PM
#0009e7 [get]
#0009e7 [get] - avatar
0
I don't understand why it couldn't be: def hit(self): if self._lives > 0: self._lives -= 1 else: print('Game Over')
7th Oct 2021, 5:58 PM
Debora Reichert
Debora Reichert - avatar
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())
26th Jan 2022, 2:59 PM
Mohammad Jamal Mahmoud Al Jadallah
Mohammad Jamal Mahmoud Al Jadallah - avatar
0
class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): self._lives -= 1 @property def isAlive(self): return self._lives > 0 p = Player("Cyberpunk77", int(input())) i = 1 while True: p.hit() print("Hit # " + str(i)) i += 1 if not p.isAlive: print("Game Over") break
28th Mar 2023, 11:23 PM
المهندس أحمد
المهندس أحمد - avatar
- 1
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()
14th Feb 2022, 8:07 PM
Liria
Liria - avatar