Question:
I'm trying to pass the "ink" parameter to the "Pen" class but I can't. I've tried using boolean expressions instead of index, but still with no result. Could someone give me a help ?
class Caneta():
açao = 'escrever'
def __init__(self, tinta):
self.tinta = tinta
def NivelTinta(tinta):
rng = range(0,100)
for tinta in rng:
if tinta in rng[5:100]:
print('A caneta está boa')
break
elif tinta in rng[1:4]:
print('A caneta está falhando')
break
else:
print('A tinta acabou')
break
CanetaAzul = Caneta(50)
CanetaAzul.NivelTinta()
Every time I run the code, "The ink ran out" appears, and "The pen is fine" should appear, because the parameter I set is "50".
Answer:
It lacks some logic in its code, besides having a certain error.
Firstly, you are not getting tinta
as a parameter, and this is not even necessary since the value is already saved in the object. You are taking self
as a parameter (which is the object itself). So instead of trying to directly access tinta
, you must access the property (or attribute) tinta
that is within the parameter (also called tinta
in this case – I changed the name to self
just to avoid confusion).
Second, this loop is completely unnecessary. You don't need to loop to find out if the ink level is in a certain range, you just need to use the logical comparators <
(less than) and >
(greater than).
Another important thing, even if the loop was necessary, the break
statement makes the code "jump out of the loop ", this means that the conditions will be evaluated only once and after that the loop is stopped.
I made an adaptation in your code and now it is functional.
class Caneta():
acao = 'escrever'
def __init__(self, tinta):
self.tinta = tinta
def NivelTinta(self):
print(self.tinta)
if(1 <= self.tinta <= 5):
print('A caneta esta falhando')
elif(5 < self.tinta <= 100):
print('A caneta esta boa')
else:
print('A tinta acabou')
CanetaAzul = Caneta(50)
CanetaAzul.NivelTinta()