Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 11th, 2006, 2:09 PM   #1
UnKnown X
Hobbyist Programmer
 
UnKnown X's Avatar
 
Join Date: Dec 2005
Location: Sandvika, Norway
Posts: 114
Rep Power: 0 UnKnown X is an unknown quantity at this point
Send a message via MSN to UnKnown X
Catching only one word

Using this code to get a sequence of 'words' (well, numbers, but that's irrelevant) separated by a space, it fails at the split(" ") when only one word is given (I assume). However, it doesn't raise an exception and I'm unsure on how to catch the single word anyway.

def GetSequence(highNumber):
    while 1:
        sequence = GetString("Enter a Sequence of numbers separated by a space: ")
        try:
            list = []
            for word in sequence.split(" "):
                list.append(int(word))
        except ValueError:
            print "Error: '%s' is not a number! Try again." % word,
            continue
        except:
            print "Error! Try again.",
            continue
        break
    return list

Last edited by UnKnown X; Feb 11th, 2006 at 2:17 PM. Reason: Typo
UnKnown X is offline   Reply With Quote
Old Feb 11th, 2006, 2:14 PM   #2
UnKnown X
Hobbyist Programmer
 
UnKnown X's Avatar
 
Join Date: Dec 2005
Location: Sandvika, Norway
Posts: 114
Rep Power: 0 UnKnown X is an unknown quantity at this point
Send a message via MSN to UnKnown X
Found a solution!

def GetSequence(highNumber):
    while 1:
        sequence = GetString("Enter a Sequence of numbers separated by a space: ")
        try:
            list = []
            try:
                list.append(int(sequence))
            except ValueError:
                for word in sequence.split(" "):
                    list.append(int(word))
            except:
                print "Error! Try again.",
                continue
        except ValueError:
            print "Error: '%s' is not a number! Try again." % word,
            continue
        except:
            print "Error! Try again.",
            continue
        break
    return list


I love quick fixes!
UnKnown X is offline   Reply With Quote
Old Feb 11th, 2006, 2:21 PM   #3
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
We appreciate your posting the solution for other people. All too often people don't do that, or destroy their post, or something. Thanks.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Feb 11th, 2006, 2:24 PM   #4
UnKnown X
Hobbyist Programmer
 
UnKnown X's Avatar
 
Join Date: Dec 2005
Location: Sandvika, Norway
Posts: 114
Rep Power: 0 UnKnown X is an unknown quantity at this point
Send a message via MSN to UnKnown X
Glad to help! (Even though I probably mostly helped myself here... )
UnKnown X is offline   Reply With Quote
Old Feb 11th, 2006, 11:28 PM   #5
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Quote:
Originally Posted by UnKnown X
Using this code to get a sequence of 'words' (well, numbers, but that's irrelevant) separated by a space, it fails at the split(" ") when only one word is given (I assume). However, it doesn't raise an exception and I'm unsure on how to catch the single word anyway.
Your problem is elsewhere - it's perfectly ok to split on a non-existent token:
x = "1234"
print x.split(" ")  # Will be a single-element list.
The "GetString" is the likely culprit. Instead of hand-rolling your own, just use raw_input():
def get_sequence():
    while True:
        seq = raw_input("Enter a sequence of numbers separated by a space: ")
        try:
            return [int(word) for word in seq.split(" ")]
        except ValueError:
            print "Error: '%s' is not a number! Try again." % word
print get_sequence()
reasons for some of the other changes:
* functions and variables use lower_case; classes use MixedCase.
* high_number was unused
* "while True" is a little prettier than while 1
* It's easier to build a list comprehension than manually create and append elements.
* Never call a list "list" since it shadows a built-in.
* The only exception that the return... line is likely to raise is ValueError. Any other exception is a critical one (eg: MemoryError, in which case continuing is not a great idea)
* bare excepts shouldn't be used in 99% of cases.

-T.
hydroxide is offline   Reply With Quote
Old Feb 12th, 2006, 4:39 AM   #6
UnKnown X
Hobbyist Programmer
 
UnKnown X's Avatar
 
Join Date: Dec 2005
Location: Sandvika, Norway
Posts: 114
Rep Power: 0 UnKnown X is an unknown quantity at this point
Send a message via MSN to UnKnown X
Thanks for your post, hydroxide!


I don't think Get_string is doing anything wrong - it does use raw_input, just with error checking. I just put it in a separate function to keep it a bit neat.

Here it is anyway:

def Get_sequence():
    while True:
        sequence = Get_string("Enter a Sequence of numbers separated by a space: ")
        if sequence == None:
            return None
        try:
            token_list = []
            try:
                token_list.append(int(sequence))
            except ValueError:
                for word in sequence.split(" "):
                    token_list.append(int(word))
            except:
                print "Error! Try again.",
                return None
        except ValueError:
            print "Error: '%s' is not a number! Try again." % word,
            continue
        except:
            print "Error!",
            return None
        break
    return token_list

def Get_string(msg):
    while True:
        try:
            return raw_input(msg)
        except ValueError:
            print "ValueError exception encountered! Try again."
            continue
        except:
            print "Error!"
            return None
        break
    print "Loop error occured!"
    return None
UnKnown X is offline   Reply With Quote
Old Feb 12th, 2006, 5:14 AM   #7
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by UnKnown X
I don't think Get_string is doing anything wrong - it does use raw_input, just with error checking. I just put it in a separate function to keep it a bit neat.
Generally speaking, it's okay if a function raises an exception - that's what they're there for - just so long as the exception is eventually caught. It's also worth thinking about dividing your program in generalised pieces:
def parse_sequence(sequence):
    output = []
    for item in sequence.split(" "):
        try:
            output.append(int(item))
        except ValueError:
            raise ValueError, "'%s' is not a number! Try again." % item
    return output

def get_user_sequence(prompt):
    return parse_sequence(raw_input(prompt))

def printer(s):
    print s

def while_exceptions(function, logger = printer):
    while True:
        try:
            return function()
        except Exception, e:
            logger(e)

def main():
    def get_sequence():
        return get_user_sequence(
                "Enter a sequence of numbers separated by a space: ")
    print while_exceptions(get_sequence, printer)

main()
Arevos is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:57 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC