if __name__ == "__main__":
print("Hello, World!")
Methods #
String #
str(123)->'123'Convert to string' a b c '.strip()->'a b c'Remove leading and trailing whitespace'abc'.capitalize()->'Abc'Capitalize the first character of the string'ab bc cd'.title()->'Ab Bc Cd'Capitalize the first character of each word'a b c'.split('')->['a','b','c']Split the string into a list of substrings'abc'.startswith('a')->TrueCheck if the string starts with a specific substring'abc'.endswith('c')->TrueCheck if the string ends with a specific substring'abc'.find('b')->1Find the index of the first occurrence of a substring'abc'.rfind('b')->1Find the index of the last occurrence of a substring'abc'.count('a')->1Count the number of occurrences of a substring'abc'.replace('a', 'x')->'xbc'Replace a substring with another substring'abc'.upper()->'ABC'Convert the string to uppercase'abc'.lower()->'abc'Convert the string to lowercase'abc'.swapcase()->'ABC'Swap the case of each character in the string'abc'.isalpha()->TrueCheck if the string contains only alphabetic characters'abc123'.isalnum()->TrueCheck if the string contains only alphanumeric characters'abc'.isdigit()->FalseCheck if the string contains only digits'abc'.isupper()->FalseCheck if the string is in uppercase'abc'.islower()->TrueCheck if the string is in lowercase'abc'.isspace()->FalseCheck if the string contains only whitespace characters'abc'.isnumeric()->FalseCheck if the string contains only numeric characters
String Formatting #
f"{z:,}Format a number with commasf"{z:.2f}"Format a number with 2 decimal places
Integer #
int()Convert to integer
Float #
float()Convert to floatround()Round to the nearest integerround(x, 2)Round to 2 decimal places
Conditionals #
True if x > 0 else FalseTernary operator- Match statement (Python 3.10+):
match name: case "Harry" | "Hermione" | "Ron": print("Gryffindor") case "Draco": print("Slytherin") case _: print("Other")
Ranges #
range(10)Create a range from 0 to 9range(1, 11)Create a range from 1 to 10range(1, 11, 2)Create a range from 1 to 10 with a step of 2range(10, 0, -1)Create a range from 10 to 1 (inclusive of 10, exclusive of 0)
Lists #
list = [1, 2, 3]Create a listlist.append(4)Add an element to the end of the listlist.insert(0, 0)Insert an element at the beginning of the listlist.remove(2)Remove the first occurrence of an element from the listlist.pop()Remove and return the last element of the listlist.pop(0)Remove and return the first element of the listlist.sort()Sort the list in ascending orderlist.reverse()Reverse the order of the listlist.index(3)Get the index of the first occurrence of an element in the listlist.count(3)Count the number of occurrences of an element in the listlist[0]Access the first element of the listlist[-1]Access the last element of the listlist1 + list2Concatenate two listslist1 * 2Repeat the list twicelen(list)Get the length of the listlist1 == list2Check if two lists are equallist1 != list2Check if two lists are not equallist1 in list2Check if an element is in the listlist1 not in list2Check if an element is not in the listlist(range(10))Convert a range to a listlist(range(1, 11))Convert a range from 1 to 10 to a list
Slices #
list[start:end]Get a slice of the list from indexstarttoend(exclusive)list[start:end:step]Get a slice of the list from indexstarttoend(exclusive) with a step size ofsteplist[start:]Get a slice of the list from indexstartto the endlist[:end]Get a slice of the list from the beginning to indexend(exclusive)list[:]Get a copy of the entire listlist[::-1]Get a reversed copy of the listlist[::2]Get every second element of the listlist[-1]Access the last element of the listlist[-2]Access the second-to-last element of the listlist[-3:]Get the last three elements of the listlist[:-3]Get all elements of the list except the last threelist[1:5]Get a slice of the list from index 1 to 4 (inclusive of 1, exclusive of 5)list[1:5:2]Get a slice of the list from index 1 to 4 (inclusive of 1, exclusive of 5) with a step size of 2
Operator shorthands #
i = 0Initialize i to 0i = i + 1Increment i by 1i += 1Increment i by 1 (shorthand)i = i - 1Decrement i by 1i -= 1Decrement i by 1 (shorthand)i = i * 2Multiply i by 2i *= 2Multiply i by 2 (shorthand)i = i / 2Divide i by 2i /= 2Divide i by 2 (shorthand)i = i ** 2Square ii **= 2Square i (shorthand)i = i % 2Modulo i by 2i %= 2Modulo i by 2 (shorthand)
Loops #
for i in range(10):Loop from 0 to 9for i in range(1, 11):Loop from 1 to 10for i in range(1, 11, 2):Loop from 1 to 10 with step 2for i in range(10, 0, -1):Loop from 10 to 1for _ in range(10):Loop 10 times without using the loop variablefor item in [1,2,3]:Loop through each item in the list
while loops:
while x < 10:Loop while x is less than 10
Dict #
dict = {'a': 1, 'b': 2, 'c': 3}Create a dictionarydict['d'] = 4Add a key-value pair to the dictionarydict['a']Access the value associated with the key ‘a’dict.get('a')Access the value associated with the key ‘a’ (returns None if key does not exist)dict.keys()Get a list of keys in the dictionarydict.values()Get a list of values in the dictionarydict.items()Get a list of key-value pairs in the dictionarydict.pop('a')Remove and return the value associated with the key ‘a’dict.popitem()Remove and return the last key-value pair in the dictionarydict.update({'d': 4})Update the dictionary with a new key-value pairdict.clear()Remove all key-value pairs from the dictionarydict1 == dict2Check if two dictionaries are equaldict1 != dict2Check if two dictionaries are not equal
Exceptions #
try:
# code that may raise an exception
except Exception as e:
# handle the exception
else:
# code to execute if no exception was raised
finally:
# code to execute regardless of whether an exception was raised or not
raise Exception("Error message")Raise an exception with a custom error messageassert condition, "Error message"Assert that a condition is true, raise an exception with a custom error message if it is notpassDo nothing (used as a placeholder)
Importing #
import randomImport the random moduleimport random as rndImport the random module with an aliasfrom random import choiceImport the choice function from the random module
Core Libraries #
import randomImport the random libraryrandom.randint(1, 10)Generate a random integer between 1 and 10 (inclusive)random.random()Generate a random float between 0.0 and 1.0random.uniform(1, 10)Generate a random float between 1.0 and 10.0random.choice([1, 2, 3])Randomly select an element from a listrandom.sample([1, 2, 3], 2)Randomly select 2 unique elements from a listrandom.shuffle([1, 2, 3])Shuffle a list in placerandom.seed(42)Set the seed for random number generation for reproducibilityrandom.gauss(0, 1)Generate a random number from a Gaussian distribution with mean 0 and standard deviation 1random.expovariate(1)Generate a random number from an exponential distribution with lambda 1
import statisticsImport the statistics librarymean([100, 90])Calculate the mean of a list of numbersmedian([100, 90])Calculate the median of a list of numbersmode([100, 90])Calculate the mode of a list of numbersstdev([100, 90])Calculate the standard deviation of a list of numbersvariance([100, 90])Calculate the variance of a list of numberspvariance([100, 90])Calculate the population variance of a list of numberspstdev([100, 90])Calculate the population standard deviation of a list of numbersquantiles([100, 90], n=4)Calculate the quartiles of a list of numbersharmonic_mean([100, 90])Calculate the harmonic mean of a list of numbersgeometric_mean([100, 90])Calculate the geometric mean of a list of numbersmedian_low([100, 90])Calculate the lower median of a list of numbers
import sysImport the sys librarysys.argvAccess command-line arguments as a list passed to the scriptsys.exit(0)Exit the script with a status code (0 for success)sys.pathAccess the list of directories Python searches for modulessys.versionGet the version of Python being usedsys.platformGet the platform Python is running on (e.g., ’linux’, ‘win32’, ‘darwin’)sys.modulesAccess the list of loaded modulessys.getsizeof(object)Get the size of an object in bytes
import loggingImport the logging library (for logging messages)logging.basicConfig(level=logging.INFO)Set up basic logging configurationlogging.getLogger("my_logger")Get a logger with a specific namelogger.setLevel(logging.DEBUG)Set the logging level for a specific loggerlogger.info("This is an info message")Log an info messagelogger.warning("This is a warning message")Log a warning messagelogger.error("This is an error message")Log an error messagelogger.debug("This is a debug message")Log a debug messagelogger.critical("This is a critical message")Log a critical messagelogger.exception("This is an exception message")Log an exception message with tracebacklogger.addHandler(logging.StreamHandler())Add a handler to a logger to output logs to the consolelogger.addHandler(logging.FileHandler("logfile.log"))Add a handler to a logger to output logs to a file
import mathImport the math librarymath.sqrt(16)Calculate the square root of a numbermath.pow(2, 3)Calculate 2 raised to the power of 3math.factorial(5)Calculate the factorial of a numbermath.gcd(12, 15)Calculate the greatest common divisor of two numbersmath.lcm(12, 15)Calculate the least common multiple of two numbersmath.piGet the value of pimath.eGet the value of Euler’s numbermath.sin(math.pi / 2)Calculate the sine of an angle in radiansmath.cos(math.pi)Calculate the cosine of an angle in radiansmath.tan(math.pi / 4)Calculate the tangent of an angle in radiansmath.log(100, 10)Calculate the logarithm of a number with a specified basemath.log10(100)Calculate the base-10 logarithm of a numbermath.log2(8)Calculate the base-2 logarithm of a numbermath.exp(1)Calculate the exponential of a number (e^x)math.degrees(math.pi)Convert radians to degreesmath.radians(180)Convert degrees to radians
import datetimeImport the datetime libraryimport osImport the os libraryimport jsonImport the json libraryimport reImport the re library (regular expressions)
Packages #
pip install package_nameInstall a package using pippip install package_name==versionInstall a specific version of a packagepip install package_name>=versionInstall a package with a minimum versionpip install package_name<=versionInstall a package with a maximum versionpip install package_name[extra]Install a package with optional extraspip install -e .Install a package in editable mode (for development)pip install -r requirements.txtInstall packages from a requirements filepip freeze > requirements.txtList installed packages and their versionspip listList installed packagespip show package_nameShow information about a specific packagepip uninstall package_nameUninstall a packagepip search querySearch for packagespip checkCheck for broken dependenciespip cacheManage the pip cachepip configManage pip configurationpip wheel package_nameBuild a wheel distribution of a packagepip download package_nameDownload a package without installing itpip install --upgrade package_nameUpgrade a package to the latest versionpip install --force-reinstall package_nameForce reinstall a packagepip install --no-deps package_nameInstall a package without its dependenciespip install --user package_nameInstall a package for the current user onlypip install --system package_nameInstall a package for the system (requires admin privileges)pip install --target /path/to/dir package_nameInstall a package to a specific directorypip install --no-cache-dir package_nameInstall a package without using the cachepip install --pre package_nameInstall a pre-release version of a packagepip install --trusted-host host package_nameInstall a package from a trusted host
Popular Libraries #
requestsImport the requests library (for making HTTP requests)requests.get('https://api.example.com/data')Make a GET request to an APIrequests.post('https://api.example.com/data', json={'key': 'value'})Make a POST request to an API with JSON datarequests.put('https://api.example.com/data/1', json={'key': 'new_value'})Make a PUT request to update datarequests.delete('https://api.example.com/data/1')Make a DELETE request to remove dataresponse.json()Parse the JSON response from an API requestresponse.status_codeGet the status code of the responseresponse.headersGet the headers of the responseresponse.textGet the raw text of the responseresponse.contentGet the raw content of the responseresponse.cookiesGet the cookies from the responseresponse.raise_for_status()Raise an exception for HTTP errorsrequests.Session()Create a session for persistent connectionssession.get('https://api.example.com/data')Make a GET request using a sessionsession.post('https://api.example.com/data', json={'key': 'value'})Make a POST request using a sessionsession.put('https://api.example.com/data/1', json={'key': 'new_value'})Make a PUT request using a sessionsession.delete('https://api.example.com/data/1')Make a DELETE request using a sessionsession.headersSet custom headers for a sessionsession.cookiesSet custom cookies for a sessionsession.authSet authentication for a sessionsession.proxiesSet proxies for a sessionsession.verifySet SSL verification for a session
pandas as pdImport the pandas library (for data manipulation and analysis)numpy as npImport the numpy library (for numerical operations)matplotlib.pyplot as pltImport the matplotlib library (for plotting)seaborn as snsImport the seaborn library (for statistical data visualization)scikit-learn as skImport the scikit-learn library (for machine learning)tensorflow as tfImport the tensorflow library (for deep learning)torchImport the torch library (for deep learning with PyTorch)cv2Import the OpenCV library (for computer vision)PILImport the PIL library (for image processing)sqlite3Import the sqlite3 library (for working with SQLite databases)sqlalchemyImport the sqlalchemy library (for working with databases)unittestImport the unittest library (for unit testing)pytestImport the pytest library (for testing)flaskImport the flask library (for web development)djangoImport the django library (for web development)fastapiImport the fastapi library (for building APIs)scrapyImport the scrapy library (for web scraping)beautifulsoup4 as bs4Import the beautifulsoup4 library (for parsing HTML and XML documents)lxmlImport the lxml library (for parsing XML and HTML documents)xml.etree.ElementTree as ETImport the xml.etree.ElementTree library (for parsing XML documents)csvImport the csv library (for working with CSV files)jsonImport the json library (for working with JSON data)yamlImport the yaml library (for working with YAML data)configparserImport the configparser library (for working with configuration files)argparseImport the argparse library (for parsing command-line arguments)timeImport the time library (for working with time)datetimeImport the datetime library (for working with dates and times)calendarImport the calendar library (for working with calendars)itertoolsImport the itertools library (for working with iterators)functoolsImport the functools library (for working with higher-order functions)operatorImport the operator library (for working with operators)collectionsImport the collections library (for working with specialized container datatypes)heapqImport the heapq library (for working with heaps)bisectImport the bisect library (for working with sorted lists)arrayImport the array library (for working with arrays)structImport the struct library (for working with C-style data structures)ctypesImport the ctypes library (for working with C libraries)multiprocessingImport the multiprocessing library (for parallel processing)threadingImport the threading library (for working with threads)queueImport the queue library (for working with queues)subprocessImport the subprocess library (for running external commands)shutilImport the shutil library (for working with files and directories)globImport the glob library (for working with file patterns)fnmatchImport the fnmatch library (for matching filenames)tempfileImport the tempfile library (for working with temporary files)zipfileImport the zipfile library (for working with ZIP files)tarfileImport the tarfile library (for working with TAR files)gzipImport the gzip library (for working with GZIP files)bz2Import the bz2 library (for working with BZ2 files)lzmaImport the lzma library (for working with LZMA files)base64Import the base64 library (for encoding and decoding base64 data)hashlibImport the hashlib library (for working with hash functions)hmacImport the hmac library (for working with HMACs)