Thanks for contribution 🤗:
https://github.com/ShixiangWang/iLearning/blob/master/study/Python/learnPython/搞定Python基本操作.ipynb https://github.com/rajathkmp/Python-Lectures/blob/master/03.ipynb https://jupyter.org/try-jupyter/lab/index.html?fromURL=https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynb https://github.com/jamwine/Python-Beginners-Guide/blob/master/Learn%20Python%20in%20Jupyter%20Notebook.ipynb https://github.com/cs231n/cs231n.github.io/blob/master/python-colab.ipynb
for i in {2..6}; do printf " [🦄](https://jupyter.org/try-jupyter/lab/index.html?fromURL=https://gist.githubusercontent.com/duangsuse/519411ab618ee57350ee2df93d33f58e/raw/$i.ipynb)"; done
open a link above, CtrlV, ShiftEnter to run code below.
# <3 Python is REALLY simple, differ from MOST popular languages eg. Java C PHP Ruby
# 💯 CtrlL https://hellogithub.com/en/report/tiobe
# No "$" or "-" for var_x/defX/ClassX Names, no ^[0-9] at start.
# indentation & case sensitive, use Tab / Shift+Tab / ?var for docs
["It's not from TOML.io !"]
name = "Alice" # String
age = 30 # Integer, 10//3 is 3
usdt = 19.99 # Float (USE 1999 FOR BALANCE)
is_active = True # use with if bool(x):
hex2 = 0xdeadbeef # int, 0xHex format
prices = {"Apple": 1.99, "Banana": 0.99}
fruits = ["Apple", "Banana", "Cherry"]
top1_fruit = fruits[i:=0] # try i in range(0, < 3), or row[0:3] slice (supports -1=len()-1)
Compose statement literal containing API callgraph(': block' s) & vartree(GC values), reuse app functions with def(vars):
subprocess.getoutput
n=3 3 3
Hello 5
typed 5
world 5
[('Hello', 5), ('typed', 5), ('world', 5)] [('Hello', 5), ('typed', 5), ('world', 5)]
list(kv)=['Hello', 'typed', 'world']
kv={}
kv['Hello'] = 5
kv['typed'] = 5
kv['world'] = 5
two十(3)=5 666
two十(3)=5 669
More
# for(n=0, i=0;i<3;i+=1) n+=i
n = 0
for i in (rn := range(0, 3)):
n += i
print(f"{n=}", sum(i + 0 for i in range(0, 3)), sum(rn))
words = "Hello typed world ".split(" ")
stdo = []
for w in words:
if w != "":
print(w, len(w))
for w in words:
stdo.append((w, len(w))) if w != "" else None
print(stdo, kv := [(u, len(u)) for u in words], end="\n" * 2)
"deleteMe" or kv.pop(-1) # , retWhenNone
kv = dict(kv) # vartype shadowing
print(f"{list(kv)=}") # = [*kv]
"duck🦆" or kv.pop("typed")
print("kv={}") # 👎 C-style boilerplates
for col in kv.items():
k, v = map(repr, col) # json-compat literal_eval?
if "explicit":
k, v = (repr(u) for u in col)
print(f"kv[{k}] = {v}")
def make_十(n):
return lambda x: x + n
two十 = make_十(2)
print(f"{two十(3)=}", two十(664))
from argparse import Namespace
def cell_十(n=0): # constructor(var n)
def javaSAM(step):
nonlocal n # 👍 Py: no let-var style declarations, no (this.n)
n += step
return n
return Namespace(inc=javaSAM)
two十 = cell_十(2).inc
print(f"{two十(3)=}", two十(664))
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print("Negative changed to zero")
elif x == 0:
print("Zero")
elif x == 1:
print("Single")
else:
print("More")
# Let's extract the input(stdin.line),
# and make print a 'callback' by return(str) to sys callstack
def numKind(num):
match num:
case 0: it = "Zero"
case 1: it = "Single"
case x if x < 0:
it = f"Negative ({x})"
case _: it = "Normal"
return it
# it = match num: or "match num as it" are unsupported.
def tryInt(s: "123"):
try:
return int(s)
except:
return None
while "REPL":
n = tryInt(input("integer: ").strip())
if not n and n != 0:
break
# ^ Oops, NaN means 'invalid input', (0) ALSO DOES? so could nan be Falsey? .: bool(math.nan)
print(numKind(n))import io, pandas as pd
import matplotlib.pyplot as plt
STORE = """csv
Apple,Banana,Cherry
1,2,3
1.99,0.99,2
"""
# module_KV, class, def/arg:Type, (lambda nonlocalVars, codetree..) are ALL DICT AND 'k=v's in Python3.
for k in globals():
if not all(c.isupper() for c in k):
continue # if /^[A-Z]+$/: replaceIt() # tool regex101.com
ext, mem = eval(f"{k}").split("\n", 1) # v with(globalThis) of module.py
exec(f"{k} = pd.read_{ext}(io.StringIO(mem))")
def main():
df = STORE
aapl_sales = df[df["Apple"] > 1]
all = df.sum()
# df.to_excel("out_store.xlsx", index=False)
display(*vars().keys())
display(*vars().values())
df["Sale"] = df["Apple"] + df["Banana"]
df["Sale"].plot(kind="line")
plt.title("Units Sold Over Time")
plt.show()
main()#def With(u, f): call eg. With(Box(1), lambda x: x.As(x.v+1)), too long
def With(u):
def PipeBy(f): f(u); return u
return PipeBy
@With({})
def js(u):
u['A'] = 1
print(js) # Yeah, @decorator are just fncall. cout<< are operator<<(call), printf() are syscall(write,fd=0)
# They're FAKE SYNTAX, but idioms are not constant.
from dataclasses import dataclass, field
def data(T):
'Trick: create vartree containers w/o def __init__ or call([],{})'
{setattr(T, k, field(default_factory=v if isFn else v.copy)) for k,v in T.__annotations__.items() if (isFn:=callable(v))or hasattr(v,'copy')}
return dataclass(T)
@data
class UserQueue:
id: list
usd: dict
def onBuy(u, id):
u.id.append(id)
u.usd[id]=100
def _repr_markdown_(u):
get_ipython().__class__.__name__
#^ https://ipython.readthedocs.io/en/stable/config/integrating.html
return "".join(f"- [{me}]() **\\${u.usd[me]/100}**\n" for me in u.id)
@With(UserQueue())
def uq(u):
[u.onBuy(id) for id in "Amy Jack Rose".split()]
u.usd['Jack']=10_000
display(uq)
# got tired of `def try$Int` templates?
# cool @decorator to convert raise ValueError() to None
def tryFill(op, v0=None):
def safe(*a, **kw):
try: return op(*a, **kw)
except: return (v0(a[0]) if callable(v0) else v0)
return safe
@tryFill
def faulty(x):
if x: raise x
return x
if "": # edit, re-run!
@tryFill
def faulty(a):
try:
for x in a: raise x
except TypeError: pass
tryFill(int)('abc'), tryFill(int, len)('abc')4 major IO demo: EchoArgs, Counter, Checklist_DDL, SplitJoinWalk
first one (async Flask + cookie):
#sudo setcap 'cap_net_bind_service=+pie' /usr/bin/python3.*
from fastapi import FastAPI, Request
from fastapi.responses import Response
from uvicorn import run as bun
from pydantic import BaseModel, Field
I = FastAPI()
if "real world":
@I.get("/login")
async def setJsGlobal():
# Create response with login message
rpc = Response("Login successful. Session address set.")
# Set session cookie with 1-day expiration
rpc.set_cookie(
key="USER",
value="objectID", # In production, use a hash(random+salt) token
max_age=dur,
expires=dur,
path="/", # Cookie available for HOST/*
secure=False, # Set to True in production with HTTPS
httponly=True, # Prevent XSS attacks
samesite="lax", # Prevent CSRF with modern browsers
)
return rpc
class Blog(BaseModel):
"try connect DB"
id: int = Field(None, description="TBD, eg. UUID, auto-increment")
slug: str = Field(min_length=4, max_length=15)
html: str = Field(min_length=1, max_length=3000) # no optional, age range
# @I.get("/{path:path}")
async def echo(path: str, u: Request):
output = [
f"curl $I/{path}",
f"location.search: {u.query_params}",
"Body: None (call PUT for write)\n\n",
f"Client IP: {u.client.host}",
]
auth(output, u)
output.append("kwargs = {")
for key, value in u.headers.items(): # try shorten!
output.append(f" {key} = {value}, ")
output.append("}\n")
return Response(content="\n".join(output), media_type="text/plain")
superFn = echo
@I.get("/{path}") # dont GET /
async def echo(
path: str,
q: str = "",
p: int = 1,
sort: str = "-1create_at",
per_page: int = 100,
u: Request = None,
):
curs = (p - 1) * per_page
res = await superFn(path, u) # middleware are just "override fun" or pipes
return Response(
f"db.filter({q})[{curs}:{curs + per_page}].sort_({sort})\n".encode() + res.body
)
@I.post("/{path}")
async def echo(path: str, u: Request): # orderBy created, [0 1 2..]
output = [
"",
f"location.search: {u.query_params}",
f"Client IP: {u.client.host}",
]
auth(output, u) # try sort output!
(output.append)("kwargs:")
for key, value in u.headers.items(): # try shorten!
output.append(f" {key}: {value}")
body = await u.body()
output.append(f"\nBody ({len(body)} bytes/octects):")
output.append(crud := body.decode("utf-8", errors="ignore"))
output[0] = f"curl $I/{path} -d@'-' <<<{repr(crud)}"
return Response(content="\n".join(output), media_type="text/plain")
if __name__ == "__main__":
dur = 10 or 86400 # 24 hours in seconds
foreign = {
"objectID": f"Proxy.revocable(SQL_pointer,{dur}s)",
None: "readonly, no-REST",
}
auth = lambda ln, u: ln.append(
f"SK_ *(&api): {foreign.get(u.cookies.get('USER', None), 'expired')}"
)
bun(I, host="0.0.0.0", port=8080)
if "fetch() fail":
see = "https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware"
see = "https://jsonplaceholder.typicode.com/"
if "f-string and let-match were not born" or "ES6 = uglify JS":
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(host='localhost', port=8080)