# Becoming Pythonic # Variables # Python x = 7 y = 3 z = x + y # 10 # Pythonic x,y = 7,3 z = x + y # Sorting without a sort() or reverse() # Python a = 10 b = 5 ## print a,b 10,5 print(a,b) ## asserting 5,10 temp = a # original value of a in temp temp = 10 a = b # assign the current value of b as a a = 5 b = temp # assing the current value of temp as b b = 10 # a = 5, temp = 10, b = 10 print(a,b) # 5,10 # Pythonic a,b = 10,5 print(a,b) a,b = b,a print(a,b) # List Comprehension # Python ## Create an empty list in memory n = [] ## Append elements to the list for x in range(10): n.append(x) x + 1 print(n) # Pythonic # Create the list, append the elements then object in memory n = [x + 1 for x in range(10)] # no append() print(n) # Dictionary Comprehension # Collection names = ["Bob", "Joe", "Mary"] # { fname: Bob} # Python ## Create an empty dict in memory name_lengths = {} ## Loop thru the list and assign values for name in names: name_lengths[name] = len(name) print(name_lengths) fname_names = [] # empty list for name in names: fname_name = {'fname': name} fname_names.append(fname_name) print(fname_names) # [ {k:v}, {k:v}, {k:v} ] # Pythonic name_lengths = { name: len(name) for name in names } print(name_lengths) fname_names = [{'fname': name} for name in names] print(fname_names) # [ {k:v}, {k:v}, {k:v} ] # Same rules apply to tuple () and set {} # Python ## Create the empty collection () {} ## then loop # Pythonic # Compress the local var and the loop into the collection # {condition for x in ys loop} # tuple you have to do it as a list then cast to tuple # Tuple Casting due to immutable properties ccInfo = () print(type(ccInfo)) # tuple print(ccInfo) # prints an empty tuple # Populate a list !set t_ccInfo = ('4111 5255 4521 4152', '12/25', '523') print(t_ccInfo) # Convert to list and update position 2 def updateCVC(): t_ccInfo = ('4111 5255 4521 4152', '12/25', '523') new_cvc = input("CVC Code invalid, please enter a valid 3 digit code: ") l_ccInfo = list(t_ccInfo) l_ccInfo[2] = new_cvc # assertion print(l_ccInfo) # GC Class both none or del keyword #l_ccInfo = None # unassigned variable #del l_ccInfo # dispose() t_ccInfo = tuple(l_ccInfo) # tuple return t_ccInfo # print(updateCVC()) # Custom Iterables to improve or make pythonic the for x in ys loop # Python ## Using the iterable() for the in keyword inside the object class NonPythonicIterable: # __init__ iterate() def __init__(self, max): self.max = max # 3 defined interator def iterate(self): num = 0 # control while num < self.max: # condition while 0 < 3 yield num num += 1 # increment working with function() # num + 1 # addition operator working with variable # create an instance of the class and use the iterate() iterator = NonPythonicIterable(3) for num in iterator.iterate(): print(num) # Pythonic ## Use the interable() for the in as Property __next__ on the class class PythonicIterable: # __init__ iterate() __next__ # move control from iterate() to __init__ def __init__(self, max): self.max = max self.num = 0 # use the built in Property __iter__ instead of a function() / iterate() def __iter__(self): return self # handle the return # def __next__ Property to handle the condition def __next__(self): if self.num < self.max: num = self.num self.num += 1 # increment instead of addition operator + return num raise StopIteration # ys is coming from __next__ iterator = PythonicIterable(3) for num in iterator: print(num) # Regular Expression import re # test email patterns emails = ["philipm@onlc.com", "www.onlc.com", "philip.matusiak@gmail.comm", "bob123@hotmail.us"] # Python use the if keyword def validate_email(email): if re.match(r"^[a-zA-Z0-9_.]+@[a-zA-Z0-9]+?\.[a-zA-Z]{2,3}$", email): return True else: return False for email in emails: if validate_email(email): print(f"{email} is a valid email address.") else: print(f"{email} is an invalid email address.") # Pythonic use the bool() to replace the if pattern lamba to replace the if in the for loop def is_valid_email(email): return bool(re.match(r"^[a-zA-Z0-9_.]+@[a-zA-Z0-9]+?\.[a-zA-Z]{2,3}$", email)) for email in emails: print(f"{email} is {'a valid' if is_valid_email(email) else 'not a valid'} email address.") # ternary operator or lambda