In: Computer Science
question: Phone Number CheckingAlice has been having trouble with
people filling her website’s form incorrectly, especially with
phone numbers. She’d like tomake sure a user’s phone number input
only has digits (other than -) and is exactly 10 digits
long.Finishvalidphonenumber(string)such that the function returns
True if a phone number is valid, and False if not.
def valid_phone_number(number: str) -> bool:
"""
Return True if the number is a valid phone
number. A valid phone number:
1) Has exactly 10 digits (we are excluding the
country code)
2) Only has digits (no alphabets or special
characters)
3) May have "-" to split numbers. Example:
0123456789 and 012-345-6789 are
BOTH valid
Do *not* use loops for this problem. Try to make sure you only use built-ins
Hint: you will need 3 built-in string methods
>>>
valid_phone_number("0123456789")
True
>>>
valid_phone_number("012-345-6789")
True
>>>
valid_phone_number("01-23-45-67-89")
True
"""
# TODO: do some checking here
# change this
return True
#### Part 2: String Functions with loops ###
Code in Python with comments
def valid_phone_number(number: str) -> bool:
# Firstly we remove all the occurance of - from our phone number
number = number.replace("-", "")
# After this our string should be of length 10 and a number
# Check for length
if(len(number)!=10):
return false
# Check for number
return number.isdigit()
print(valid_phone_number("0123456789"))
print(valid_phone_number("012-345-6789"))
print(valid_phone_number("01-23-45-67-89"))
python code screenshot for indentation
Console Output Screenshot
Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.