Python 3 Snippets
int
i = 123
str
s = ''
s = str(200) + ' calories'
len('ABCD') # 4
name = 'John'
age = 8
s = f'{name} is {age} years old.'
s = f'{age:03d}' # 008
if 'apple' == 'apple':
print('Same')
dict
d = {"JAN": 1, "FEB": 2, "MAR": 3}
d["JAN"] # 1
list
d = []
d = [1, 2, 3]
d.append(4)
d[-1] = 8 # last element
tuple
e = ('abcd', 123, 456, 'efgh')
e[0] # abcd
If Else
if a == 100 and b == 'banana':
#
elif row[0] in MONTHS:
#
else:
#
For Loop
ages = [1, 2, 3]
for age in ages:
print(age)
for idx, age in enumerate(ages):
if idx == 3:
continue
Function
def add(a, b):
return a + b
c = add(1, 2)
def aaa(amount=0, description=''):
date = date
SQLite
conn = sqlite3.connect('school.db')
c = conn.cursor()
s = [('Tom', 22), ('Bob', 33), ('Sam', 44)]
c.executemany('''INSERT INTO students(name,age)
VALUES (?,?)''', s)
conn.commit()
conn.close()
CSV (Excel)
a = []
with open('list.csv', newline='') as csvfile:
# Skip first line
next(csvfile)
reader = csv.reader(csvfile)
for row in reader:
a.append([row[0], row[1]])
Unix Timestamp
import time
timestamp = time.time()
Date
from datetime import date
d = date(2020, 12, 31)
d.isoformat() # '2020-12-31'
d.year # 2020
d.month # 12
Class
class Apple:
def __init__(self, weight=100):
self.weight = weight
def __repr__(self):
return 'Weight: ' + str(self.weight)
a = Apple()
a.weight # 100
print(a) # Weight: 100
'Apple: ' + str(a) # 'Apple: Weight: 100'
Shell (cmd)
import subprocess
subprocess.run('ping 127.0.0.1', shell=True)
subprocess.run('"C:\\Program Files\\test.exe" -i abc',
shell=True)