The way I typically sanitize user input is by a safe cast function. You can except ValueError since that is what would be raise, but in this case, there's probably no reason to do that.
PHP Code
<?php
def safe_cast(new_type, value, default=None):
try:
default = new_type(value)
finally:
return default
There's also a pretty wide use for a temporary storage class that can be used to store and then check user input without having a ton of statements to get around the fact that there's no do/while loop. For example, if you wanted to force the user to keep entering user input until they entered something valid, you can do it with a simple class:
PHP Code
<?php
class Storage:
def __init__(self):
self.val = None
def set(self, val):
self.val = val
return val
def get(self):
return self.val
Now, to accept user input and such...
PHP Code
<?php
def is_valid_domain(domain):
if domain == "google.com": # arbitrary checking here... provide whatever checks you want
return True
return False
storage = Storage() # an instance of the storage class
while is_valid_domain(storage.set(input("Enter a domain: "))) is False:
print("Invalid domain. ", end="") # python3 only...
domain = storage.get() # you can guarantee that the value passed the is_valid_domain check
print("Domain is {}".format(domain))