🖍️
Developer Note
  • Welcome
  • Git
    • Eslint & Prettier & Stylelint & Husky
  • Programming Language
    • JavaScript
      • Script Async vs Defer
      • Module
      • Const VS Let VS Var
      • Promise
      • Event Loop
      • Execution Context
      • Hoisting
      • Closure
      • Event Buddling and Capturing
      • Garbage Collection
      • This
      • Routing
      • Debounce and Throttle
      • Web Component
      • Iterator
      • Syntax
      • String
      • Array
      • Object
      • Proxy & Reflect
      • ProtoType
      • Class
      • Immutability
      • Typeof & Instanceof
      • Npm (Node package manager)
    • TypeScript
      • Utility Type
      • Type vs Interface
      • Any vs Unknown vs Never
      • Void and undefined
      • Strict Mode
      • Namespace
      • Enum
      • Module
      • Generic
    • Python
      • Local Development
      • Uv
      • Asyncio & Event loop
      • Context Manager
      • Iterator & Generator
      • Fast API
      • Pydantic & Data Class
    • Java
      • Compilation and Execution
      • Data Type
      • Enumeration
      • Data Structure
      • Try Catch
      • InputStream and OutputStream
      • Concurrent
      • Unicode Block
      • Build Tools
      • Servlet
      • Java 8
  • Coding Pattern
    • MVC vs MVVM
    • OOP vs Functional
    • Error Handling
    • MVC vs Flux
    • Imperative vs Declarative
    • Design Pattern
  • Web Communication
    • REST API
      • Web Hook
      • CORS issue
    • HTTPS
    • GraphQL
      • REST API vs GraphQL
      • Implementation (NodeJS + React)
    • Server-Sent Event
    • Web Socket
    • IP
    • Domain Name System (DNS)
  • Frontend
    • Progressive Web App (PWA)
    • Single Page & Multiple Page Application
    • Search Engine Optimiaztion (SEO)
    • Web bundling & Micro-frontend
      • Webpack
        • Using Webpack to build React Application
        • Using Webpack to build react library
      • Vite
      • Using rollup to build react library
      • Implementing micro frontend
    • Web Security
      • CSRF & Nonce
      • XSS
      • Click hijacking
    • Cypress
    • CSS
      • Core
        • Box Model
        • Inline vs Block
        • Flexbox & Grid
        • Pseudo Class
        • Position
      • Tailwind CSS
        • Shadcn
      • CSS In JS
        • Material UI
    • React
      • Core
        • Component Pattern
        • React Lazy & Suspense
        • React Portal
        • Error Boundary
        • Rendering Methods
        • Environment Variable
        • Conditional CSS
        • Memo
        • Forward Reference
        • High Order Component (HOC) & Custom Hook
        • TypeScript
      • State Management
        • Redux
        • Recoil
        • Zustand
      • Routing
        • React Router Dom
      • Data Fetching
        • Axios & Hook
        • React Query
        • Orval
      • Table
        • React Table
      • Form & Validation
        • React Hook Form
        • Zod
      • NextJS
        • Page Router
        • App Router
      • React Native
    • Angular
    • Svelte
      • Svelte Kit
  • Backend
    • Cache
      • Browser Cache
      • Web Browser Storage
      • Proxy
      • Redis
    • Rate limit
    • Monitoring
      • Logging
      • Distributed Tracing
    • Load Test
    • Encryption
    • Authentication
      • Password Protection
      • Cookie & Session
      • JSON Web Token
      • SSO
        • OAuth 2.0
        • OpenID Connect (OIDC)
        • SAML
    • Payment
      • Pre-built
      • Custom
    • File Handling
      • Upload & Download (Front-end)
      • Stream & Buffer
    • Microservice
      • API Gateway
      • Service Discovery
      • Load Balancer
      • Circuit Breaker
      • Message Broker
      • BulkHead & Zipkin
    • Elastic Search
    • Database
      • SQL
        • Group By vs Distinct
        • Index
        • N + 1 problem
        • Normalization
        • Foreign Key
        • Relationship
        • Union & Join
        • User Defined Type
      • NOSQL (MongoDB)
      • Transaction
      • Sharding
      • Lock (Concurrency Control)
    • NodeJS
      • NodeJS vs Java Spring
      • ExpressJS
      • NestJS
        • Swagger
        • Class Validator & Validation Pipe
        • Passport (Authentication)
      • Path Module
      • Database Connection
        • Integrating with MYSQL
        • Sequalize
        • Integrating with MongoDB
        • Prisma
        • MikroORM
        • Mongoose
      • Streaming
      • Worker Thread
      • Passport JS
      • JSON Web Token
      • Socket IO
      • Bull MQ
      • Pino (Logging)
      • Yeoman
    • Spring
      • Spring MVC
      • Spring REST
      • Spring Actuator
      • Aspect Oriented Programming (AOP)
      • Controller Advice
      • Filter
      • Interceptor
      • Concurrent
      • Spring Security
      • Spring Boot
      • Spring Cloud
        • Resilience 4j
      • Quartz vs Spring Batch
      • JPA and Hibernate
      • HATEOS
      • Swagger
      • Unit Test (Java Spring)
      • Unit Test (Spring boot)
  • DevOp
    • Docker
    • Kubernetes
      • Helm
    • Nginx
    • File System
    • Cloud
      • AWS
        • EC2 (Virtual Machine)
        • Network
        • IAM
          • Role-Service Binding
        • Database
        • Route 53
        • S3
        • Message Queue
        • Application Service
        • Serverless Framework
        • Data Analysis
        • Machine Learning
        • Monitoring
        • Security
      • Azure
        • Identity
        • Compute Resource
        • Networking
        • Storage
        • Monitoring
      • Google Cloud
        • IAM
          • Workload Identity Federation
        • Compute Engine
        • VPC Network
        • Storage
        • Kubernetes Engine
        • App Engine
        • Cloud function
        • Cloud Run
        • Infra as Code
        • Pub/Sub
    • Deployment Strategy
    • Jenkins
    • Examples
      • Deploy NextJS on GCP
      • Deploy Spring on Azure
      • Deploy React on Azure
  • Domain Knowledge
    • Web 3
      • Blockchain
      • Cryptocurrency
    • AI
      • Prompt
      • Chain & Agent
      • LangChain
      • Chunking
      • Search
      • Side Products
