\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{Taissir Boukrouba (taissir2002)} \pdfinfo{ /Title (python-essentials.pdf) /Creator (Cheatography) /Author (Taissir Boukrouba (taissir2002)) /Subject (Python Essentials Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{451CB8} \definecolor{LightBackground}{HTML}{F3F0FA} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Python Essentials Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{Taissir Boukrouba (taissir2002)} via \textcolor{DarkBackground}{\uline{cheatography.com/193976/cs/40402/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}Taissir Boukrouba (taissir2002) \\ \uline{cheatography.com/taissir2002} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 9th November, 2023.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{x{1.09494 cm} x{3.88206 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Datatypes}} \tn % Row 0 \SetRowColor{LightBackground} Text & `str` \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} Numeric & `int` ,` float` \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \seqsplit{Sequence} & `list` , `tuple` , `range` \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} Mapping & `dict` \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} Set & `set` \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} Other & `bool` , `Nonetype` , `bytes` \tn % Row Count 6 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.59501 cm} x{1.60195 cm} x{2.38004 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Casting}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{`int()`} & converts into an integer & `int(2.8) = 2` `int("3") = 3` \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \seqsplit{`float()`} & converts into float & `float(1) = 1.0` `float("3") = 3.0` \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{`str()`} & converts into string & `str(3) = "3"` `str(1.0) = "1.0"` \tn % Row Count 6 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{Casting is converting a datatype to another} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4177 cm} x{1.04425 cm} x{1.2531 cm} x{1.46195 cm} } \SetRowColor{DarkBackground} \mymulticolumn{4}{x{5.377cm}}{\bf\textcolor{white}{Input \& Output (I/O)}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{Output} & we use the `print()` function & it has 3 main arguments which the `string` , the `seperator` and the `end` statement & `print("Are you okay",end="?")` `print("Hi","How are you","I missed you",sep="!!")` \tn % Row Count 7 (+ 7) % Row 1 \SetRowColor{white} Input & we use the `input()` function & the input function is used to take input from user and takes a `text` that is optional as argument & `num = input('Enter your age: ')` \tn % Row Count 16 (+ 9) \hhline{>{\arrayrulecolor{DarkBackground}}----} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Packages}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{p{5.377cm}}{\vspace{1px}\centerline{\includegraphics[width=5.1cm]{/web/www.cheatography.com/public/uploads/taissir2002_1695375898_Screenshot 2023-09-22 at 10.43.12.png}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\textasciicircum{}A directory must contain a file named `init.py` in order for Python to consider it as a package. This file can be left empty but we generally place the initialisation code for that package in this file.\textasciicircum{}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.32733 cm} x{1.60195 cm} x{1.64772 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Operators}} \tn % Row 0 \SetRowColor{LightBackground} Logical ( `and` , `or` , `not` ) & used to check whether an expression is {\emph{True}} or {\emph{False}} & `a = 5`\{\{nl\}\} `b = 6`\{\{nl\}\} `print((a \textgreater{} 2) and (b \textgreater{}= 6))` \textgreater{} ` True` \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} Identity (`is` , `is not`) & used to check if two values are located on the same part of the memory & `x1 = 5` \{\{nl\}\}`y1 = 5` \{\{nl\}\} `print(x1 is not y1)` \{\{nl\}\} \textgreater{} `False` \tn % Row Count 10 (+ 5) % Row 2 \SetRowColor{LightBackground} Membership (`in` , `not in` ) & used to test whether a value or variable is found in a sequence `(string, list, tuple, set, dictionary)` & `x = 'Hello world'` \{\{nl\}\} \seqsplit{`print('hello'} not in x)` \{\{nl\}\}\textgreater{} `True` \tn % Row Count 18 (+ 8) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{{\emph{for membership operators , in dictionaries it only checks the keys and not values}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Module}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{- {\bf{Module}} is a file that contains code to perform a specific task. \newline % Row Count 2 (+ 2) - A {\bf{module}} may contain variables, functions, classes ... \newline % Row Count 4 (+ 2) - A collection of {\bf{modules}} , can make what we call a {\bf{package}} \newline % Row Count 6 (+ 2) \textasciicircum{}As our program grows bigger, it may contain many lines of code. Instead of putting everything in a single file, we can use modules to separate codes in separate files as per their functionality. This makes our code organised and easier to maintain.\textasciicircum{}% Row Count 11 (+ 5) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-- `example.py` -{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-- \newline `\{\{lang-py\}\}def add(a, b): \{\{nl\}\} result = a + b \{\{nl\}\}return result` \newline -{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-- `main.py` -{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-- \newline `\{\{lang-py\}\}import example \{\{nl\}\}addition.add(4,5) \# returns 9`} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.69349 cm} x{1.23579 cm} x{1.64772 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{List's Basic Operations}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Accessing Lists}} & `list{[}index{]}` & `languages = {[}"Python", "Swift"{]}\{\{nl\}\}\# access item at index 0 \{\{nl\}\}print(languages{[}0{]})` \tn % Row Count 7 (+ 7) % Row 1 \SetRowColor{white} {\bf{Slicing Lists}} & `list{[}from:to{]}` & `\# List slicing in Python \{\{nl\}\}my\_list = {[}'p','r','o','g','r'{]} \{\{nl\}\}\# items from index 2 to index 4 \{\{nl\}\}print(my\_list{[}2:5{]})` \tn % Row Count 17 (+ 10) % Row 2 \SetRowColor{LightBackground} {\bf{Adding one item at the end of list }} & \seqsplit{`list.append(item)`} & `numbers = {[}21, 34, 54, 12{]} \{\{nl\}\}numbers.append(32)` \tn % Row Count 21 (+ 4) % Row 3 \SetRowColor{white} {\bf{Adding All items of an iterable}} & \seqsplit{`list1.extend(list2)`} & `numbers = {[}1, 3, 5{]} \{\{nl\}\}even\_numbers = {[}4, 6, 8{]}\{\{nl\}\}numbers.extend(even\_numbers)` \tn % Row Count 28 (+ 7) % Row 4 \SetRowColor{LightBackground} {\bf{Adding one item at specific index}} & \seqsplit{`list.insert(index},item)` & `numbers = {[}10, 30, 40{]}\{\{nl\}\}numbers.insert(1, 20)` \tn % Row Count 32 (+ 4) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.69349 cm} x{1.23579 cm} x{1.64772 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{List's Basic Operations (cont)}} \tn % Row 5 \SetRowColor{LightBackground} {\bf{Changing item values}} & `list{[}item\_index{]} = \seqsplit{new\_value`} & `languages = {[}'Python', 'Swift', 'C++'{]} \{\{nl\}\}\# changing the third item to 'C' \{\{nl\}\}languages{[}2{]} = 'C'` \tn % Row Count 8 (+ 8) % Row 6 \SetRowColor{white} {\bf{Removing one item of a list}} & \seqsplit{`list.remove(item)`} & `languages = {[}'Python', 'Swift'{]} \{\{nl\}\}\# remove 'Python' from the list \{\{nl\}\}languages.remove('Python')` \tn % Row Count 16 (+ 8) % Row 7 \SetRowColor{LightBackground} {\bf{Removing one or more items of a list}} & `del list{[}from:to{]}` & `del languages{[}1{]}` \{\{nl\}\} `del language{[}0:2{]}` \tn % Row Count 20 (+ 4) % Row 8 \SetRowColor{white} {\bf{Check if an item exists in a list}} & `item in list` & `languages = {[}'Python', 'Swift', 'C++'{]} \{\{nl\}\}print('C' in languages) \{\{nl\}\}\textgreater{} False` \tn % Row Count 27 (+ 7) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{A list is a data structure that holds : \newline 1) multiple data at once \newline 2) of different data types (`str`,`int`,`float`) \newline 3) can store duplicates \newline \newline \textasciicircum{}\textgreater{} we can create lists using brackets {\bf{{[} {]}}} or the {\bf{list()}} constructor\textasciicircum{}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.69349 cm} x{1.14425 cm} x{1.73926 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Other Lists Methods}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Remove all items from a list}} & \seqsplit{`list.clear()`} & \seqsplit{`languages.clear()`} \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} {\bf{Return index of item}} & \seqsplit{`list.index(item)`} & `animals = {[}'cat', 'dog', 'rabbit', 'horse'{]} \{\{nl\}\}\# get the index of 'dog' \{\{nl\}\}index = \seqsplit{animals.index('dog')`} \tn % Row Count 11 (+ 8) % Row 2 \SetRowColor{LightBackground} {\bf{Return length of a list}} & \seqsplit{`len(list)`} & \seqsplit{`length(languages)} \{\{nl\}\}\textgreater{} 3` \tn % Row Count 13 (+ 2) % Row 3 \SetRowColor{white} {\bf{Return count of a specific item in a list}} & \seqsplit{`list.count(item)`} & `numbers = {[}2, 3, 5, 2, 11, 2, 7{]} \{\{nl\}\}\# check the count of 2 \{\{nl\}\}count = \seqsplit{numbers.count(2)`} \tn % Row Count 20 (+ 7) % Row 4 \SetRowColor{LightBackground} {\bf{Sort a list (by default ascending)}} & \seqsplit{`list.sort(reverse=false)`} & `vowels = {[}'e', 'a', 'u', 'o', 'i'{]}\{\{nl\}\}vowels.sort(reverse=True) \{\{nl\}\}\textgreater{}{[}'u', 'o', 'i', 'e', 'a'{]}` \tn % Row Count 27 (+ 7) % Row 5 \SetRowColor{white} {\bf{Reverse items of list}} & \seqsplit{`list.reverse()`} & \seqsplit{`prime\_numbers} = {[}2, 3, 5, 7{]} \{\{nl\}\}\# reverse the order of list elements \{\{nl\}\}prime\_numbers.reverse()` \tn % Row Count 34 (+ 7) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.69349 cm} x{1.14425 cm} x{1.73926 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Other Lists Methods (cont)}} \tn % Row 6 \SetRowColor{LightBackground} {\bf{Copy a list}} & \seqsplit{`list.copy()`} & \seqsplit{`prime\_numbers} = {[}2, 3, 5{]} \{\{nl\}\}\# copying a list \{\{nl\}\}numbers = \seqsplit{prime\_numbers.copy()`} \tn % Row Count 6 (+ 6) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{List Comprehensions}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Like there is a short way to write functions , there is a short one to also write lists and it's called {\bf{list comprehension}} \newline % Row Count 3 (+ 3) {\bf{Syntax :}} `{[}expression for item in list{]}` \newline % Row Count 4 (+ 1) \textasciicircum{}List comprehension is generally more compact and faster than normal functions and loops for creating list\textasciicircum{} \newline % Row Count 7 (+ 3) Examples : \newline % Row Count 8 (+ 1) `h\_letters = {[} letter for letter in 'human' {]}\{\{nl\}\}print(h\_letters) \{\{nl\}\}\textgreater{} {[}'h', 'u', 'm', 'a', 'n'{]} ` \newline % Row Count 11 (+ 3) - We can add conditional to list comprehensions : \newline % Row Count 12 (+ 1) `-{}-{}-{}-{}-{}-{}-{}-{}-{}-- example 01 -{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-\{\{nl\}\}number\_list = {[} x for x in range(20) if x \% 2 == 0{]}\{\{nl\}\}print(number\_list)\{\{nl\}\} \textgreater{}{[}0, 2, 4, 6, 8, 10, 12, 14, 16, 18{]}` \newline % Row Count 16 (+ 4) `-{}-{}-{}-{}-{}-{}-{}-{}-{}-- example 02 -{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-{}-\{\{nl\}\}num\_list = {[}y for y in range(100) if y \% 2 == 0 if y \% 5 == 0{]}\{\{nl\}\}print(num\_list)\{\{nl\}\}\textgreater{}{[}0, 10, 20, 30, 40, 50, 60, 70, 80, 90{]}`% Row Count 20 (+ 4) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.64772 cm} x{1.05271 cm} x{1.87657 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Python Tuples}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Accessing tuples}} & `tuple{[}index{]}` & `letters = 'a','b','c' \{\{nl\}\}letters{[}0{]}` \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} {\bf{Slicing tuples}} & `tuple{[}from:to{]}` & `letters = ('a','b','c','d','e') \{\{nl\}\}letters{[}1:3{]}` \tn % Row Count 7 (+ 4) % Row 2 \SetRowColor{LightBackground} {\bf{Return index of item}} & \seqsplit{`tuple.index(item)`} & `letters = ('a','b','c','d','e') \{\{nl\}\}letters.index('a')` \tn % Row Count 11 (+ 4) % Row 3 \SetRowColor{white} {\bf{Return count of a specific item}} & \seqsplit{`tuple.count(item)`} & `letters = ('a','b','a','d','e') \{\{nl\}\}letters.count('a')` \tn % Row Count 15 (+ 4) % Row 4 \SetRowColor{LightBackground} {\bf{Iterating over a tuple}} & `for item in tuple : ` & `languages = ('Python', 'Swift', 'C++') \{\{nl\}\}\# iterating through the tuple \{\{nl\}\}for language in languages: \{\{nl\}\} \seqsplit{print(language)`} \tn % Row Count 24 (+ 9) % Row 5 \SetRowColor{white} {\bf{Check if a tuple element exists}} & `item in tuple` & `'C' in languages` \tn % Row Count 27 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{A {\bf{tuple}} is a data structure that : \newline - holds multiple data at once \newline - of different types (`str`,`int`,`float`) \newline - can store duplicates \newline - is `immutable` so we cannot modify its items (this makes it faster to iterate over compared to lists) , meaning no delete or assignement operations \newline \newline \textasciicircum{}we can create lists using brackets `()` or just comma seperated value (meaning the `()` are optional) like follows :\textasciicircum{} \newline ` first\_tuple = (1,2,3) \{\{nl\}\} second\_tuple = 1,2,3`} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.28156 cm} x{1.64772 cm} x{1.64772 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Dictionaries}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Accessing Items}} & `dictionary{[}key{]}` \{\{nl\}\} \seqsplit{`dictionary.get(key)`} & \seqsplit{`country\_capitals} = \{ \{\{nl\}\}"United States": "Washington D.C.", \{\{nl\}\}"Italy": "Rome", \{\{nl\}\}"England": "London" \} \{\{nl\}\}print(country\_capitals{[}"United States"{]})\{\{nl\}\}\textgreater{} Washington D.C` \tn % Row Count 14 (+ 14) % Row 1 \SetRowColor{white} {\bf{Removing Items}} & `del dictionary{[}key{]}` \{\{nl\}\} \seqsplit{`dictionary.pop(key)`} & `sales = \{ 'apple': 2, 'orange': 3, 'grapes': 4 \} \{\{nl\}\}popped\_element = \seqsplit{sales.pop('apple')`} \tn % Row Count 21 (+ 7) % Row 2 \SetRowColor{LightBackground} {\bf{Membership Test}} (keys only) & ` key in dictionary` & `my\_list = \{1: "Hello", "Hi": 25, "Howdy": 100\} \{\{nl\}\}print(1 in my\_list) -\textgreater{} True\{\{nl\}\}print("Howdy" not in my\_list) -\textgreater{} False\{\{nl\}\}print("Hello" in my\_list) -\textgreater{} False` \tn % Row Count 33 (+ 12) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.28156 cm} x{1.64772 cm} x{1.64772 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Dictionaries (cont)}} \tn % Row 3 \SetRowColor{LightBackground} {\bf{Iterating Items}} & `for key,value in \seqsplit{dictionary.items()`} & `my\_dict = \{'apple': 1, 'banana': 2, 'orange': 3, 'grape': 4\} \{\{nl\}\}for key, value in \seqsplit{my\_dict.items():} \{\{nl\}\}print(f"Key: \{key\}, Value: \{value\}")` \tn % Row Count 11 (+ 11) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{A {\bf{dictionary}} is a data structure and a collection that : \newline - allows us to store data in key-value pairs. \newline - {\bf{dictionary}} keys must be immutable, such as tuples, strings, integers, etc meaning we cannot use mutable (changeable) objects such as lists as keys. \newline - {\bf{dictionary}} values must be mutable of course \newline \newline \textasciicircum{}We create dictionaries by placing {\bf{key:value}} pairs inside curly brackets {\bf{\{ \}}}, separated by commas\textasciicircum{}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Other Dictionary Methods}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Update Items}} & `dictionary.update(\{key : new\_value\})`\{\{nl\}\} `dictionary.update(\{new\_key : new\_value\})` & `d = \{1: "one", 2: "three"\} \{\{nl\}\}d1 = \{2: "two"\} \{\{nl\}\}\# updates the value of key 2 \{\{nl\}\}d.update(d1)` \tn % Row Count 9 (+ 9) % Row 1 \SetRowColor{white} {\bf{Remove All Items}} & \seqsplit{`dictionary.clear()`} & `d.clear()` \tn % Row Count 11 (+ 2) % Row 2 \SetRowColor{LightBackground} {\bf{Return All Keys}} & \seqsplit{`dictionary.keys()`} & `numbers = \{1: 'one', 2: 'two', 3: 'three'\} \{\{nl\}\}\# extracts the keys of the dictionary\{\{nl\}\}dictionaryKeys = \seqsplit{numbers.keys()`} \tn % Row Count 21 (+ 10) % Row 3 \SetRowColor{white} {\bf{Return All Values}} & \seqsplit{`dictionary.values()`} & `marks = \{'Physics':67, 'Maths':87\} \{\{nl\}\}print(marks.values())` \tn % Row Count 26 (+ 5) % Row 4 \SetRowColor{LightBackground} {\bf{Return Items}} & \seqsplit{`dictionary.items()`} & `marks = \{'Physics':67, 'Maths':87\} \{\{nl\}\}print(marks.items()) \{\{nl\}\}\textgreater{} dict\_items({[}('Physics', 67), ('Maths', 87){]})` \tn % Row Count 36 (+ 10) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Other Dictionary Methods (cont)}} \tn % Row 5 \SetRowColor{LightBackground} {\bf{Copy Dictionary}} & \seqsplit{`dictionary.copy()`} & \seqsplit{`original\_marks} = \{'Physics':67, 'Maths':87\} \{\{nl\}\}copied\_marks = \seqsplit{original\_marks}.copy()` \tn % Row Count 7 (+ 7) % Row 6 \SetRowColor{white} {\bf{Create Dictionary From Keys \& Values}} & \seqsplit{`dict.fromkeys(keys},values)` & `keys = \{'a', 'e', 'i', 'o', 'u' \}\{\{nl\}\}value = {[}1{]} \{\{nl\}\}vowels = \seqsplit{dict.fromkeys(keys}, value)` \tn % Row Count 15 (+ 8) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.60195 cm} x{1.3731 cm} x{1.60195 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Sets}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Adding Items}} & \seqsplit{`set.add(item)`} & `numbers = \{21, 34, 54, 12\} \{\{nl\}\}numbers.add(32)` \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} {\bf{Update Items}} & \seqsplit{`set.update(iterable)`} & `companies = \{'Lacoste', 'Ralph Lauren'\} \{\{nl\}\}tech\_companies = {[}'apple', 'google', 'apple'{]} \{\{nl\}\}companies.update(tech\_companies)\{\{nl\}\}print(companies) \{\{nl\}\}\textgreater{} \{'google', 'apple', 'Lacoste', 'Ralph Lauren'\}` \tn % Row Count 20 (+ 16) % Row 2 \SetRowColor{LightBackground} {\bf{Remove Items}} & \seqsplit{`set.discard(item)`} & `removedValue = \seqsplit{languages.discard('Java')`} \tn % Row Count 23 (+ 3) % Row 3 \SetRowColor{white} {\bf{ Checking if All Set Items Are True (or empty)}} & `all(set)` \textasciicircum{}(stands for U or *) \textasciicircum{} & `L = {[}1, 3, 4, 5{]} \{\{nl\}\}print(all(L))\{\{nl\}\}\textgreater{} True` \tn % Row Count 27 (+ 4) % Row 4 \SetRowColor{LightBackground} {\bf{ Checking if Any Set Items Are True}} & `any(set)` \textasciicircum{}(stands for ∩ or + )\textasciicircum{} & `L = {[}1, 3, 4, 0{]} \{\{nl\}\}print(any(L))\{\{nl\}\}\textgreater{} True` \tn % Row Count 31 (+ 4) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.60195 cm} x{1.3731 cm} x{1.60195 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Sets (cont)}} \tn % Row 5 \SetRowColor{LightBackground} {\bf{ Returning Enumerate Object}} & \seqsplit{`enumurate(iterable)`} & `grocery = {[}'bread', 'milk', 'butter'{]} \{\{nl\}\}for count, item in \seqsplit{enumerate(grocery):} \{\{nl\}\} print(count, item) \{\{nl\}\}\textgreater{} 0 bread \{\{nl\}\} 1 milk \{\{nl\}\} 2 butter` \tn % Row Count 12 (+ 12) % Row 6 \SetRowColor{white} {\bf{ Returning Length Of Set}} & `len(set)` & \seqsplit{`len(grocery)`} \tn % Row Count 14 (+ 2) % Row 7 \SetRowColor{LightBackground} {\bf{ Largest \& Smallest item}} & `max(set)` \{\{nl\}\} `min(set)` & `numbers = {[}9, 34, 11, -4, 27{]} \{\{nl\}\}\# find the maximum number \{\{nl\}\}max\_number = max(numbers)` \tn % Row Count 21 (+ 7) % Row 8 \SetRowColor{white} {\bf{ Sorting Set }} & \seqsplit{`sorted(set)`} & `py\_set = \{'e', 'a', 'u', 'o', 'i'\} \{\{nl\}\}print(sorted(py\_set)\{\{nl\}\}\textgreater{} {[}'a', 'e', 'i', 'o', 'u'{]}` \tn % Row Count 28 (+ 7) % Row 9 \SetRowColor{LightBackground} {\bf{ Summing Set Items }} & `sum(set)` & `marks = \{65, 71, 68, 74, 61\} \{\{nl\}\}\# find sum of all marks \{\{nl\}\}total\_marks = sum(marks)\{\{nl\}\}\textgreater{} 339` \tn % Row Count 36 (+ 8) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.60195 cm} x{1.3731 cm} x{1.60195 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Sets (cont)}} \tn % Row 10 \SetRowColor{LightBackground} {\bf{ Iterate Over Set }} & `for item in set : ` & `fruits = \{"Apple", "Peach", "Mango"\} \{\{nl\}\}\# loop to access each fruits \{\{nl\}\}for fruit in fruits: \{\{nl\}\} print(fruit)` \tn % Row Count 9 (+ 9) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{A {\bf{Set}} is data structure that : \newline - Stores different data types \newline - Cannot have duplicates \newline - has {\bf{immutable}} elements unlike lists and dictionaries \newline \newline \textasciicircum{}In Python, we create sets by placing all the elements inside curly braces {\bf{\{ \}}} , separated by comma or using the {\bf{set()}} constructor.\textasciicircum{} \newline `student\_id = \{112, 114, 116, 118, 115\}`} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.05271 cm} x{1.78503 cm} x{1.73926 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Set Operations}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Union}} & `set1.union(set2)`\{\{nl\}\}`set1 | set2` & `A = \{1, 3, 5\} \{\{nl\}\}B = \{0, 2, 4\}\{\{nl\}\}print(A|B)\{\{nl\}\}\textgreater{} \{0, 1, 2, 3, 4, 5\}` \tn % Row Count 6 (+ 6) % Row 1 \SetRowColor{white} {\bf{Intersection}} & \seqsplit{`set1.intersection(set2)`} \{\{nl\}\} `set1 \& set2` & `A = \{1, 3, 5\} \{\{nl\}\}B = \{1, 2, 3\}\{\{nl\}\}print(A \& B)\{\{nl\}\}\textgreater{} \{1, 3\}` \tn % Row Count 11 (+ 5) % Row 2 \SetRowColor{LightBackground} {\bf{Difference}} & \seqsplit{`set1.difference(set2)`} \{\{nl\}\} `set1 - set2` & `A = \{2, 3, 5\}\{\{nl\}\}B = \{1, 2, 6\} \{\{nl\}\}print(A - B)\{\{nl\}\}\textgreater{} \{3, 5\}` \tn % Row Count 16 (+ 5) % Row 3 \SetRowColor{white} {\bf{Symmetric Difference}} & \seqsplit{`set1.symmetric\_difference(set2)`} \{\{nl\}\} `set1 \textasciicircum{} set2` & `A = \{2, 3, 5\}\{\{nl\}\}B = \{1, 2, 6\} \{\{nl\}\}print(A \textasciicircum{} B)\{\{nl\}\}\textgreater{} \{1, 3, 5, 6\}` \tn % Row Count 21 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Python Strings}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Accessing Strings}} & `string{[}index{]}` & `greet = 'hello' \{\{nl\}\}print(greet{[}1{]})` \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} {\bf{Slicing Strings}} & `string{[}from:to{]}` & `greet = 'hello' \{\{nl\}\}print(greet{[}0:2{]})` \tn % Row Count 7 (+ 4) % Row 2 \SetRowColor{LightBackground} {\bf{Comparing Two Strings}} & `string1 == string2` & `str1 = "Hello, world!" \{\{nl\}\}str2 = "I love Python." \{\{nl\}\}print(str1 == str2)` \tn % Row Count 14 (+ 7) % Row 3 \SetRowColor{white} {\bf{Joining Strings}} & `string1 + string2` & `str1 = "Hello, world!" \{\{nl\}\}str2 = "I love Python." \{\{nl\}\}print(str1 + str2)` \tn % Row Count 21 (+ 7) % Row 4 \SetRowColor{LightBackground} {\bf{String Length}} & \seqsplit{`len(string)`} & `greet = 'hello' \{\{nl\}\}print(len(greet))` \tn % Row Count 25 (+ 4) % Row 5 \SetRowColor{white} {\bf{Formatting Strings (f-strings)}} & `f"\{string\}"` & `print(f'\{name\} is from \{country\}')` \tn % Row Count 28 (+ 3) % Row 6 \SetRowColor{LightBackground} {\bf{Uppercase \& Lowercase Strings}} & \seqsplit{`string.upper()`} \{\{nl\}\} \seqsplit{`string.lower()`} & `message = 'python is fun' \{\{nl\}\}print(message.upper())` \tn % Row Count 33 (+ 5) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Python Strings (cont)}} \tn % Row 7 \SetRowColor{LightBackground} {\bf{Partitioning String Into Three Part Tuples}} & \seqsplit{`string.partition(seperator)`} & `string = "Python is fun, isn't it" \{\{nl\}\}print(string.partition('is'))\{\{nl\}\}\textgreater{}('Python ', 'is', " fun, isn't it")` \tn % Row Count 9 (+ 9) % Row 8 \SetRowColor{white} {\bf{Replacing Sub-String}} & \seqsplit{`string.replace(old\_substring},new\_substring,occurences\textasciicircum{}optional\textasciicircum{})` & `song = 'Let it be, let it be, let it be, let it be' \{\{nl\}\}\# replacing only two occurrences of 'let' \{\{nl\}\}print(song.replace('let', "don't let", 2))` \tn % Row Count 21 (+ 12) % Row 9 \SetRowColor{LightBackground} {\bf{Return Index of Substring}} & \seqsplit{`string.find(substring)`} & `quote = 'Let it be, let it be, let it be' \{\{nl\}\}\# first occurance of 'let it'(case sensitive) \{\{nl\}\}result = \seqsplit{quote.find('let} it')` \tn % Row Count 32 (+ 11) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Python Strings (cont)}} \tn % Row 10 \SetRowColor{LightBackground} {\bf{Remove Trailing Characters ( By default removes whitespace)}} & `string.rstripe(substring\textasciicircum{}optional\textasciicircum{})` & `website = \seqsplit{'www.programiz.com/'} \{\{nl\}\}print(website.rstrip('m/.'))` \tn % Row Count 6 (+ 6) % Row 11 \SetRowColor{white} {\bf{Splitting Strings}} & \seqsplit{`string.split(seperator},maxsplit`) & `grocery = "Milk, Chicken, Bread, Butter"\{\{nl\}\}print(grocery.split(', ', 1)) \{\{nl\}\}\textgreater{}{[}"Milk","Chicken, Bread, Butter"{]}` \tn % Row Count 16 (+ 10) % Row 12 \SetRowColor{LightBackground} {\bf{Checking String Start}} & \seqsplit{`string.startswith(substring)`} & `text = "Python is easy to learn." \{\{nl\}\}result = \seqsplit{text.startswith('is} easy') \{\{nl\}\}\textgreater{} False` \tn % Row Count 24 (+ 8) % Row 13 \SetRowColor{white} {\bf{Advanced String Indexing}} & \seqsplit{`string.index(substring} , from, to \textasciicircum{}optional\textasciicircum{}) & `sentence = 'Python programming is fun.' \{\{nl\}\}\# Substring is searched in 'gramming is ' \{\{nl\}\}print(sentence.index('g is', 10, -4))` \tn % Row Count 35 (+ 11) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{Python strings are immutable meaning we cannot change them , but we can assign its variable to another string which can do the job : \newline `message = 'Hola Amigos' \{\{nl\}\}message = 'Hello Friends'`} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Python Files}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{A {\bf{file}} is a container in computer storage devices used for storing data. \newline % Row Count 2 (+ 2) When we want to read from or write to a file, we need to : \newline % Row Count 4 (+ 2) 1- Open the file \newline % Row Count 5 (+ 1) 2- Read or write in the file \newline % Row Count 6 (+ 1) 3- Close the file% Row Count 7 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.28156 cm} x{1.64772 cm} x{1.64772 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{File Operations}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Opening Files For Reading}} & `open(source,'r')` & `file1= \seqsplit{open("test.txt"},'r')` \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} {\bf{Reading Files}} & `file.read()` & \seqsplit{`read\_content} = file1.read() \{\{nl\}\}print(read\_content)` \tn % Row Count 7 (+ 4) % Row 2 \SetRowColor{LightBackground} {\bf{Closing Files}} & \seqsplit{`file.close()`} & \seqsplit{`file1.close()`} \tn % Row Count 9 (+ 2) % Row 3 \SetRowColor{white} {\bf{Opening Files For Writing}} & `open(source,'w')` & `file2 = \seqsplit{open("test.txt"},'w')` \tn % Row Count 12 (+ 3) % Row 4 \SetRowColor{LightBackground} {\bf{Writing in Files}} & \seqsplit{`file.write(text)`} & \seqsplit{`file2.write('Programming} is Fun.')` \tn % Row Count 15 (+ 3) % Row 5 \SetRowColor{white} {\bf{Automatically Closing Files}} & `with open(source,mode) as filname : \{\{nl\}\}\#instructions` & `with \seqsplit{open("test.txt"}, "r") as file1:\{\{nl\}\}read\_content = file1.read()\{\{nl\}\}print(read\_content)` \tn % Row Count 22 (+ 7) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.51041 cm} x{1.3731 cm} x{1.69349 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Directory Management}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{ Get Current Working Directory }} & \seqsplit{`os.getcwd()`} & `import os \{\{nl\}\}print(os.getcwd()\{\{nl\}\}\textgreater{} \seqsplit{/Users/tayssirboukrouba/Data} Science Cheat Sheet` \tn % Row Count 7 (+ 7) % Row 1 \SetRowColor{white} {\bf{ Changing Directory}} & \seqsplit{`os.chdir(new\_directory)`} & `import os\{\{nl\}\}os.chdir('/Users/tayssirboukrouba/')\{\{nl\}\}print(os.getcwd())` \tn % Row Count 13 (+ 6) % Row 2 \SetRowColor{LightBackground} {\bf{ List Directories }} & \seqsplit{`os.listdir()`} & `import os\{\{nl\}\}os.chdir('/Users/tayssirboukrouba/')\{\{nl\}\}os.listdir()` \tn % Row Count 19 (+ 6) % Row 3 \SetRowColor{white} {\bf{ Making New Directory }} & \seqsplit{`os.mkdir('dir\_name')`} & `os.mkdir('test')\{\{nl\}\}os.listdir()` \tn % Row Count 22 (+ 3) % Row 4 \SetRowColor{LightBackground} {\bf{ Renaming Directory or File }} & \seqsplit{`os.rename('old\_dir'},'new\_dir')` & `import os\{\{nl\}\}os.listdir()\{\{nl\}\}os.rename('test','new\_one')\{\{nl\}\}os.listdir()` \tn % Row Count 28 (+ 6) % Row 5 \SetRowColor{white} {\bf{Removing Directories}} & \seqsplit{`os.remove('directory')`} & `import os\{\{nl\}\}\# delete "test.txt" file\{\{nl\}\}os.remove("test.txt")` \tn % Row Count 33 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{A {\bf{Directory}} is a collection of files and subdirectories. \newline A directory inside a directory is known as a {\bf{sub-directory}} . \newline \newline Python has the {\bf{`os`}} module that provides us with many useful methods to work with directories (and files as well).} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4577 cm} x{2.05965 cm} x{2.05965 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Conditionals}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{if}} & used to execute an instruction if a condition was true & `number = 0` \{\{nl\}\} `if number \textgreater{} 0: \{\{nl\}\} print("Positive number")` \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} {\bf{elif}} & used to execute an instruction if the previous condition was not true and stands for {\emph{else if}} & `elif number == 0: \{\{nl\}\} print('Zero')` \tn % Row Count 11 (+ 6) % Row 2 \SetRowColor{LightBackground} {\bf{else}} & used to execute an instruction if all conditions were not true & `else print("not positive")` \tn % Row Count 15 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.59501 cm} x{2.01388 cm} x{1.96811 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Loops}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{for}} & used mostly to loop through a sequence & `languages = {[}'Swift', 'Python', 'Go', 'JavaScript'{]}` \{\{nl\}\} `for language in languages:` \{\{nl\}\} \seqsplit{`print(language)`} \tn % Row Count 7 (+ 7) % Row 1 \SetRowColor{white} {\bf{while}} & used to loop through a statement while the condition is not met & `counter = 0 ` \{\{nl\}\}`while counter \textless{} 3:` \{\{nl\}\} `print('Inside loop') ` \{\{nl\}\} `counter = counter + 1` \{\{nl\}\}`else print('Inside else')` \tn % Row Count 16 (+ 9) % Row 2 \SetRowColor{LightBackground} {\bf{break}} & used to terminate the loop immediately when it is encountered & `for i in range(5):` \{\{nl\}\} ` if i == 3:` \{\{nl\}\} ` break` \{\{nl\}\} `print(i)` \tn % Row Count 22 (+ 6) % Row 3 \SetRowColor{white} {\bf{continue}} & used to skip the current iteration of the loop and the control flow of the program goes to the next iteration & `for i in range(5):` \{\{nl\}\} ` if i == 3:` \{\{nl\}\} ` continue` \{\{nl\}\} `print(i)` \tn % Row Count 29 (+ 7) % Row 4 \SetRowColor{LightBackground} {\bf{pass}} & null statement which can be used as a placeholder for future code & `n = 10` \{\{nl\}\} `if n \textgreater{} 10:`\{\{nl\}\} ` pass` \{\{nl\}\}`print('Hello')` \tn % Row Count 34 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.09034 cm} x{2.88666 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Functions \& Arguments}} \tn % Row 0 \SetRowColor{LightBackground} Syntax & `def \seqsplit{function\_name(arguments):} \{\{nl\}\} \# function body \{\{nl\}\}return` \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} Arguments with default values & `def add\_numbers(a = 7, b = 8):` \tn % Row Count 6 (+ 2) % Row 2 \SetRowColor{LightBackground} Arguments with keywords & `def \seqsplit{display\_info(first\_name}, last\_name): \{\{nl\}\} print('First Name:', first\_name) \{\{nl\}\} print('Last Name:', last\_name) \{\{nl\}\}display\_info(last\_name = 'Cartman', first\_name = 'Eric')` \tn % Row Count 15 (+ 9) % Row 3 \SetRowColor{white} Arbitrary Arguments & `def my\_function(*kids): \{\{nl\}\}print("The youngest child is " + kids{[}2{]}) \{\{nl\}\}my\_function("Emil", "Tobias", "Linus")` \tn % Row Count 21 (+ 6) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{If you do not know how many arguments that will be passed into your function, add a `*` before the parameter name in the function definition which will make the param an {\emph{arbitrary argument}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{0.86963 cm} x{1.87657 cm} x{1.8308 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Variables Scopes}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Local variable}} & a variables that is declared inside a function ( cannot be accessed outside it ) & `def greet(): \{\{nl\}\}\# local variable \{\{nl\}\} message = 'Hello' \{\{nl\}\} print('Local', message`)\{\{nl\}\}`greet()` \tn % Row Count 8 (+ 8) % Row 1 \SetRowColor{white} {\bf{Global variable}} & a variables that is declared outside a function ( can be accessed outside or inside it ) & `\# declare global variable \{\{nl\}\}message = 'Hello' \{\{nl\}\}def greet(): \{\{nl\}\} \# declare local variable \{\{nl\}\} print('Local', message) \{\{nl\}\}greet() \{\{nl\}\}print('Global', message)` \tn % Row Count 20 (+ 12) \hhline{>{\arrayrulecolor{DarkBackground}}---} \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{we can use the `global` keyword when we are inside a function , and we want to read and write a global variable inside a function.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.74655 cm} x{4.23045 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Lambda Functions}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{Syntax} & `lambda arguments : expression` \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \seqsplit{Example} & `greet\_user = lambda name : print('Hey,', name)`\{\{nl\}\} `greet\_user('Delilah')`\{\{nl\}\} `\textgreater{} Hey, Delilah` \tn % Row Count 4 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Lambda functions are also called anonymous functions because they have no name} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Python OOP}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Object}} & it's a collection of {\bf{data}} (variables) and {\bf{methods}} (functions). & `class Bike:\{\{nl\}\}\#Attributes with default values :\{\{nl\}\}name = ""\{\{nl\}\}gear = 0` \tn % Row Count 7 (+ 7) % Row 1 \SetRowColor{white} {\bf{Class}} & it is a {\bf{blueprint}} or an example (sample) of that object & `bike1 = Bike()` \tn % Row Count 12 (+ 5) % Row 2 \SetRowColor{LightBackground} {\bf{Accessing Class Attributes Using Objects}} & We use the {\bf{"`.`"}} notation to access the attributes of a class & `\# modify the name attribute\{\{nl\}\}bike1.name = "Mountain Bike"\{\{nl\}\}\# access the gear attribute\{\{nl\}\}bike1.gear` \tn % Row Count 21 (+ 9) % Row 3 \SetRowColor{white} {\bf{ Class Methods}} & A Python Function defined inside a class is called a {\bf{method}}. & `class Room:\{\{nl\}\} length = 0.0\{\{nl\}\} breadth = 0.0\{\{nl\}\}\# method to calculate area \{\{nl\}\} def \seqsplit{calculate\_area(self):} \{\{nl\}\} print("Area of Room =", self.length * \seqsplit{self.breadth)`} \tn % Row Count 36 (+ 15) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Python OOP (cont)}} \tn % Row 4 \SetRowColor{LightBackground} {\bf{Constructors}} & We can initialise class using {\bf{`\_\_init\_\_()`}} function & `class Bike: \{\{nl\}\}\# constructor function \{\{nl\}\} def \seqsplit{\_\_init\_\_(self}, name = ""):\{\{nl\}\} self.name = name\{\{nl\}\}bike1 = Bike()\{\{nl\}\}bike1 = \seqsplit{Bike("Mountain} Bike")` \tn % Row Count 13 (+ 13) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.23965 cm} x{2.73735 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Exception Handeling}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{`try-except` Statement}} & `try:\{\{nl\}\} numerator = 10 \{\{nl\}\} denominator = 0\{\{nl\}\} result = numerator/denominator\{\{nl\}\} print(result)\{\{nl\}\}except:\{\{nl\}\} print("Error: Denominator cannot be 0.")\{\{nl\}\}\# Output: Error: Denominator cannot be 0. ` \tn % Row Count 10 (+ 10) % Row 1 \SetRowColor{white} {\bf{ Catching Specific Exceptions}} & `try:\{\{nl\}\} even\_numbers = {[}2,4,6,8{]}\{\{nl\}\} print(even\_numbers{[}5{]})\{\{nl\}\}except ZeroDivisionError:\{\{nl\}\} print("Denominator cannot be 0.")\{\{nl\}\}except IndexError:\{\{nl\}\} print("Index Out of Bound.")\{\{nl\}\}\# Output: Index Out of Bound` \tn % Row Count 21 (+ 11) % Row 2 \SetRowColor{LightBackground} {\bf{`try-else` Statement}} & `\# program to print the reciprocal of even numbers\{\{nl\}\}try:\{\{nl\}\} num = int(input("Enter a number: "))\{\{nl\}\} assert num \% 2 == 0 \{\{nl\}\}except:\{\{nl\}\} print("Not an even number!")\{\{nl\}\}else:\{\{nl\}\} reciprocal = 1/num\{\{nl\}\} print(reciprocal)` \tn % Row Count 32 (+ 11) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{2.23965 cm} x{2.73735 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Exception Handeling (cont)}} \tn % Row 3 \SetRowColor{LightBackground} {\bf{ `try-finally` Statement}} & `try:\{\{nl\}\} numerator = 10\{\{nl\}\} denominator = 0\{\{nl\}\} result = numerator/denominator\{\{nl\}\} print(result) \{\{nl\}\}except:\{\{nl\}\} print("Error: Denominator cannot be 0.")\{\{nl\}\}finally:\{\{nl\}\} print("This is finally block.")` \tn % Row Count 10 (+ 10) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\emph{Exceptions can terminate the program's execution , that's why it is important to handle them}} \newline \newline {\emph{when an exception occurs, the rest of the code inside the {\bf{try}} block is skipped. If none of the statements in the {\bf{try}} block generates an exception, the {\bf{except}} block is skipped.}} \newline \newline In Python, the {\bf{finally}} block is always executed no matter whether there is an exception or not.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.59264 cm} x{3.38436 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Python Exceptions}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{`SyntaxError`} & Raised when there is a syntax error in the code, such as incorrect indentation, invalid syntax, or mismatched parentheses. \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} \seqsplit{`IndentationError`} & A specific type of SyntaxError that occurs when there are problems with the indentation of the code. \tn % Row Count 9 (+ 4) % Row 2 \SetRowColor{LightBackground} `NameError` & Raised when a variable or name is used before it is defined. \tn % Row Count 12 (+ 3) % Row 3 \SetRowColor{white} `TypeError` & Occurs when an operation or function is applied to an object of an inappropriate type. \tn % Row Count 16 (+ 4) % Row 4 \SetRowColor{LightBackground} \seqsplit{`ValueError`} & Raised when a function receives an argument of the correct data type but an inappropriate value \tn % Row Count 20 (+ 4) % Row 5 \SetRowColor{white} \seqsplit{`ZeroDivisionError`} & Occurs when attempting to divide by zero \tn % Row Count 22 (+ 2) % Row 6 \SetRowColor{LightBackground} \seqsplit{`IndexError`} & Raised when trying to access an index that is out of range for a list, tuple, or string. \tn % Row Count 26 (+ 4) % Row 7 \SetRowColor{white} `KeyError` & Raised when trying to access a non-existent key in a dictionary. \tn % Row Count 29 (+ 3) % Row 8 \SetRowColor{LightBackground} \seqsplit{`AttributeError`} & Raised when an attribute or method is not found for an object. \tn % Row Count 32 (+ 3) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{1.59264 cm} x{3.38436 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Python Exceptions (cont)}} \tn % Row 9 \SetRowColor{LightBackground} \seqsplit{`ImportError`} & Occurs when a module cannot be imported. \tn % Row Count 2 (+ 2) % Row 10 \SetRowColor{white} \seqsplit{`AssertionError`} & Raised when an assert statement fails. \tn % Row Count 4 (+ 2) % Row 11 \SetRowColor{LightBackground} \seqsplit{`OverflowError`} & Raised when the result of an arithmetic operation is too large to be represented. \tn % Row Count 7 (+ 3) % Row 12 \SetRowColor{white} \seqsplit{`MemoryError`} & Occurs when the Python interpreter cannot allocate enough memory for an object. \tn % Row Count 10 (+ 3) % Row 13 \SetRowColor{LightBackground} \seqsplit{`RuntimeError`} & A generic error that is raised when no specific exception applies. \tn % Row Count 13 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{An {\bf{exception}} is an unexpected event (error) that occurs during program execution , for example : \newline \newline `divide\_by\_zero = 7 / 0` \newline \newline The above code causes an exception as it is not possible to divide a number by 0.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}