ClearCode

7tips

May 12th, 2022
1,343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # match case -> simplified if statement
  2. a = 2
  3. if a == 0: print('0')
  4. elif a == 1: print('1')
  5. elif a == 2: print('2')
  6. elif a == 3: print('3')
  7.  
  8. match a:
  9.     case 0: print('0')
  10.     case 1: print('1')
  11.     case 2: print('2')
  12.     case 3: print('3')
  13.  
  14. # ternary operator / single line if statement
  15. day_time = False
  16. greet = 'hello' if day_time else 'goodbye'
  17. print(f"Somthing basic: {'hello' if day_time else 'goodbye'}")
  18.  
  19. # chain comparisons
  20. min_value = 5
  21. max_value = 10
  22. value = 7
  23.  
  24. #if min_value < value and max_value > value:
  25. if min_value < value < max_value:
  26.     print('value inside boundaries')
  27.  
  28. # clamp some values between a minimum and a maximum
  29. min_value = 0
  30. max_value = 100
  31. value = 50
  32.  
  33. while True:
  34.     value += 0.001
  35.     # value never exceeds maximum value
  36.     # if value > max_value:
  37.     #   value = max_value
  38.     # if value < min_value:
  39.     #   value = min_value
  40.     value = max(min_value,min(value,max_value))
  41.     print(value)
  42.  
  43. # eval + exec
  44. test_string = 'hello'
  45. print(eval('test_string.upper()'))
  46. print(exec('test_string = "updated"'))
  47. print(test_string)
  48.  
  49. for operation in ['upper', 'lower', 'casefold', 'title']:
  50.     print(eval(f'test_string.{operation}()'))
  51.  
  52. # print(test_string.upper())
  53. # print(test_string.lower())
  54. # print(test_string.casefold())
  55. # print(test_string.title())
  56.  
  57. # dict.get
  58. test_dict = {'a': 1, 'b': 2, 'c' : 3}
  59. if test_dict.get('a'):
  60.     print(test_dict.get('a'))
  61.  
  62. # list flattening with sum()
  63. test_list = [[1, 2, 3], [4, 5, 6, 7], [8 , 9]]
  64. print(sum(test_list,[]))
Advertisement
Add Comment
Please, Sign In to add comment