x = 5
print("Hello, World!")
# Comment
'''Comment'''
"Hello"
42
3.14
True
or False
[1, 2, 3]
(1, 2, 3)
{1, 2, 3}
{"key": "value"}
+, -, *, /, //, %, **
==, !=, <, >, <=, >=
and, or, not
in, not in
is, is not
if x > y:
elif x < y:
else:
for x in range(5):
while x < 5:
break
continue
def my_function():
my_function()
def func(x, y=0):
def func(*args, **kwargs):
class MyClass:
def __init__(self):
def method(self):
class_var = 0
my_object = MyClass()
class DerivedClass(BaseClass):
def method(self):
try:
except Exception as e:
raise ValueError("Error message")
finally:
import numpy
import numpy as np
from math import pi
with open("file.txt", "r") as file:
file.read()
with open("file.txt", "w") as file:
with open("file.txt", "a") as file:
[expression for item in iterable if condition]
lambda arguments: expression
iter(obj)
next(iterator)
def my_generator(): yield value
(expression for item in iterable if condition)
class MyContext:
def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
with MyContext() as my_context:
len(obj)
→ Length of objectsum(iterable[, start])
→ Sum of elementsmax(iterable[, key])
→ Maximum elementmin(iterable[, key])
→ Minimum elementsorted(iterable[, key][, reverse])
→ Sorted listrange(stop[, start][, step])
→ Sequence of numberszip(*iterables)
→ Iterator of tuplesmap(function, iterable)
→ Apply function to all itemsfilter(function, iterable)
→ Filter elements by functionisinstance(obj, classinfo)
→ Check object’s classlower()
→ Lowercaseupper()
→ Uppercasestrip([chars])
→ Remove leading/trailing characterssplit([sep][, maxsplit])
→ Split by separatorreplace(old, new[, count])
→ Replace substringfind(sub[, start][, end])
→ Find substring indexformat(*args, **kwargs)
→ Format stringappend(item)
→ Add item to endextend(iterable)
→ Add elements of iterableinsert(index, item)
→ Insert item at indexremove(item)
→ Remove first occurrencepop([index])
→ Remove & return itemindex(item[, start][, end])
→ Find item indexcount(item)
→ Count occurrencessort([key][, reverse])
→ Sort listreverse()
→ Reverse listkeys()
→ View list of keysvalues()
→ View list of valuesitems()
→ View key-value pairsget(key[, default])
→ Get value for keyupdate([other])
→ Update dictionarypop(key[, default])
→ Remove & return valueclear()
→ Remove all itemsadd(item)
→ Add itemupdate(iterable)
→ Add elements of iterablediscard(item)
→ Remove item if presentremove(item)
→ Remove item or raise KeyErrorpop()
→ Remove & return itemclear()
→ Remove all itemsunion(*others)
→ Union of setsintersection(*others)
→ Intersection of setsdifference(*others)
→ Difference of setsissubset(other)
→ Check if subsetissuperset(other)
→ Check if supersetimport re
re.search(pattern, string)
re.match(pattern, string)
re.findall(pattern, string)
re.sub(pattern, repl, string)
\d
: Digit\w
: Word character\s
: Whitespace.
: Any character (except newline)^
: Start of string$
: End of string*
: Zero or more repetitions+
: One or more repetitions?
: Zero or one repetition{n}
: Exactly n repetitions{n,}
: At least n repetitions{,m}
: At most m repetitions{n,m}
: Between n and m repetitions (inclusive)def my_decorator(func):
@my_decorator
import my_module
__init__.py
from my_package import my_module
python -m venv myenv
myenv\Scripts\activate
source myenv/bin/activate
deactivate
pip install package_name
pip uninstall package_name
pip install --upgrade package_name
pip list
pip show package_name
import datetime
datetime.datetime.now()
datetime.date(year, month, day)
datetime.time(hour, minute, second, microsecond)
datetime.datetime.strftime(format)
datetime.datetime.strptime(date_string, format)
%Y
, %m
, %d
, %H
, %M
, %S
import json
json.loads(json_string)
json.dumps(obj)
json.load(file)
json.dump(obj, file)
import threading
t = threading.Thread(target=function, args=(arg1, arg2))
t.start()
t.join()
import multiprocessing
p = multiprocessing.Process(target=function, args=(arg1, ##arg2))
p.start()
p.join()
import sqlite3
conn = sqlite3.connect('mydb.sqlite')
cursor = conn.cursor()
cursor.execute("CREATE TABLE my_table (id INTEGER, name TEXT)")
conn.commit()
cursor.fetchall()
conn.close()
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content,'html.parser')
soup.find_all('tag_name')
element['attribute_name']
element.text
import requests
response = requests.get(url)
response = requests.post(url, data=payload)
response.content
response.json()
response.status_code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
import tensorflow as tf
from tensorflow import keras
import torch
import argparse
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('--arg_name', type=str,help='Description of the argument')
args = parser.parse_args()
args.arg_name
import logging
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug()
, logging.info()
, logging.warning()
, logging.error()
, logging.critical()
import os
os.environ.get('VAR_NAME')
os.environ['VAR_NAME'] = 'value'
def my_function(param: int, optional_param: Optional[str] = None) -> List[int]:
my_variable: Dict[str, int] = {}