Reputation: 61
A little background on the program. it sets up a graphwindow with 2 pictures of the candidates, some instructions and an entry box, the user then puts the abbreviation into the entry box and clicks on one of the candidates and it displays the amount of votes are equivalent to whatever state then entered. I am having trouble writing an exception handler thats supposed to print an error message if the user enters a state that is not in my list. heres the section of the code that im having trouble with:
while True:
vote = win.getMouse()
voteX = vote.getX()
voteY = vote.getY()
#Romney
if voteX >= 163 and voteX <= 237 and voteY <= 100:
enteredtext = entrybox.getText()
enteredtextu = enteredtext.upper()
for i, s in enumerate(STATE_LIST):
if enteredtextu != s:
print('Not a state')
else:
totalvotesr += STATE_VOTES[enteredtextu]
votesnumr = ('VOTES:' ,totalvotesr)
displayvotesr.setText(votesnumr)
entrybox = Entry(Point(WINDOW_WIDTH/2, WINDOW_HEIGHT/1.1), 10)
entrybox.draw(win)
if totalvotesr >= 270:
circle_winner(win, Point(WINDOW_WIDTH/4, WINDOW_HEIGHT/12))
cross_out_loser(win, Point(WINDOW_WIDTH/(4/3), WINDOW_HEIGHT/12))
STATE_LIST is a list of all 50 states abbreviated. What i tried to do is use enumerate and have it check entereredtextu to all items in the list and if it isnt there it would print "Not a state". the problem i am having is that when i enter a state thats not in my list it prints "Not a state" 50 times and when i enter a state that is on the list it displays the amount of votes like its supposed to, but also prints "Not a state" 50 times
Upvotes: 0
Views: 77
Reputation: 8982
Here's what's going on. Let's say the user enters AR
:
Let's start 'enumerating' over the list of states:
AK != AR ? Yup! print 'Not a state'
AL != AR ? Yup! print 'Not a state'
AR != AR ? Oh these are the same! Print the number of votes!
AZ != AR ? Yup! print 'Not a state'
... so on ...
Upvotes: 1
Reputation: 14271
You check for every state whether its name matches the entered text, as that check is inside the for loop. So it makes sense that you get 'Not a state' 50 (or 49) times .
Try the code below instead. It checks just once whether enteredtextu
is in the list of states, and enters the loop for finding the number of votes only if it is.
...
enteredtext = entrybox.getText()
enteredtextu = enteredtext.upper()
if not enteredtextu in STATE_LIST:
print 'Not a state'
else:
for i, s in enumerate(STATE_LIST):
# ... etc
Upvotes: 2