SIGN IN SIGN UP
Fechin / reference UNCLAIMED

⭕ Share quick reference cheat sheet for developers.

0 0 1 EJS
2020-12-25 09:55:10 +08:00
---
title: Python
date: 2020-12-23 18:41:20
2021-12-15 10:48:31 +08:00
background: bg-[#436b97]
2020-12-25 09:55:10 +08:00
tags:
- script
- interpret
2020-12-25 09:55:10 +08:00
categories:
- Programming
2020-12-25 09:55:10 +08:00
intro: |
The [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.
2023-03-06 16:19:19 +08:00
plugins:
- copyCode
2025-01-01 20:05:18 +02:00
- runCode
2020-12-25 09:55:10 +08:00
---
## Getting Started
2020-12-25 09:55:10 +08:00
### Introduction
- [Python](https://www.python.org/) _(python.org)_
- [Python Document](https://docs.python.org/3/index.html) _(docs.python.org)_
2020-12-25 09:55:10 +08:00
- [Learn X in Y minutes](https://learnxinyminutes.com/docs/python/) _(learnxinyminutes.com)_
2023-06-15 10:44:51 +08:00
- [Regex in python](/regex#regex-in-python) _(cheatsheets.zip)_
2020-12-25 09:55:10 +08:00
### Hello World
```python
>>> print("Hello, World!")
Hello, World!
```
The famous "Hello World" program in Python
### Variables
2020-12-25 09:55:10 +08:00
```python
2021-12-15 20:07:49 +08:00
age = 18 # age is of type int
name = "John" # name is now of type str
print(name)
2020-12-25 09:55:10 +08:00
```
Python can't declare a variable without assignment.
2020-12-25 09:55:10 +08:00
### Data Types {.row-span-2}
2021-09-14 13:03:55 +08:00
| | |
| ---------------------------------- | -------- |
2021-09-14 13:03:55 +08:00
| `str` | Text |
| `int`, `float`, `complex` | Numeric |
2020-12-25 09:55:10 +08:00
| `list`, `tuple`, `range` | Sequence |
2021-09-14 13:03:55 +08:00
| `dict` | Mapping |
| `set`, `frozenset` | Set |
| `bool` | Boolean |
| `bytes`, `bytearray`, `memoryview` | Binary |
2020-12-25 09:55:10 +08:00
See: [Data Types](#python-built-in-data-types)
2020-12-25 09:55:10 +08:00
### Slicing String
```python
2021-12-15 20:07:49 +08:00
>>> msg = "Hello, World!"
>>> print(msg[2:5])
2020-12-25 09:55:10 +08:00
llo
```
2021-12-15 20:16:34 +08:00
See: [Strings](#python-strings)
2020-12-25 09:55:10 +08:00
### Lists
2020-12-25 09:55:10 +08:00
```python
mylist = []
mylist.append(1)
mylist.append(2)
2021-12-15 20:07:49 +08:00
for item in mylist:
print(item) # prints out 1,2
2020-12-25 09:55:10 +08:00
```
2021-12-15 20:16:34 +08:00
See: [Lists](#python-lists)
2020-12-25 09:55:10 +08:00
### If Else
2020-12-25 09:55:10 +08:00
```python
2021-12-15 20:07:49 +08:00
num = 200
if num > 0:
print("num is greater than 0")
2020-12-25 09:55:10 +08:00
else:
2021-12-15 20:07:49 +08:00
print("num is not greater than 0")
2020-12-25 09:55:10 +08:00
```
2021-12-15 20:16:34 +08:00
See: [Flow control](#python-flow-control)
2020-12-25 09:55:10 +08:00
### Loops
2020-12-25 09:55:10 +08:00
```python
2021-12-15 20:07:49 +08:00
for item in range(6):
if item == 3: break
print(item)
2020-12-25 09:55:10 +08:00
else:
2021-02-10 10:03:06 +08:00
print("Finally finished!")
2020-12-25 09:55:10 +08:00
```
See: [Loops](#python-loops)
2020-12-25 09:55:10 +08:00
### Functions
2020-12-25 09:55:10 +08:00
```python
>>> def my_function():
2021-02-10 10:07:39 +08:00
... print("Hello from a function")
2020-12-25 09:55:10 +08:00
...
>>> my_function()
Hello from a function
```
2021-12-15 20:16:34 +08:00
See: [Functions](#python-functions)
2020-12-25 09:55:10 +08:00
### File Handling {.col-span-2}
2020-12-25 09:55:10 +08:00
```python
with open("myfile.txt", "r", encoding='utf8') as file:
2021-12-15 20:07:49 +08:00
for line in file:
print(line)
2020-12-25 09:55:10 +08:00
```
2021-12-15 20:16:34 +08:00
See: [File Handling](#python-file-handling)
2020-12-25 09:55:10 +08:00
### Arithmetic
2020-12-25 09:55:10 +08:00
```python
result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5 # => 250
result = 16 / 4 # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2 # => 1
result = 5 ** 3 # => 125
```
The `/` means quotient of x and y, and the `//` means floored quotient of x and y, also see
[StackOverflow](https://stackoverflow.com/a/183870/13192320)
2020-12-25 09:55:10 +08:00
### Plus-Equals
2020-12-25 09:55:10 +08:00
```python
counter = 0
counter += 10 # => 10
counter = 0
counter = counter + 10 # => 10
message = "Part 1."
2021-12-15 19:55:02 +08:00
2020-12-25 09:55:10 +08:00
# => Part 1.Part 2.
message += "Part 2."
2020-12-25 09:55:10 +08:00
```
2021-12-15 19:55:02 +08:00
### f-Strings (Python 3.6+)
2021-12-15 19:55:02 +08:00
```python
2024-07-17 11:36:52 +08:00
>>> website = 'cheatsheets.zip'
2021-12-15 19:55:02 +08:00
>>> f"Hello, {website}"
2024-07-17 11:36:52 +08:00
"Hello, cheatsheets.zip"
2021-12-15 19:55:02 +08:00
>>> num = 10
2021-12-15 19:55:02 +08:00
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
```
2020-12-25 09:55:10 +08:00
See: [Python F-Strings](#python-f-strings-since-python-3-6)
2020-12-25 09:55:10 +08:00
## Python Built-in Data Types
2020-12-25 09:55:10 +08:00
### Strings
```python
2021-12-15 20:07:49 +08:00
hello = "Hello World"
hello = 'Hello World'
2020-12-25 09:55:10 +08:00
2021-12-15 20:07:49 +08:00
multi_string = """Multiline Strings
2020-12-25 09:55:10 +08:00
Lorem ipsum dolor sit amet,
consectetur adipiscing elit """
```
See: [Strings](#python-strings)
2020-12-25 09:55:10 +08:00
### Numbers
2020-12-25 09:55:10 +08:00
```python
x = 1 # int
y = 2.8 # float
z = 1j # complex
>>> print(type(x))
<class 'int'>
```
### Booleans
2020-12-25 09:55:10 +08:00
```python
my_bool = True
2021-12-15 20:07:49 +08:00
my_bool = False
2020-12-25 09:55:10 +08:00
bool(0) # => False
bool(1) # => True
```
### Lists
2020-12-25 09:55:10 +08:00
```python
list1 = ["apple", "banana", "cherry"]
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))
```
See: [Lists](#python-lists)
2020-12-25 09:55:10 +08:00
### Tuple
2020-12-25 09:55:10 +08:00
```python
2021-12-15 20:07:49 +08:00
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
2025-04-30 14:16:54 -03:00
tupla = (1, 2, 3, 'python')
print(tupla[0]) # Output: 1
print(tupla.count(1)) # Count occurrences
print(tupla.index(2)) # Find index
tupla1 = (1, 2, 3)
tupla2 = ('a', 'b')
len(tuple) Returns the number of elements.
in Checks if an element exists in the tuple.
Concatenation (+) Combines two tuples.
Repetition (*) Repeats a tuple.
Slicing (tuple[start:end]) Extracts a subtuple.
print(len(tupla1)) # Output: 3
print(2 in tupla1) # Output: True
print(tupla1 + tupla2) # Output: (1, 2, 3, 'a', 'b')
print(tupla1[1:]) # Output: (2, 3)
# unpacking
a, b, c, d = tupla # Each value goes into a variable
2020-12-25 09:55:10 +08:00
```
Similar to List but immutable
2020-12-25 09:55:10 +08:00
### Set
2020-12-25 09:55:10 +08:00
```python
set1 = {"a", "b", "c"}
2020-12-25 09:55:10 +08:00
set2 = set(("a", "b", "c"))
```
Set of unique items/objects
2020-12-25 09:55:10 +08:00
### Dictionary
2021-02-10 10:03:06 +08:00
```python {.wrap}
2020-12-25 09:55:10 +08:00
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
2021-02-10 10:03:06 +08:00
>>> a.update({"four": 4})
2020-12-25 09:55:10 +08:00
>>> a.keys()
2021-02-10 10:03:06 +08:00
dict_keys(['one', 'two', 'three', 'four'])
2020-12-25 09:55:10 +08:00
>>> a['four']
4
```
Key: Value pair, JSON like object
2020-12-25 09:55:10 +08:00
### Casting
#### Integers
2020-12-25 09:55:10 +08:00
```python
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
```
#### Floats
2020-12-25 09:55:10 +08:00
```python
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
```
#### Strings
2020-12-25 09:55:10 +08:00
```python
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
```
## Python Advanced Data Types
### Heaps {.col-span-2 .row-span-3}
```python
import heapq
myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # turn myList into a Min Heap
2022-11-22 11:35:10 +08:00
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap
heapq.heappush(myList, 10) # insert 10
2022-11-22 11:35:10 +08:00
x = heapq.heappop(myList) # pop and return smallest item
print(x) # => 1
```
#### Negate all values to use Min Heap as Max Heap
```python
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # multiply by -1 to negate
heapq.heapify(myList)
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)
```
Heaps are binary trees for which every parent node has a value less than or equal to any of its children. Useful for
accessing min/max value quickly. Time complexity: O(n) for heapify, O(log n) push and pop. See:
[Heapq](https://docs.python.org/3/library/heapq.html)
### Stacks and Queues {.row-span-3}
```python
from collections import deque
2022-11-22 11:35:10 +08:00
q = deque() # empty
q = deque([1, 2, 3]) # with values
2022-11-22 11:35:10 +08:00
q.append(4) # append to right side
q.appendleft(0) # append to left side
2022-11-22 11:35:10 +08:00
print(q) # => deque([0, 1, 2, 3, 4])
x = q.pop() # remove & return from right
y = q.popleft() # remove & return from left
2022-11-22 11:35:10 +08:00
print(x) # => 4
print(y) # => 0
print(q) # => deque([1, 2, 3])
q.rotate(1) # rotate 1 step to the right
2022-11-22 11:35:10 +08:00
print(q) # => deque([3, 1, 2])
```
2020-12-25 09:55:10 +08:00
Deque is a double-ended queue with O(1) time for append/pop operations from both sides. Used as stacks and queues. See:
[Deque](https://docs.python.org/3/library/collections.html#collections.deque)
2020-12-25 09:55:10 +08:00
## Python Strings
2020-12-25 09:55:10 +08:00
### Array-like
```python
2021-12-15 20:07:49 +08:00
>>> hello = "Hello, World"
>>> print(hello[1])
2020-12-25 09:55:10 +08:00
e
2021-12-15 20:16:34 +08:00
>>> print(hello[-1])
2020-12-25 09:55:10 +08:00
d
```
2021-12-15 20:16:34 +08:00
Get the character at position 1 or last
2020-12-25 09:55:10 +08:00
### Looping
```python
2021-12-15 20:16:34 +08:00
>>> for char in "foo":
2021-12-15 20:07:49 +08:00
... print(char)
2021-12-15 20:16:34 +08:00
f
o
o
2020-12-25 09:55:10 +08:00
```
Loop through the letters in the word "foo"
2020-12-25 09:55:10 +08:00
### Slicing string {.row-span-4}
2021-04-20 17:44:59 +08:00
```java
2021-04-20 17:43:03 +08:00
┌───┬───┬───┬───┬───┬───┬───┐
2020-12-25 09:55:10 +08:00
| m | y | b | a | c | o | n |
2021-04-20 17:43:03 +08:00
└───┴───┴───┴───┴───┴───┴───┘
2020-12-25 09:55:10 +08:00
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
```
---
2021-02-18 11:25:39 +08:00
```python
2020-12-25 09:55:10 +08:00
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
```
```python
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
```
```python
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
```
#### With a stride
2020-12-25 09:55:10 +08:00
```python
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
```
### String Length
```python
2021-12-15 20:07:49 +08:00
>>> hello = "Hello, World!"
>>> print(len(hello))
2020-12-25 09:55:10 +08:00
13
```
The len() function returns the length of a string
2020-12-25 09:55:10 +08:00
### Multiple copies
2020-12-25 09:55:10 +08:00
```python
>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'
```
### Check String
```python
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True
```
### Concatenates
2020-12-25 09:55:10 +08:00
```python
>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'
```
### Formatting {.col-span-2}
2020-12-25 09:55:10 +08:00
```python
name = "John"
print("Hello, %s!" % name)
```
```python
name = "John"
age = 23
print("%s is %d years old." % (name, age))
```
#### format() Method
2020-12-25 09:55:10 +08:00
```python
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
2020-12-25 09:55:10 +08:00
```
### Input
2021-02-18 11:25:39 +08:00
```python
2020-12-25 09:55:10 +08:00
>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'
```
Get input data from console
2020-12-25 09:55:10 +08:00
### Join
2020-12-25 09:55:10 +08:00
```python
>>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'
```
### Endswith
2020-12-25 09:55:10 +08:00
```python
>>> "Hello, world!".endswith("!")
True
```
## Python F-Strings (Since Python 3.6+)
2021-12-15 19:55:02 +08:00
### f-Strings usage
2021-12-15 19:55:02 +08:00
```python
2024-07-17 11:36:52 +08:00
>>> website = 'cheatsheets.zip'
2021-12-15 19:55:02 +08:00
>>> f"Hello, {website}"
2024-07-17 11:36:52 +08:00
"Hello, cheatsheets.zip"
2021-12-15 19:55:02 +08:00
>>> num = 10
2021-12-15 19:55:02 +08:00
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
>>> f"""He said {"I'm John"}"""
"He said I'm John"
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
>>> name = 'Eric'
>>> age = 27
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
```
it is available since Python 3.6, also see:
[Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)
2021-12-15 19:55:02 +08:00
### f-Strings Fill Align
2021-12-15 19:55:02 +08:00
```python
>>> f'{"text":10}' # [width]
'text '
>>> f'{"test":*>10}' # fill left
'******test'
>>> f'{"test":*<10}' # fill right
'test******'
>>> f'{"test":*^10}' # fill center
'***test***'
>>> f'{12345:0>10}' # fill with numbers
'0000012345'
```
### f-Strings Type
2021-12-15 19:55:02 +08:00
```python
>>> f'{10:b}' # binary type
'1010'
>>> f'{10:o}' # octal type
'12'
>>> f'{200:x}' # hexadecimal type
'c8'
>>> f'{200:X}'
'C8'
>>> f'{345600000000:e}' # scientific notation
'3.456000e+11'
>>> f'{65:c}' # character type
'A'
>>> f'{10:#b}' # [type] with notation (base)
'0b1010'
>>> f'{10:#o}'
'0o12'
>>> f'{10:#x}'
'0xa'
```
### F-Strings Others
2021-12-15 19:55:02 +08:00
```python
>>> f'{-12345:0=10}' # negative numbers
'-000012345'
>>> f'{12345:010}' # [0] shortcut (no align)
'0000012345'
>>> f'{-12345:010}'
'-000012345'
>>> import math # [.precision]
>>> math.pi
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # [grouping_option]
'1,000,000.00'
>>> f'{1000000:_.2f}'
'1_000_000.00'
>>> f'{0.25:0%}' # percentage
'25.000000%'
>>> f'{0.25:.0%}'
'25%'
```
### F-Strings Sign
2021-12-15 19:55:02 +08:00
```python
>>> f'{12345:+}' # [sign] (+/-)
'+12345'
>>> f'{-12345:+}'
'-12345'
>>> f'{-12345:+10}'
' -12345'
>>> f'{-12345:+010}'
'-000012345'
```
2020-12-25 09:55:10 +08:00
## Python Lists
2020-12-25 09:55:10 +08:00
### Defining
2020-12-25 09:55:10 +08:00
```python
>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
### Generate {.col-span-2}
2020-12-25 09:55:10 +08:00
```python
>>> list(filter(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x ** 2 for x in range (1, 11) if x % 2 == 1]
[1, 9, 25, 49, 81]
>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]
>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[6, 7]
```
### Append
2020-12-25 09:55:10 +08:00
```python
>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]
```
### List Slicing {.col-span-2 .row-span-3}
2020-12-25 09:55:10 +08:00
Syntax of list slicing:
2020-12-25 09:55:10 +08:00
```python
a_list[start:end]
a_list[start:end:step]
```
2020-12-25 09:55:10 +08:00
#### Slicing
2020-12-25 09:55:10 +08:00
```python
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[2:5]
['bacon', 'tomato', 'ham']
>>> a[-5:-2]
['egg', 'bacon', 'tomato']
>>> a[1:4]
['egg', 'bacon', 'tomato']
```
2020-12-25 09:55:10 +08:00
#### Omitting index
2020-12-25 09:55:10 +08:00
```python
>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
```
2020-12-25 09:55:10 +08:00
#### With a stride
2020-12-25 09:55:10 +08:00
```python
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0:6:2]
['spam', 'bacon', 'ham']
>>> a[1:6:2]
['egg', 'tomato', 'lobster']
>>> a[6:0:-2]
['lobster', 'tomato', 'egg']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
```
### Remove
2020-12-25 09:55:10 +08:00
```python
>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']
```
### Access
2020-12-25 09:55:10 +08:00
```python
>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
```
### Concatenating {.row-span-2}
2020-12-25 09:55:10 +08:00
```python
>>> odd = [1, 3, 5]
>>> odd.extend([9, 11, 13])
>>> odd
[1, 3, 5, 9, 11, 13]
>>> odd = [1, 3, 5]
>>> odd + [9, 11, 13]
[1, 3, 5, 9, 11, 13]
```
### Sort & Reverse {.row-span-2}
2020-12-25 09:55:10 +08:00
```python
>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]
```
### Count
2020-12-25 09:55:10 +08:00
```python
>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2
```
### Repeating
2020-12-25 09:55:10 +08:00
```python
>>> li = ["re"] * 3
>>> li
['re', 're', 're']
```
## Python Flow control
2020-12-25 09:55:10 +08:00
### Basic
2020-12-25 09:55:10 +08:00
```python
2021-12-15 20:07:49 +08:00
num = 5
if num > 10:
print("num is totally bigger than 10.")
elif num < 10:
print("num is smaller than 10.")
2020-12-25 09:55:10 +08:00
else:
2021-12-15 20:07:49 +08:00
print("num is indeed 10.")
2020-12-25 09:55:10 +08:00
```
### One line (ternary operator)
2020-12-25 09:55:10 +08:00
```python
>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a
```
### else if
```python
value = True
if not value:
2021-02-10 10:03:06 +08:00
print("Value is False")
2020-12-25 09:55:10 +08:00
elif value is None:
2021-02-10 10:03:06 +08:00
print("Value is None")
2020-12-25 09:55:10 +08:00
else:
2021-02-10 10:03:06 +08:00
print("Value is True")
2020-12-25 09:55:10 +08:00
```
### match case
```python
x = 1
match x:
case 0:
print("zero")
case 1:
print("one")
case _:
print("multiple")
```
## Python Loops
2020-12-25 09:55:10 +08:00
### Basic
```python
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
```
Prints: 2 3 5 7
2020-12-25 09:55:10 +08:00
### With index
```python
animals = ["dog", "cat", "mouse"]
2022-11-22 11:35:10 +08:00
# enumerate() adds counter to an iterable
2020-12-25 09:55:10 +08:00
for i, value in enumerate(animals):
print(i, value)
```
Prints: 0 dog 1 cat 2 mouse
2020-12-25 09:55:10 +08:00
### While
2020-12-25 09:55:10 +08:00
```python
x = 0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1
```
Prints: 0 1 2 3
2022-11-22 11:35:10 +08:00
### Break
2020-12-25 09:55:10 +08:00
```python
x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)
```
Prints: 0 10 20 30 40
2020-12-25 09:55:10 +08:00
### Continue
```python
for index in range(3, 8):
2020-12-25 09:55:10 +08:00
x = index * 10
if index == 5:
continue
print(x)
```
Prints: 30 40 60 70
2020-12-25 09:55:10 +08:00
### Range
2020-12-25 09:55:10 +08:00
```python
for i in range(4):
print(i) # Prints: 0 1 2 3
for i in range(4, 8):
print(i) # Prints: 4 5 6 7
for i in range(4, 10, 2):
print(i) # Prints: 4 6 8
```
2020-12-25 11:59:54 +08:00
### With zip()
2020-12-25 11:59:54 +08:00
```python
2022-11-22 11:35:10 +08:00
words = ['Mon', 'Tue', 'Wed']
nums = [1, 2, 3]
# Use zip to pack into a tuple list
for w, n in zip(words, nums):
print('%d:%s, ' %(n, w))
2020-12-25 11:59:54 +08:00
```
2022-11-22 11:35:10 +08:00
Prints: 1:Mon, 2:Tue, 3:Wed,
2020-12-25 11:59:54 +08:00
2022-11-22 11:35:10 +08:00
### for/else
2020-12-25 11:59:54 +08:00
```python
2022-11-22 11:35:10 +08:00
nums = [60, 70, 30, 110, 90]
for n in nums:
if n > 100:
print("%d is bigger than 100" %n)
break
else:
print("Not found!")
2020-12-25 11:59:54 +08:00
```
2020-12-25 09:55:10 +08:00
Also see: [Python Tips](https://book.pythontips.com/en/latest/for_-_else.html)
2020-12-25 09:55:10 +08:00
### Over Dictionary
```python
johndict = {
"firstname": "John",
"lastname": "Doe",
"age": 30
}
x = johndict.items()
print(x)
# Output: dict_items([('firstname', 'John'),
# ('lastname', 'Doe'),
# ('age', 30)])
for key, value in johndict.items():
print(f"{key} : : {value}")
# Output: firstname : : John
# Output: lastname : : Doe
# Output: age : : 30
```
2025-06-17 17:25:58 +02:00
## Python Comprehensions
### Comprehension List {.col-span-2}
```python
languages = ["html", "go", "rust", "javascript", "python"]
newlist = [x for x in languages if "l" not in x]
# add language for language in languages if "l" not in language
print(newlist) #Output : [ 'go', 'rust', 'javascript', 'python']
# List comprehension avoid this :
2025-06-17 17:25:58 +02:00
oldlist = []
for x in languages:
if "l" not in x:
oldlist.append(x)
print(oldlist) #Output : [ 'go', 'rust', 'javascript', 'python']
```
### Comprehension Dictionary {.col-span-2}
```python
languages = ["html", "go", "rust", "javascript", "python"]
language_dict = {lang: ('l' not in lang) for lang in languages}
# Key is the language & bool is Value (no offense for html..)
print(language_dict)
# Output: {'html': False, 'go': True, 'rust': True,
# 'javascript': True, 'python': True}
# Dictionary comprehension avoid this :
2025-06-17 17:25:58 +02:00
language_dict2 = {}
2025-06-17 17:25:58 +02:00
for e in languages:
if "l" not in e:
language_dict2[e] = True
else:
language_dict2[e] = False
print(language_dict2)
# Output: {'html': False, 'go': True, 'rust': True,
# 'javascript': True, 'python': True}
```
## Python Functions
2020-12-25 09:55:10 +08:00
### Basic
```python
def hello_world():
2020-12-25 09:55:10 +08:00
print('Hello, World!')
```
### Return
```python
def add(x, y):
print("x is %s, y is %s" %(x, y))
return x + y
add(5, 6) # => 11
```
### Positional arguments
2020-12-25 09:55:10 +08:00
```python
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
```
2023-07-01 23:43:44 +08:00
Type of "args" is tuple.
2020-12-25 09:55:10 +08:00
### Keyword arguments
2020-12-25 09:55:10 +08:00
```python
def keyword_args(**kwargs):
return kwargs
# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness")
```
2023-07-01 23:43:44 +08:00
Type of "kwargs" is dict.
2020-12-25 09:55:10 +08:00
### Returning multiple
2020-12-25 09:55:10 +08:00
```python
def swap(x, y):
return y, x
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
```
### Default Value
2020-12-25 09:55:10 +08:00
```python
def add(x, y=10):
return x + y
add(5) # => 15
add(5, 20) # => 25
```
### Anonymous functions
2020-12-25 09:55:10 +08:00
```python
# => True
(lambda x: x > 2)(3)
2021-02-10 10:03:06 +08:00
# => 5
2020-12-25 09:55:10 +08:00
(lambda x, y: x ** 2 + y ** 2)(2, 1)
```
2025-06-17 17:28:55 +02:00
### @decorator {.col-span-2}
2020-12-25 09:55:10 +08:00
2025-06-17 17:28:55 +02:00
```python
# Modify or extend behavior of function or class method,
# without changing their actual code.
# Define decorator that will wrap function or method
def handle_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return print(f"Error : {e}")
return wrapper
# Decorate function or method
2025-06-17 17:28:55 +02:00
@handle_errors
def divide(a, b):
return a / b
divide(10, 0) # Output : Error : division by zero
```
## Python Modules
2020-12-25 09:55:10 +08:00
### Import modules
2020-12-25 09:55:10 +08:00
```python
import math
print(math.sqrt(16)) # => 4.0
```
### From a module
```python
from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
```
### Import all
```python
from math import *
```
### Shorten module
2020-12-25 09:55:10 +08:00
```python
import math as m
# => True
math.sqrt(16) == m.sqrt(16)
```
### Functions and attributes
```python
import math
dir(math)
```
## Python File Handling
2020-12-25 09:55:10 +08:00
### Read file
2020-12-25 09:55:10 +08:00
#### Line by line
2020-12-25 09:55:10 +08:00
```python
with open("myfile.txt") as file:
for line in file:
print(line)
```
2020-12-25 09:55:10 +08:00
#### With line number
2020-12-25 09:55:10 +08:00
```python
file = open('myfile.txt', 'r')
for i, line in enumerate(file, start=1):
2020-12-25 09:55:10 +08:00
print("Number %s: %s" % (i, line))
```
### String
#### Write a string
2020-12-25 09:55:10 +08:00
```python
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
file.write(str(contents))
```
#### Read a string
2020-12-25 09:55:10 +08:00
```python
with open('myfile1.txt', "r+") as file:
contents = file.read()
print(contents)
```
### Object
#### Write an object
2020-12-25 09:55:10 +08:00
```python
contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents))
```
#### Read an object
2020-12-25 09:55:10 +08:00
```python
with open('myfile2.txt', "r+") as file:
contents = json.load(file)
print(contents)
```
### Delete a File
```python
import os
os.remove("myfile.txt")
```
### Check and Delete
```python
import os
if os.path.exists("myfile.txt"):
2021-02-10 10:03:06 +08:00
os.remove("myfile.txt")
2020-12-25 09:55:10 +08:00
else:
2021-02-10 10:03:06 +08:00
print("The file does not exist")
2020-12-25 09:55:10 +08:00
```
### Delete Folder
```python
import os
os.rmdir("myfolder")
```
## Python Classes & Inheritance
2020-12-25 09:55:10 +08:00
### Defining
```python
class MyNewClass:
pass
# Class Instantiation
my = MyNewClass()
```
### Constructors
```python
class Animal:
2021-02-10 10:03:06 +08:00
def __init__(self, voice):
self.voice = voice
2020-12-25 09:55:10 +08:00
cat = Animal('Meow')
print(cat.voice) # => Meow
dog = Animal('Woof')
2020-12-25 09:55:10 +08:00
print(dog.voice) # => Woof
```
### Method
2020-12-25 09:55:10 +08:00
```python
class Dog:
2021-02-10 10:03:06 +08:00
# Method of the class
def bark(self):
print("Ham-Ham")
2020-12-25 09:55:10 +08:00
charlie = Dog()
charlie.bark() # => "Ham-Ham"
```
### Class Variables {.row-span-2}
2020-12-25 09:55:10 +08:00
```python
class MyClass:
2021-02-10 10:03:06 +08:00
class_variable = "A class variable!"
2020-12-25 09:55:10 +08:00
# => A class variable!
print(MyClass.class_variable)
2020-12-25 09:55:10 +08:00
x = MyClass()
2020-12-25 09:55:10 +08:00
# => A class variable!
print(x.class_variable)
2020-12-25 09:55:10 +08:00
```
### Super() Function {.row-span-2}
```python
class ParentClass:
2021-02-10 10:03:06 +08:00
def print_test(self):
print("Parent Method")
2020-12-25 09:55:10 +08:00
class ChildClass(ParentClass):
2021-02-10 10:03:06 +08:00
def print_test(self):
print("Child Method")
# Calls the parent's print_test()
super().print_test()
```
---
2020-12-25 09:55:10 +08:00
```python
>>> child_instance = ChildClass()
>>> child_instance.print_test()
Child Method
Parent Method
```
### repr() method
```python
class Employee:
2021-02-10 10:03:06 +08:00
def __init__(self, name):
self.name = name
2021-02-10 10:03:06 +08:00
def __repr__(self):
return self.name
2020-12-25 09:55:10 +08:00
john = Employee('John')
print(john) # => John
```
### User-defined exceptions
2020-12-25 09:55:10 +08:00
```python
class CustomError(Exception):
2021-02-10 10:03:06 +08:00
pass
2020-12-25 09:55:10 +08:00
```
### Polymorphism
```python
class ParentClass:
2021-02-10 10:03:06 +08:00
def print_self(self):
print('A')
2020-12-25 09:55:10 +08:00
class ChildClass(ParentClass):
2021-02-10 10:03:06 +08:00
def print_self(self):
print('B')
2020-12-25 09:55:10 +08:00
obj_A = ParentClass()
obj_B = ChildClass()
2021-06-04 17:20:40 +08:00
obj_A.print_self() # => A
obj_B.print_self() # => B
2020-12-25 09:55:10 +08:00
```
### Overriding
2020-12-25 09:55:10 +08:00
```python
class ParentClass:
2021-02-10 10:03:06 +08:00
def print_self(self):
print("Parent")
2020-12-25 09:55:10 +08:00
class ChildClass(ParentClass):
2021-02-10 10:03:06 +08:00
def print_self(self):
print("Child")
2020-12-25 09:55:10 +08:00
child_instance = ChildClass()
child_instance.print_self() # => Child
```
### Inheritance
2020-12-25 09:55:10 +08:00
```python
class Animal:
2021-02-10 10:03:06 +08:00
def __init__(self, name, legs):
self.name = name
self.legs = legs
2020-12-25 09:55:10 +08:00
class Dog(Animal):
2021-02-10 10:03:06 +08:00
def sound(self):
print("Woof!")
2020-12-25 09:55:10 +08:00
Yoki = Dog("Yoki", 4)
2021-06-04 17:20:40 +08:00
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
2020-12-25 09:55:10 +08:00
```
### @staticmethod {.col-span-2}
```python
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# No instantiation nedded
# Call via class
print(MyClass.greet("Alice")) # => Hello, Alice!
# Can still call via instance
obj = MyClass()
print(obj.greet("Bob")) # => Hello, Bob!
```
## Python Type Hints (Since Python 3.5)
2023-07-01 23:43:44 +08:00
### Variable & Parameter
2023-07-01 23:43:44 +08:00
```python
string: str = "ha"
times: int = 3
# wrong hit, but run correctly
result: str = 1 + 2
print(result) # => 3
def say(name: str, start: str = "Hi"):
return start + ", " + name
print(say("Python")) # => Hi, Python
2023-07-01 23:43:44 +08:00
```
### Built-in date type
2023-07-01 23:43:44 +08:00
```python
from typing import Dict, Tuple, List
2023-07-01 23:43:44 +08:00
bill: Dict[str, float] = {
"apple": 3.14,
"watermelon": 15.92,
"pineapple": 6.53,
}
completed: Tuple[str] = ("DONE",)
succeeded: Tuple[int, str] = (1, "SUCCESS")
statuses: Tuple[str, ...] = (
"DONE", "SUCCESS", "FAILED", "ERROR",
)
codes: List[int] = (0, 1, -1, -2)
2023-07-01 23:43:44 +08:00
```
### Built-in date type (3.10+)
2023-07-01 23:43:44 +08:00
```python
bill: dict[str, float] = {
"apple": 3.14,
"watermelon": 15.92,
"pineapple": 6.53,
}
completed: tuple[str] = ("DONE",)
succeeded: tuple[int, str] = (1, "SUCCESS")
statuses: tuple[str, ...] = (
"DONE", "SUCCESS", "FAILED", "ERROR",
)
codes: list[int] = (0, 1, -1, -2)
2023-07-01 23:43:44 +08:00
```
### Positional argument
2023-07-01 23:43:44 +08:00
```python
def calc_summary(*args: int):
return sum(args)
print(calc_summary(3, 1, 4)) # => 8
```
2023-07-02 00:24:06 +08:00
Indicate all arguments' type is int.
2023-07-01 23:43:44 +08:00
### Returned
2023-07-01 23:43:44 +08:00
```python
def say_hello(name) -> str:
return "Hello, " + name
var = "Python"
print(say_hello(var)) # => Hello, Python
```
### Union returned
2023-07-01 23:43:44 +08:00
```python
from typing import Union
def resp200(meaningful) -> Union[int, str]:
return "OK" if meaningful else 200
```
Means returned value type may be int or str.
### Keyword argument
2023-07-01 23:43:44 +08:00
```python
def calc_summary(**kwargs: int):
return sum(kwargs.values())
print(calc_summary(a=1, b=2)) # => 3
```
Indicate all parameters' value type is int.
### Multiple returns
2023-07-01 23:43:44 +08:00
```python
def resp200() -> (int, str):
return 200, "OK"
returns = resp200()
print(returns) # => (200, 'OK')
print(type(returns)) # tuple
2023-07-01 23:43:44 +08:00
```
### Union returned (3.10+)
2023-07-01 23:43:44 +08:00
```python
def resp200(meaningful) -> int | str:
return "OK" if meaningful else 200
```
Since Python 3.10
### Property
2023-07-01 23:43:44 +08:00
```python
class Employee:
name: str
age: int
def __init__(self, name, age):
self.name = name
self.age = age
self.graduated: bool = False
```
### Self instance
2023-07-01 23:43:44 +08:00
```python
class Employee:
name: str
def set_name(self, name) -> "Employee":
self.name = name
return self
def copy(self) -> 'Employee':
return type(self)(self.name)
2023-07-01 23:43:44 +08:00
```
### Self instance (3.11+)
2023-07-01 23:43:44 +08:00
```python
from typing import Self
class Employee:
name: str
age: int
def set_name(self: Self, name) -> Self:
self.name = name
return self
```
### Type & Generic {.col-span-2}
2023-07-01 23:43:44 +08:00
```python
from typing import TypeVar, Type
T = TypeVar("T")
# "mapper" is a type, like int, str, MyClass and so on.
# "default" is an instance of type T, such as 314, "string", MyClass() and so on.
2023-07-02 00:24:06 +08:00
# returned is an instance of type T too.
2023-07-01 23:43:44 +08:00
def converter(raw, mapper: Type[T], default: T) -> T:
try:
return mapper(raw)
except:
return default
2023-07-02 00:24:06 +08:00
raw: str = input("Enter an integer: ")
2023-07-01 23:43:44 +08:00
result: int = converter(raw, mapper=int, default=0)
```
### Function {.col-span-2}
2023-07-01 23:43:44 +08:00
```python
from typing import TypeVar, Callable, Any
T = TypeVar("T")
def converter(raw, mapper: Callable[[Any], T], default: T) -> T:
try:
return mapper(raw)
except:
return default
# Callable[[Any], ReturnType] means a function declare like:
# def func(arg: Any) -> ReturnType:
# pass
# Callable[[str, int], ReturnType] means a function declare like:
# def func(string: str, times: int) -> ReturnType:
# pass
# Callable[..., ReturnType] means a function declare like:
# def func(*args, **kwargs) -> ReturnType:
2023-07-02 00:38:31 +08:00
# pass
2023-07-01 23:43:44 +08:00
def is_success(value) -> bool:
return value in (0, "OK", True, "success")
resp = dict(code=0, message="OK", data=[])
successed: bool = converter(resp["message"], mapper=is_success, default=False)
2023-07-01 23:43:44 +08:00
```
## Python Operators
### Walrus {.col-span-2}
```python
values = [1, "text", True, "", 2]
i = 0
# It assigns a value to a variable and compares it in a boolean expression
while (data := values[i]):
print(data, end=",")
i = i + 1
# Expected result: 1, "text", True
```
## Date & Time Handling
### Current date and time
```python
import datetime
now = datetime.datetime.now()
print(now) # e.g., 2024-04-27 14:35:22.123456
```
### Creating specific date/time objects
```python
import datetime
# Create a date object
d = datetime.date(2024, 4, 27)
print(d) # 2024-04-27
# Create a time object
t = datetime.time(15, 30, 45)
print(t) # 15:30:45
# Create a datetime object
dt = datetime.datetime(2024, 4, 27, 15, 30, 45)
print(dt) # 2024-04-27 15:30:45
```
### Converting between date formats
```python
import datetime
# Convert a string to a datetime object
date_str = "2024-04-27 14:00"
dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M")
print(dt_obj) # 2024-04-27 14:00:00
# Convert a datetime object to a string
formatted_str = dt_obj.strftime("%d/%m/%Y %H:%M")
print(formatted_str) # 27/04/2024 14:00
```
### Timestamps and Unix time
```python
import datetime
# Get current timestamp
timestamp = datetime.datetime.now().timestamp()
print(timestamp) # e.g., 1714188922.123456
# Convert timestamp back to datetime
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp)
```
### Date difference and timedelta {.col-span-2}
```python
import datetime
date1 = datetime.date(2024, 4, 27)
date2 = datetime.date(2024, 5, 1)
delta = date2 - date1
print(delta.days) # 4
# Using timedelta for date arithmetic
new_date = date1 + datetime.timedelta(days=10)
print(new_date) # 2024-05-07
```
## Miscellaneous
2020-12-25 09:55:10 +08:00
### Comments
```python
# This is a single line comments.
```
```python
""" Multiline strings can be written
using three "s, and are often used
as documentation.
"""
```
2020-12-25 09:55:10 +08:00
```python
''' Multiline strings can be written
using three 's, and are often used
as documentation.
'''
```
### Generators
2020-12-25 09:55:10 +08:00
```python
def double_numbers(iterable):
for i in iterable:
yield i + i
```
Generators help you make lazy code.
### Generator to list
2020-12-25 09:55:10 +08:00
```python
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
# => [-1, -2, -3, -4, -5]
print(gen_to_list)
```
### Handle exceptions {.col-span-3}
2020-12-25 09:55:10 +08:00
```python
try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
2021-06-04 17:20:40 +08:00
finally: # Execute under all circumstances
2020-12-25 09:55:10 +08:00
print("We can clean up resources here")
```
### Dispatcher Pattern {.col-span-3}
```python
# Dispatcher allows dynamic selection and execution of functions based on user input or other runtime conditions
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return 'Error: Division by zero'
return x / y
# Dispatcher dictionary: maps operation names to their corresponding functions
operations = {
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
# Function to dispatch operation based on operation name
# Common use cases include executing different functions dynamically, such as in calculators, command interpreters, or event handling
def dispatcher(operation_name, x, y):
func = operations.get(operation_name)
if func:
return func(x, y)
else:
return f"Unknown operation: {operation_name}"
# Usage examples
print(dispatcher('add', 5, 3)) # Output: 8
print(dispatcher('multiply', 4, 2)) # Output: 8
print(dispatcher('divide', 10, 0)) # Output: Error: Division by zero
print(dispatcher('mod', 10, 3)) # Output: Unknown operation: mod
```