Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 8 Online
OpenStudy (anonymous):

As I understand it raw_input is received as a string, correct? How would I write code that checks each character of the input and determines if it's a digit? I know about the helpful string.digits list, but this only works directly for 1 digit (a 2-digit string isn't in the digits list). How can I step through the entered text one character at a time and make sure they are all digits? Specifically, I want to have an input message repeat (perhaps on a while loop) until the user enters a valid number...

OpenStudy (anonymous):

you can write a for loop using index i and loop through each element of the string and determine it is a digit or not..

OpenStudy (anonymous):

I was trying to, but I kept getting errors when I tied to make i step through each element string[i]. I wound up finding a little function on stackoverflow.com that looks like this: Then you just initialize your input to a non-number and then do a while loop as long as this function returns false. Pretty handy! def is_number(s): try: float(s) return True except ValueError: return False

OpenStudy (anonymous):

i know that import string has a few handy things for this it has a string.isAlpha() to tell you if the contents are in the alphabet, maybe it was alpha numberic, it stopped people from putting in # and what not

OpenStudy (anonymous):

Ya that one is pretty handy!!.. the try n except block is cool..

OpenStudy (anonymous):

the isdigit method ( http://docs.python.org/library/stdtypes.html?highlight=isdigit#str.isdigit) works on the entire string - http://dpaste.com/573808/ or if you want to test each letter individually:you could use a try/except statement: http://dpaste.com/573818/ http://docs.python.org/reference/compound_stmts.html#the-try-statement

OpenStudy (anonymous):

yeah, handled exceptions in action, pretty cool

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!