[Tutor] Created Function, Need Argument to be a String
Matt Williams
matt.williams45.mw at gmail.com
Thu Dec 15 03:01:52 EST 2016
Use the str() function.
M
On Thu, 15 Dec 2016, 07:56 Bryon Adams, <bryonadams at openmailbox.org> wrote:
> Is there a way to force my argument to always be a string before
> entering the function? Else, is there a better way to go about this? In
> whatever program I write, I could change what I want as input to be a
> string prior to tossing it into the function but I think it would make
> more sense for my function to already do it. The function otherwise
> works. This is on Python3.5 under Fedora 25
>
> The only other thing I could think of would be to put exceptions in for
> syntax error and whatever else pops up as I go along, though to be
> honest it *should* always be a string that gets dumped into the
> function. Not sure how I'd put the exception together though since it's
> not making it into the function prior to failing.
>
> -------------------------------------------
> Error from interpreter: (looks like it's taking issue with it being a
> number it doesn't know how to deal with)
>
> >>> ip_checker(169.254.0.1)
> File "<stdin>", line 1
> ip_checker(169.254.0.1)
> ^
> SyntaxError: invalid syntax
>
> -------------------------------------------
> My function:
>
> def ip_checker(ip_address):
> '''
> Takes one IP address and checks whether it is valid or not.
> '''
> # Try to convert to integers
> try:
> ip_addr = [int(i) for i in ip_address.split('.')]
> except ValueError:
> print('Invalid characters were entered or an octet is empty, please
> try again.')
> return False
>
> # Determine how many octets were entered
> if len(ip_addr) != 4:
> print('Incorrect number of octets, please try again.')
> return False
>
> # Determine validity of first octet
> if ((ip_addr[0] > 223) and (ip_addr[0] < 256)) or (ip_addr[0] == 0):
> print('First octet is reserved or zero.')
> return False
>
> # Determine if this is a loopback address
> if ip_addr[0] == 127:
> print('I think that was a loopback address, please try again.')
> return False
>
> # Determine if this is an APIPA address
> if (ip_addr[0] == 169) and (ip_addr[1] == 254):
> print('I think that was an APIPA address, please try again.')
> return False
>
> # Determine if the last three octets are between 0-255
> for octet in (ip_addr[1], ip_addr[2], ip_addr[3]):
> if octet not in [i for i in range(0,256)]:
> print('Octet too large or too small, please try again.')
> return False
> else:
> print('The IP address {} is valid.'.format(ip_address))
> return True
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list