[Tutor] Created Function, Need Argument to be a String
Juan C.
juan0christian at gmail.com
Thu Dec 15 11:49:08 EST 2016
On Mon, Dec 12, 2016 at 2:29 PM, Bryon Adams <bryonadams at openmailbox.org> wrote:
> Is there a way to force my argument to always be a string before entering
> the function?
You could do the following:
1. Use `def ip_checker(ip_address: str):` to make it more clear that
you're expecting a str, but remember, this is just a "hint", it
doesn't enforce anything. (Read more at
https://docs.python.org/3/library/typing.html#module-typing)
2. You could also write something like that:
valid_ip = "192.168.0.1"
invalid_ip = 10
def ip_check(ip_addr: str):
if type(ip_addr) is not str:
raise TypeError('The IP address should be a string.') #
https://docs.python.org/3/library/exceptions.html#TypeError
# continue your function...
print(ip_addr, 'is valid!')
ip_check(valid_ip) # 192.168.0.1 is valid!
ip_check(invalid_ip) # TypeError: The IP address should be a string.
More information about the Tutor
mailing list