Homepage / Notes / Computer Science / Programming Languages / Python
'hello'
hello
1 + 1
2
for i in range(1, 5):
print(i)
1
2
3
4
**2 for x in range(5)] [x
[0, 1, 4, 9, 16]
for x in range(10) if x % 2 == 0] [x
[0, 2, 4, 6, 8]
Docs: https://docs.python.org/3/tutorial/classes.html
Most basic example:
class MyClass:
"""A simple example class"""
= 12345
i
def f(self):
return 'hello world'
About __init()__
:
>>> class Complex:
def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
...>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
3.0, -4.5) (
Hint to the programmer that it is for internal use only. Not enforced in any way.
"Name mangling".
>>> class Test:
def __mangled_name(self):
... pass
... def normal_name(self):
... pass
...
...>>> t = Test()
>>> [attr for attr in dir(t) if "name" in attr]
'_Test__mangled_name', 'normal_name'] [
To avoid naming conflicts, for example class_
.
Reserved for spcial use like __init__
.
By convention, used as a temporary variable name.
Typing
Docs: https://docs.python.org/3/library/typing.html
Not enforced in any way, only there to help.
Takes a string, outputs a string:
def greeting(name: str) -> str:
return 'Hello ' + name
Introduced in Python 3.10
def string_age(age):
match age:
case x if x < 6:
return "User is very young"
case x if 6 <= x < 18:
return "User is a minor"
case x if 18 <= x < 65:
return "User is an adult"
case x if 65 <= x:
return "User is probably retired"
print(string_age(2))
print(string_age(12))
print(string_age(22))
print(string_age(90))
User is very young
User is a minor
User is an adult
User is probably retired
from itertools import repeat
return list(repeat('A', 3))
A | A | A |
from itertools import combinations
return list(combinations('ABC', 2))
A | B |
A | C |
B | C |
from itertools import permutations
return list(permutations('ABC', 2))
A | B |
A | C |
B | A |
B | C |
C | A |
C | B |
from itertools import batched
return list(batched(['green', 'blue', 'red', 'yellow', 'black', 'pink'], 2))
Scientific Computing
NumPy's main object if the multidimensional array, called ndarray
. Different from standard Python array
, which only handles one-dimensional arrays. Dimensions are called axes.
pip3 install numpy
import numpy as np
= np.arange(15).reshape(3, 5)
a print(a)
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
print(a.shape)
(3, 5)
print(a.ndim)
2
print(a.size)
15
You can create an array from a regular Python list
= np.array([1, 2, 3, 4])
b print(b)
[1 2 3 4]
Or zeros / ones
print(np.zeros((3, 4)))
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
print(np.ones((2, 3, 4)))
[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]
= np.array([100, 100, 100])
a = np.array([10, 20, 30])
b print(a - b)
[90 80 70]
print(b*2)
[20 40 60]
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool
pip3 install pandas
Basic object of pandas
is the DataFrame. A DataFrame is made of rows and columns, like a spreadsheet. Each column in a DataFrame is a Series.
import pandas as pd
= pd.DataFrame(
df
{"Name": [
"Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",
],"Age": [22, 35, 58],
"Sex": ["male", "male", "female"],
}
)
print(df)
Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
Selecting a single Series
print(df["Age"])
0 22
1 35
2 58
Name: Age, dtype: int64
print(df["Age"].max())
58
print(df["Age"].describe())
count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
50% 35.000000
75% 46.500000
max 58.000000
Name: Age, dtype: float64
https://github.com/gruns/icecream
Never use print() to debug again.
https://arrow.readthedocs.io/en/latest/
Better dates & times for Python
https://github.com/willmcgugan/rich
Rich is a Python library for rich text and beautiful formatting in the terminal.
https://facebookresearch.github.io/Kats/
One stop shop for time series analysis in Python
https://github.com/unit8co/darts
A Python library for easy manipulation and forecasting of time series.
Numba makes Python code fast
Numba is an open source JIT compiler that translates a subset of Python and NumPy code into fast machine code.
https://github.com/pyscript/pyscript
PyScript is a Pythonic alternative to Scratch, JSFiddle, and other "easy to use" programming frameworks, with the goal of making the web a friendly, hackable place where anyone can author interesting and interactive applications.
https://textual.textualize.io/
Textual is a framework for building applications that run within your terminal. Text User Interfaces (TUIs) have a number of advantages over web and desktop apps.
An open source dataframe library that works with any data system
https://www.mattlayman.com/blog/2024/layman-guide-python-built-in-functions/
by Dan Bader