0
class Satellite:
  
  def __init__(self, message):
    print(message)
    self.name = input("name: ").title()
    self.lbs = int(input("lbs: "))
    self.speed = int(input("speed: "))

lstSat = []
e= input("Would you like to create satellites? If yes, type O. If not, type another letter: ").lower()
i=0
while e=="o":
    lstSat.append(Satellite("Info for satellite "+str(i+1)))
    i+=1
    e= input("Type O to create another satellite: ").lower()

Hello,

How can I make sure that 2 Satellites cannot be the same?

metal
  • 27
  • 4
  • 1
    What do you want to happen if the same name is entered? Should it raise an exception? Silently overwrite the existing satellite of the same name? – Samwise Dec 07 '22 at 19:32
  • 1
    Does [this answer](https://stackoverflow.com/q/12101958/4583620) help? – Michael Ruth Dec 07 '22 at 19:50

2 Answers2

2

Please don't ask for user input during class construction. Much better to acquire the values elsewhere then use a straightforward constructor based on the user's input values.

In order to determine repetition, you need to override the eq dunder method.

Try this:

class Satellite:
    def __init__(self, name, lbs, speed):
        self._name = name
        self._lbs = lbs
        self._speed = speed
    def __eq__(self, other):
        if isinstance(other, str):
            return self._name == name
        if isinstance(other, type(self)):
            return self._name == other._name
        return False
    def __str__(self):
        return f'Name={self._name}, lbs={self._lbs} speed={self._speed}'

lstSat = []

PROMPT = 'Would you like to create satellites? If yes, type O. If not, type another letter: '

while input(PROMPT) in 'Oo':
    name = input('Name: ').title()
    if name in lstSat:
        print(f'{name} already in use')
    else:
        lbs = int(input('lbs: '))
        speed = int(input('Speed: '))
        lstSat.append(Satellite(name, lbs, speed))

for satellite in lstSat:
    print(satellite)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1

I would go for iteration in list and check names with every satellite

...
while e=="o":
    satellite = Satellite("Info for satellite " + str(i+1))
    if check_reapeated_name(lstSat, satellite.name): # see definition of function bellow
        lstSat.append(satellite)
    else:
        # here do some output or error handling
    ...
...

and the definition of check_reapeated_name() would be something like this:

def check_reapeated_name(lstSat, satellite_name):
    for i in lstSat:
        if i.name == satellite_name:
             return False
    return True
Kaldesyvon
  • 86
  • 1
  • 8