SHARE
TWEET

walrus_operator_1

DeaD_EyE Oct 20th, 2019 99 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Walrus Operator in Python 3.8
  2. # Look this video
  3. # https://www.youtube.com/watch?v=-Rh4XW89VlQ
  4.  
  5. # The walrus operator is not used to get as many statements on one line
  6. # It's used to prevent calling functions twice or more.
  7.  
  8.  
  9. request = {'from': {'username': 'Andre', 'password': input('Please something: ')}}
  10. db = []
  11.  
  12.  
  13. def process_from(request):
  14.     """
  15.    Example function
  16.    """
  17.     password = request['from']['password']
  18.     # here we ask for the len of password
  19.     if len(password) > 5:
  20.         db.append(password)
  21.         return 'Added user!'
  22.     else:
  23.         # here we're doing it again
  24.         return f'Password is too short! The provided Password is only {len(password)} chars long'
  25.  
  26.  
  27. def process_from_pre38(request):
  28.     """
  29.    Working example for Python <= 3.7
  30.    """
  31.     password = request['from']['password']
  32.     # get the length of password one time
  33.     length = len(password)
  34.     if length > 5: # use length here
  35.         db.append(password)
  36.         return 'Added user!'
  37.     else:
  38.         # and here
  39.         return f'Password is too short! The provided Password is only {length} chars long'
  40.  
  41.  
  42. def process_from_walrus(request):
  43.     """
  44.    Same walrus operator
  45.    Requires Python 3.8
  46.    """
  47.     password = request['from']['password']
  48.  
  49.     if (length := len(password)) > 5:
  50.         db.append(password)
  51.         return 'Added user!'
  52.     else:
  53.         return f'Password is too short! The provided Password is only {length} chars long'
  54.  
  55.  
  56.  
  57. print(process_from(request))
  58. print(process_from_pre38(request))
  59. print(process_from_walrus(request))
  60. print(db)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top