I have a simple election program. The following are the requirements:
class Politician
- Randomized votes.
Taking number of politicians as input from user.
num_politicians = input("The number of politicians: ")
Looping and creating instances
names = [] for x in range(num_politicians): new_name = input("Name: ") while new_name in names: new_name = input("Please enter another name: ") names.append(new_name) #### This part is the crux of my problem ### Create instances of the Politician class #### I want to do this in a way so that i can independently #### handle each instance when i randomize and assign votes
I have looked at:
- How do you create different variable names while in a loop? (Python)
- Python: Create instance of an object in a loop
However I could not find a solution to my problem
The Politician class is below:
class Politician:
def __init__(self, name):
self.name = str(name)
self.age = age
self.votes = 0
def change(self):
self.votes = self.votes + 1
def __str__(self):
return self.name + ": " + str(self.votes)
The Desired Output:
>>> The Number of politicians: 3
>>> Name: John
>>> Name: Joseph
>>> Name: Mary
>>> Processing...
(I use time.sleep(1.0) here)
>>> Mary: 8 votes
>>> John: 2 votes
>>> Joseph: 1 vote
My problem in one statement
I want to create class instances in the for-loop in such a way that i can assign them votes randomly (This would, I suppose, require me to independently handle instances.)
Any help would be appreciated.
You can store your instances in a list:
Now you can access individual instances:
I used a modified version of your class that gives each politician a default age if no is provided:
Now you can work with your list of politicians:
prints:
this:
prints:
Assign random votes:
Now:
prints:
The whole program:
And the usage:
UPDATE
As @martineau suggests, for real-live problems a dictionary would be more useful.
Create dictionary instead of a list:
and in the loop us the name as key when you add your instance: