[Tutor] Created Function, Need Argument to be a String

Sibylle Koczian nulla.epistola at web.de
Fri Dec 16 13:49:25 EST 2016


Am 12.12.2016 um 17:29 schrieb Bryon Adams:
> 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.
>

Syntax errors don't raise exceptions, because the program doesn't start 
at all as long as it contains them. Exceptions are raised at runtime.

> -------------------------------------------
> 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
>
You are calling the function with an invalid literal: a number can't 
contain more than one decimal point and a string literal needs quotes 
around it.

If the argument is valid but is no string (a number, a list or anything 
else) trying to split it raises an AttributeError:

 >>> s = 123.456
 >>> s.split('.')
Traceback (most recent call last):
   File "<pyshell#1>", line 1, in <module>
     s.split('.')
AttributeError: 'float' object has no attribute 'split'
 >>> ['a', 'b', 'c'].split('.')
Traceback (most recent call last):
   File "<pyshell#2>", line 1, in <module>
     ['a', 'b', 'c'].split('.')
AttributeError: 'list' object has no attribute 'split'

So you could use a second except clause:

try:
     ip_addr = ...
except ValueError:
     ...
except AttributeError:
     print("Argument must be a string, please try again.")
     return False


> -------------------------------------------
> 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
>
...


HTH



More information about the Tutor mailing list