Powered by GitBook
On this page
  • Data Types
  • String
  • Logical
  • Boolean
  • List
  • Tuple
  • Set
  • Dictionaries
  • Function
  • Lambda
  • Class

Was this helpful?

  1. Programming Language

Python

Data Types

Text Type:

str

Numeric Types:

int, float, complex

Sequence Types:

list, tuple, range

Mapping Type:

dict

Set Types:

set, frozenset

Boolean Type:

bool

Binary Types:

bytes, bytearray, memoryview

None Type:

NoneType

x = 5
# Check the typing and get the type
print(type(x), isInstance(x, str))

String

  • F-String was introduced in Python 3.6, which can be used to concatenate the string and variable

age = 36
txt = f"My name is John, I am {age}"
print(txt)

Logical

  • and : &&

  • or: ||

  • not: !

a = True
b = False
if not b:
    print("b is false ar")
if a or b:
    print("a or b is true")
if a and b:
    print("a and b are true")

# Result
# b is false ar
# a or b is true
  • is vs ==

  • is is more strict than ==, as it also validate the object reference

x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)

# returns False because z is the same object as x

print(x is y)

# returns True because x is not the same object as y, even if they have the same content

print(x == y)

# to demonstrate the difference betweeen "is not" and "!=": this comparison returns False because x is equal to y


# Result
# True
# False
# True

Boolean

  • (), [], {}, "" , 0 , None , will equal to false

a = {}
if a:
    print("Yeah")
else:
    print("Nope")

# result: Nope

List

thislist = ["apple", "banana", "cherry"]
# cherry
print(thislist[-1])
# ['cherry', 'orange', 'kiwi']
print(thislist[2:5])
# add the element on the specific position
thislist.insert(2, "watermelon")
# append the element to the last position
thislist.add("lemon") 
# pop the element on specific position, if arg is none, pop the last element
thislist.pop(1)
# Looping 
thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)
  
# Join List
list1 = ["a"]
list2 = [1]
list3 = list1 + list2
print(list3)
# ["a", 1]
  • List Comprehension is similar with map method on javascript, having syntax sugar to create new array from a array

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
# ['apple', 'banana', 'mango']


fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)
# ['apple', 'orange', 'cherry', 'kiwi', 'mango']


def add(x:int):
    return x + 1
arr = [1 ,2 ,3 ,4 ,5]
arr2 = [ y for item in arr if (y:=add(item)) <=3]
print(arr2)
# [2,3]
thislist = ["apple", "banana", "cherry"]
# Create new list with different reference
mylist = thislist.copy()
print(thislist is mylist)

# Same reference
yourlist = thislist
print(thislist is yourlist)

# Result
# False
# True

Tuple

  • A tuple is a collection which is ordered and unchangeable.

mytuple = ("apple", "banana", "cherry")

Set

  • A set is a collection which is unordered, unchangeable*, and unindexed

myset = {"apple", "banana", "cherry"}

Dictionaries

  • Dictionaries which is similar with json object from javascript, containing key-value pair

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

# Loop the key
# brand , model, year
for x in thisdict:
  print(x)

# Ford
print(thisdict["brand"])

# Will crash, don't try to access non-existing key
print(thisdict["brands"])

# Check the key is existed
# False
print("brands" in thisdict)

# Directly add or edit attribute
thisdict["year"] = 2018
# remove attribute 
thisdict.pop("model")

# convert string to dictionaries
newobj = json.loads('{ "name":"John", "age":30, "city":"New York"}')
# stringify the dictionaries
newStr = json.dumps(thisdict)

Function

  • Here is the example of closure

def test():
    def test2():
        return "test"
    return test2

# Result
# test
print(test()())
  • In function , you can assign a default value to function argument, but need to take care of list, dict, as they are mutable and have unexpected behaviors

class Test:
    def fn(
        self,
        param:list = []
    ):
        param.append(1);
        print(param);
test = Test();
test2 = Test();
test.fn()
test2.fn()

// Output:
// [1]
// [1, 1]
  • From above the result, since the default parameter is mutable, so the value is accumulated

  • Here is the fix below, by setting default parameter as None

class Test:
    def fn(
        self,
        param:list = None
    ):
        param = [] if param is None else param
        param.append(1);
        print(param);
test = Test();
test2 = Test();
test.fn()
test2.fn()

// Output:
// [1]
// [1]

Lambda

  • lambda function is a small anonymous function with a simple return value

def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)

# Result: 22
print(mydoubler(11))

Class

# In the class declarification, self must included, self is equal to this
class Person:
  # init which equal to constructor function
  def __init__(self, name, age):
    self.name = name
    self.age = age
  # To customize tthe format when accessing the class instance directly
  def __str__(self):
    return f"{self.name}({self.age})"

p1 = Person("John", 36)

# John
print(p1.name)
# John(36)
print(p1)
PreviousGenericNextLocal Development

Last updated 1 month ago

Was this helpful?