1

else statement not working. how to close loop when nothing is entered? suggestions on how to approach?

def main():
    print "~*~*~*~*~*~ Timbuktu Archery Contest ~*~*~*~*~*~"
    archerList = [] #list
    timeList = [] #list2
    name = raw_input ("Enter contestants first name: ")
    s = str(name)
    archerList.append(name)
    while name > 0:
        time = raw_input ("Enter time (in milliseconds) for %s: " % s)
        timeList.append(time)
        name = raw_input ("Enter contestants first name: ")
        s = str(name)
        archerList.append(name)
    else:
        name == ""
        print "Slowest archer was " , min(timeList)
        print "Fastest archer was " , max(timeList)
3
  • What do you mean by nothing is entered? And where? Commented Feb 15, 2013 at 7:53
  • raw_input takes the input as string, what do you get by doing > 0 with it? If you want a number from the raw_input, better cast it to int... Commented Feb 15, 2013 at 7:55
  • And if you are reading a number, you should probably first change the variable name from name to something that really signifies holding a nnumeric vcalue. Commented Feb 15, 2013 at 7:56

4 Answers 4

2

To loop until an empty name is given:

while name:
Sign up to request clarification or add additional context in comments.

Comments

0

You need this:

while len(name) > 0

Comments

0

You can escape from loop if nothing is entered by using this if-else construct

if (name==''):
    break
else:
    <job to be done>

1 Comment

In Python you can have if...else, for...else, while...else, try...else.
0

this is more pythonic. DRY = Dont Repeat Yourself.

def main():
    print "~*~*~*~*~*~ Timbuktu Archery Contest ~*~*~*~*~*~"
    min = max = 0
    while True:
        name = raw_input ("Enter contestants first name: ")
        if not name:
            break
        start = raw_input ("Enter time (in milliseconds) for %s: " % name)
        min = start if start < min else min
        max = start if start > max else max
    print "Slowest archer was %i" % min
    print "Fastest archer was %i" % max

points to consider:

  • I removed archerList as you don't get values from it in your code
  • what happens if archers achieve the same time?
  • the "slowest archer was..." actually tells us the slowest archer's time, not their name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.