Python Forum

Full Version: Wrong code in Python exercise
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am practicing Python from a learning book. When i type this code i don't get the expected result. It should return:
" Phone number found: 415-555-1011
Phone number found: 415-555-9999
Done" But i get only as a result: "done". What am i doing wrong?

def isPhoneNumber(text):
    if len(text)!=12:
        return False
    for i in range(0,3):
        if not text.isdecimal():
            return False
    if text[3]!='-':
        return False
    for i in range(4,7):
        if not text[i].isdecimal():
            return False
    if text[7]!='-':
        return False
    for i in range(8,12):
        if not text[i].isdecimal():
            return False
    return True

message='Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
    chunk=message[i:i+15]
    if isPhoneNumber(chunk):
        print('Phone number found: ' + chunk)
print('Done')
There were only two things that I found that should be corrected. Line 5 should readif not text [i].isdecimal():instead ofif not text.isdecimal(): and line 21 should bechunk=message[i:i+12].
def isPhoneNumber(text):
	if len(text)!=12:
		return False
	for i in range(0,3):
		if not text [i].isdecimal():
			return False
	if text[3]!='-':
		return False
	for i in range(4,7):
		if not text[i].isdecimal():
			return False
	if text[7]!='-':
		return False
	for i in range(8,12):
		if not text[i].isdecimal():
			return False
	return True
 
message='Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
	chunk=message[i:i+12]
	if isPhoneNumber(chunk):
		print('Phone number found: ' + chunk)
print('Done')
Output:
Press ENTER or type command to continue Phone number found: 415-555-1011 Phone number found: 415-555-9999 Done
Thanks! That worked.