Home > Net >  How do I initialize values for list elements in a class in python
How do I initialize values for list elements in a class in python

Time:07-14

    def __init__(self):
        self.planets = ['Mercury', 'Venus', 'Mars',
                        'Jupiter', 'Saturn','Uranus',
                        'Neptune', 'Pluto']
        self.planets[0] = 0.38
        self.planets[1] = 0.91
        self.planets[2] = 0.38
        self.planets[3] = 2.34
        self.planets[4] = 0.93
        self.planets[5] = 0.92
        self.planets[6] = 1.12
        self.planets[7] = 0.62

    def calculate_spaceweight(self, weight):
        for i in range(len(self.planets)):
            print("your weight on", self.planets[i], " is", weight * self.planets[i] )
if __name__ == '__main__':

    weight = float(input("what is your Earthly weight: "))
    obj1 = Planet()
    print(obj1.calculate_spaceweight(weight))

The outputs are wrong, and i know theres a better way to initialize the values in the list but i cant figure out how. Heres what it is outputting:

your weight on 0.38  is 57.0
your weight on 0.91  is 136.5
your weight on 0.38  is 57.0
your weight on 2.34  is 351.0
your weight on 0.93  is 139.5
your weight on 0.92  is 138.0
your weight on 1.12  is 168.00000000000003
your weight on 0.62  is 93.0
None

Okay i made an edit, so its now outputting the correct answers

CodePudding user response:

When you use

self.planets[0] =  0.38

you are changing 0. index "Mercury" to 0.38

if you want more proper way you can use dictionaries like this

self.planets = {"Mercury": 0.38, "Venus": 0.91}

and for loop

for planet_name, planet_arg in self.planets.items():
   print("your weight on", planet_name, " is", weight * planet_arg)

CodePudding user response:

def __init__(self):
    self.planets = {
        'Mercury' : 0.38 , 
        'Venus'   : 0.91 , 
        'Mars'    : 0.38 ,
        'Jupiter' : 2.34 , 
        'Saturn'  : 0.93 ,
        'Uranus'  : 0.92 ,
        'Neptune' : 1.12 , 
        'Pluto'   : 0.62 }

def calculate_spaceweight(self, weight):
    for planet in self.planets:
        print("your weight on", planet, " is", self.planets[planet] * weight)
if __name__ == '__main__':

weight = float(input("what is your Earthly weight: "))
obj1 = Planet()
print(obj1.calculate_spaceweight(weight))

As John said, you cannot save the names and weights in a list, that is not how they work in python. A dictionary however can store values indexed by keys.

CodePudding user response:

A dictionary, which holds key-value pairs, is a more appropriate data structure for what you seem to want. A dictionary provides for quick lookup of values based on the keys.

However, since you never look up the multipliers based on the planet name, and only ever iterate over the entire dictionary, you could also use a list of tuples. In this list, each item is a tuple, whose first element is the planet's name and the second element is the planet's weight multiplier.

    def __init__(self):
        self.planets = [('Mercury', 0.38), ('Venus', 0.91), ('Mars', 0.38),
                        ('Jupiter', 2.34), ... and so on ]

    def calculate_spaceweight(self, weight):
        for planet_info in self.planets:
            planet_name = planet_info[0]  # First element of the tuple is the planet name
            planet_mult = planet_info[1]  # Second element is the multiplier
            print("your weight on", planet_name, " is", weight * planet_mult) 

Note my modification to your for i in range(len(self.planets)) loop: it is more pythonic to loop over the elements of a list rather than its indices, so I changed it to for planet_info in self.planets. Now, in each iteration, planet_info contains an element of the list, e.g. in the first iteration planet_info = ('Mercury', 0.38).


Seeing as you've named your class Planet, objects of this class should represent a single planet. Here's what I would do:

class Planet:
    def __init__(self, name, weight_multiplier):
        self.name = name
        self.weight_multiplier = weight_multiplier

    def calculate_spaceweight(self, weight):
        return self.weight_multiplier * weight

Now, in the main part of your program, make these planets:

# Create an empty list
planets = [] 

# Add all planets to it
planets.append(Planet('Mercury', 0.38))
planets.append(Planet('Venus', 0.91))
planets.append(Planet('Mars', 0.38))
planets.append(Planet('Jupiter', 2.34))
planets.append(Planet('Saturn', 0.93))
planets.append(Planet('Uranus', 0.92))
planets.append(Planet('Neptune', 1.12))
planets.append(Planet('Pluto', 0.62))

# Ask for user's weight
weight = float(input("Enter your Earth weight: "))

# Loop over all Planet objects in the planets list
for planet in planets:
    # Calculate weight on this planet
    planet_weight = planet.calculate_spaceweight(weight) 
    # Print message
    print(f"Your weight on {planet.name} is {planet_weight}")

The whole point of object-oriented programming is that a class will encapsulate all properties and methods that are relevant to the objects of that class. So, for example, you could add a property like revolution_period to your Planet class, and add a method which uses that to calculate your age in "Planet years" given "Earth years":

class Planet:
    def __init__(self, name, weight_multiplier, revolution_period_days):
        self.name = name
        self.weight_multiplier = weight_multiplier_days
        self.revolution_period = revolution_period

    def calculate_space_weight(self, weight):
        return self.weight_multiplier * weight

    def calculate_space_age(self, age):
        return 365 / self.revolution_period * age

mars = Planet("Mars", 3.72/9.81, 687)
# Ask for user's weight
weight = float(input("Enter your Earth weight (in kg): "))

print(f"You would weigh {mars.calculate_space_weight(weight)}kg on Mars")

# Ask for user's age
age = float(input("Enter your Earth age (in years): "))

print(f"You are {mars.calculate_space_age(age)} Mars-years old")
  • Related