""" This program: - asks the user to enter a string. - verifies that the string represents an integer, and has the format: - [optional] white space at the start - [optional] minus sign - a sequence of consecutive characters of digits, from 0 to 9. - [optional] white space at the end """ string = raw_input("enter a string: ") print "checking if", string, "is an integer..." position = 0 # we will set illegal_flag to true if we find proof that the string is # not a valid integer illegal_flag = False # skip any white space at the beginning while position < len(string): character = string[position] # if we find white space (plain space or a tab or a newline), # skip it and continue if (character in " \t\n"): position = position + 1 # otherwise, we have reached the end of any possible initial white space. # Time to move on to the next checks else: break # check if first non-space character is minus sign, skip it if it is if position < len(string): character = string[position] if character == "-": #skip minus sign position = position + 1 # we now should get a string of consecutive digits. Let's count how many digit_count = 0 while position < len(string): character = string[position] if character in "0123456789": position = position + 1 digit_count = digit_count + 1 else: break # we should make sure we found at least one digit if digit_count == 0: print "no digits found after initial whitespace" illegal_flag = True # we should now skip any whitespace left at the end. Note: anything # that is not whitespace means the string is not a valid integer. # skip any white space at the beginning while position < len(string): character = string[position] # if we find white space (plain space or a tab or a newline), # skip it and continue if (character in " \t\n"): position = position + 1 # otherwise, we have reached the end of any possible initial white space. # Time to move on to the next checks else: print "illegal character found in trailing white space:", character illegal_flag = True break if (illegal_flag == True): print "String", string, "is not a valid integer." else: print "Verified string", string, "as a valid integer."