Python Forum

Full Version: Phone Number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def check_phone():
while True:
phone = input("Please provide your phone number: ")
if len(phone)!=10 or ' ' in phone or phone.isdigit!=True:
print("No")
else:
print("Yes")

Conditions to check:10 digits, no whitespace,length has to 10.

Please provide your phone number: 9 99999999
No
Please provide your phone number: 999999999A
No
Please provide your phone number: 999999999
No
Please provide your phone number: 9999999999
No - STILL SAYS NO.
Where did I go wrong ?

Thanks
You can simply check what your conditions return:

>>> phone = '9999999999' 
>>> len(phone) != 10
False
>>> '' in phone
True
>>> phone.isdigit != True 
True
It quite obvious that this should return No as at least one condition is True.

EDIT:

Some explanation as well:

- len() comparison is OK
- you probably want to check ' ' not ''. My mistake, you checked for ' ' but this is actually not necessary, see below
- you probably want phone.isdigit() not phone.isidigit

You don't need to check for space in string, str.isdigit() it does it for you under the hood:

>>> help(str.isdigit)
Help on method_descriptor:

isdigit(self, /)
    Return True if the string is a digit string, False otherwise.
    
    A string is a digit string if all characters in the string are digits and there
    is at least one character in the string.
(END)
Space is obviously not a digit, so it will return False if space is present.

In this case I would use 'positive' matching (True) not 'negative' (False):

if len(phone) == 10 and phone.isdigit():
     # this is phone number

# alternative with built-in all:

if all((len(phone) == 10, phone.isdigit())):
    # this is phone number
A phone number can not only contain numbers.

it may also be a country code prefixed.
(Aug-22-2019, 08:10 AM)Axel_Erfurt Wrote: [ -> ]A phone number can not only contain numbers.

it may also be a country code prefixed.

Yep, in real life scenarious there can be spaces in phone numbers as well as hypens ('-') and country code prefix ('+'). So numbers must be 'cleaned' more thoroughly.