I am trying to write a program that accepts a phone number in the format XXX-XXX-XXXX
and translates any letters in the entry to their corresponding numbers.
Now I have this, and it will allow you to reenter the correct number if its not correct to start, but then it translates the original number entered. how do i fix this?
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
elif char in 'DEFdef':
x4='3'
s= s + x4
elif char in 'GHIghi':
x5='4'
s= s + x5
elif char in 'JKLjkl':
x6='5'
s= s + x6
elif char in 'MNOmno':
x7='6'
s= s + x7
elif char in 'PQRSpqrs':
x8='7'
s= s + x8
elif char in 'TUVtuv':
x9='8'
s= s + x9
elif char in 'WXYZwxyz':
x10='9'
s= s + x10
print(s)
import re
def validNumber(phone_nuber):
pattern = re.compile("^[\dA-Z]{3}-[\dA-Z]{3}-[\dA-Z]{4}$", re.IGNORECASE)
return pattern.match(phone_nuber) is not None
If you don't want to use regular expressions: You can use isalnum
to check if something is a number or letter. You can access the n
th character in a string using mystr[n]
so, you could try:
def validNumber(phone_number):
if len(phone_number) != 12:
return False
for i in range(12):
if i in [3,7]:
if phone_number[i] != '-':
return False
elif not phone_number[i].isalnum():
return False
return True
To see what phone_number[i]
is doing, try this:
for i in range(len(phone_number)):
print i, phone_number[i]
Using enumerate
:
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
return False
elif not c.isalnum():
return False
return True
Once you have it working, you should use it later (inside of main
) like:
def main():
phone_number = '' # an invalid number to initiate while loop
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translated_number = translateNumber(phone_number)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With