Search code examples
pythonstringwebaddress

Program to check a web site address is valid or not


I am writing a program that checks if a website has valid extension or not. First I did this

website_address = 'facebook.com'
website_address.endswith('.com')

It works fine. But I can check only one extension, so I thought to write a function that will check a list of extension.

def check_if_website_address_is_valid_by_extension(website_address):
    valid_extensions = ['.com', '.info', '.edu', '.org', '.biz', '.net']
    if website_address.endswith(valid_extensions):
        return 'check_if_website_address_is_valid_by_extension function returns True'
    else:
        return 'check_if_website_address_is_valid_by_extension functions returns False'

But when I call this function check_if_website_address_is_valid_by_extension(website_address) I get error

if website_address.endswith(valid_extensions):
TypeError: endswith first arg must be str or a tuple of str, not list

I write the program right, but I don't know by mistake. Help please!


Solution

  • So far, you are doing good. The only problem here is str.endswith function either takes a string or a tuple of string. Just change your list of valid extensions to tuple, It should work fine.

    valid_extensions = ('.com', '.info', '.edu', '.org', '.biz', '.net')
    

    SAMPLE OUTPUT:

    >>> check_if_website_address_is_valid_by_extension('facebook.com')
     'check_if_website_address_is_valid_by_extension function returns True'
    
    >>> check_if_website_address_is_valid_by_extension('google.net')
     'check_if_website_address_is_valid_by_extension function returns True'
    
    >>> check_if_website_address_is_valid_by_extension('Hello')
     'check_if_website_address_is_valid_by_extension functions returns False'
    

    One suggestion though, instead of returning such a long string, why don't you just return True or False Boolean value?