There are so many programming languages, it can be hard to know which to focus on. As a beginner, it’s easy to be overwhelmed with the possibilities. Even seasoned coders are constantly learning.
Whether you’re using CSS3, Python, or SQL, we’ve put together this article to teaches you everything you need to know to get going with programming and take your current skills up a level. This article contains:
- Arduino Commands
- CSS3 Properties
- HTML Essentials
- Javascript Commands
- Python RegEx Shortcuts
- Raspberry Pi Commands
- SQL Commands
- Visual Studio Code Shortcuts
This article is everything you need to grasp the programming basics and to start making progress on your coding projects.
Table of contents
Arduino Commands
CSS3 Properties
HTML Essentials
Javascript Commands
Python RegEx Shortcuts
Raspberry Pi Commands
SQL Commands
Visual Studio Code Shortcuts
Arduino Commands
Verify | Scans your code and reports any errors |
Upload | Compiles your code and uploads it to the Arduino board via USB |
New | Opens a blank Arduino sketch |
Open | Opens a list of your saved sketches in the file browser |
Save | Saves your current sketch |
Serial Monitor | Opens the serial monitor in a new window |
void setup {} | Runs once at startup |
void loop {} | Runs continually |
pinMode(PIN_NUMBER, INPUT/OUTPUT) | Sets the pin at the location PIN_NUMBER to be either an INPUT or an OUTPUT |
pinMode(PIN_NUMBER, INPUT_PULLUP) | Sets the pin at the location PIN_NUMBER to be an input using the Arduino board’s built-in pull-up resistor |
digitalRead(PIN_NUMBER) | Reads the input at PIN_NUMBER and returns a 1 or 0 (HIGH or LOW) |
digitalWrite(PIN_NUMBER, VALUE) | Writes a value of 1 or 0 (HIGH or LOW) to digital pin PIN_NUMBER |
analogRead(PIN_NUMBER) | Reads the analog pin PIN_NUMBER and returns an integer between 0 and 1023 |
analogWrite(PIN_NUMBER, VALUE) | Emulates analog output VALUE using PWM on PIN_NUMBER (note: only available on pins 3, 5, 6, 9, 10, and 11) |
analogReference(DEFAULT) | Use the default reference voltage (5V or 3.3V depending on board voltage) |
analogReference(INTERNAL) | Use an internal reference voltage (1.1v for ATmega168/328p, 2.56 for ATmega 32U4/8) |
analogReference(EXTERNAL) | Use a voltage applied to the AREF pin as voltage reference (note: 0-5V only) |
millis() | Returns the time in milliseconds since the Arduino sketch began running as an unsigned long integer |
micros() | Returns the time in microseconds since the Arduino sketch began running as an unsigned long integer |
delay(INTEGER) | Delays program execution for INTEGER milliseconds |
delayMicroseconds(INTEGER) | Delays program execution for INTEGER microseconds |
min(i, j) | Returns the lowest of the two values i and j |
max(i,j) | Returns the highest of the two values i and j |
abs(i) | Returns the absolute value of i |
sin(angle) | Returns the sine of an angle in radians |
cos(angle) | Returns the cosine of an angle in radians |
tan(angle) | Returns the tangent of an angle in radians |
sqrt(i) | Returns the square root of i |
pow(base, exponent) | Raises the number base to the number exponent (e.g pow (2 , 3) ==8) |
constrain(i, minval, maxval) | Contrains the value i between minval and maxval |
map(val, fromL, fromH, toL, toH) | Remaps val from one range to another |
random(i) | Returns a random long integer smaller than i |
random(i, j) | Returns a random long integer between i and j |
randomSeed(k) | Uses the value k to seed the random() function |
(type)variable | Casts the value of variable to a new type |
Serial.begin(speed) | Start serial communication at a specified speed |
Serial.end() | Close serial communication |
Serial.print(DATA) | Prints DATA to the serial port. DATA can be characters, strings, integers and floating point numbers |
Serial.available() | Return the number of characters available to read in the serial buffer |
Serial.read() | Read the first character in the serial buffer (returns -1 if no data is available) |
Serial.write(DATA) | Write DATA to the serial buffer. DATA can be a character, integer, or array |
Serial.flush() | Clears the serial buffer once outgoing communication is complete |
Servo myServo | Creates the variable myServo of type Servo |
myServo.attach(PIN_NUMBER) | Associated myServo with the pin at location PIN_NUMBER |
myServo.write(angle) | Writes an angle between 0 and 180 to the servo atached to myServo |
myServo.writeMicroseconds(uS) | Writes a value in microseconds to the servo attached to myServo (typically between 1000 and 2000 with 1500 as the midpoint) |
myServo.read() | Returns an integer containing the current angle of the servo between 0 – 180 |
myServo.attached() | Returns true if the servo is attached to a pin |
myServo.detach() | Dissasociates myServo with an attached pin |
CSS3 Properties
background | Defines a variety of background properties within one declaration. |
background-attachment | Specifies whether the background image is fixed or scrolls with the webpage. |
background-color | Defines the background color of an element on the webpage. |
background-image | Defines an element’s background image. |
background-clip | Specifies how far the background images or color extends for an element. |
background-origin | Specifies the positioning area of the background images. |
background-position | Defines the origin of a background image. |
background-repeat | Specifies how the background image is tiled. |
background-size | Specifies the size of the background images. |
border | Sets the border width, style, and color for all four sides of an element. |
border-bottom | Sets the width, style, and color for the bottom border of an element. |
border-bottom-color | Sets the color of the bottom border of an element. |
border-bottom-left-radius | Defines the shape of the bottom-left border corner of an element. |
border-bottom-right-radius | Defines the shape of the bottom-right border corner of an element. |
border-bottom-style | Sets the style of the bottom border of an element. |
border-bottom-width | Sets the width of the bottom border of an element. |
border-color | Sets the color of the border on all the four sides of an element. |
border-image | Specifies how an image is to be used in place of the border styles. |
border-image-outset | Specifies the amount by which the border image area extends beyond the border box. |
border-image-repeat | Specifies whether the border image should be repeated, rounded or stretched. |
border-image-slice | Specifies the inward offsets of the image-border. |
border-image-source | Specifies the location of the image to be used as a border. |
border-image-width | Specifies the width of the imageborder. |
border-left | Sets the width, style, and color of the left border of an element. |
border-left-color | Sets the color of the left border of an element. |
border-left-style | Sets the style of the left border of an element. |
border-left-width | Sets the width of the left border of an element. |
border-radius | Defines the shape of the border corners of an element. |
border-right | Sets the width, style, and color of the right border of an element. |
border-right-color | Sets the color of the right border of an element. |
border-right-style | Sets the style of the right border of an element. |
border-right-width | Sets the width of the right border of an element. |
border-style | Sets the style of the border on all the four sides of an element. |
border-top | Sets the width, style, and color of the top border of an element. |
border-top-color | Sets the color of the top border of an element. |
border-top-left-radius | Defines the shape of the top-left border corner of an element. |
border-top-right-radius | Defines the shape of the top-right border corner of an element. |
border-top-style | Sets the style of the top border of an element. |
border-top-width | Sets the width of the top border of an element. |
border-width | Sets the width of the border on all the four sides of an element. |
height | Defines the height of an element. |
max-height | Defines the maximum height of an element. |
max-width | Defines the maximum width of an element. |
min-height | Defines the minimum height of an element. |
min-width | Defines the minimum width of an element. |
width | Specify the width of an element. |
Content | Inserts generated content. |
quotes | Specifies quotation marks for embedded quotations. |
counter-reset | Creates or resets one or more counters. |
counter-increment | Increments one or more counter values. |
align-content | Specifies the alignment of flexible container’s items. |
align-items | Specifies the default alignment for items. |
align-self | Specifies the alignment for selected items. |
flex | Specifies the components of a flexible length. |
flex-basis | Specifies the initial main size of the flex item. |
flex-direction | Specifies the direction of the flexible items. |
flex-flow | A shorthand property for the flexdirection and the flex-wrap properties. |
flex-grow | Specifies how the flex item will grow relative to the other items inside the flex container. |
flex-shrink | Specifies how the flex item will shrink relative to the other items inside the flex container. |
flex-wrap | Specifies whether the flexible items should wrap or not. |
justify-content | Specifies how flex items are aligned along the main axis of the flex container after any flexible lengths and auto margins have been resolved. |
order | Specifies the order in which a flex items are displayed and laid out within a flex container. |
font | Defines a variety of font properties within one declaration like the font-style, font-variant, font-weight, font-size/line-height, and the font-family. |
font-family | Defines a list of fonts for element. |
font-size | Defines the font size for the text. |
font-size-adjust | Preserves the readability of text when font fallback occurs. |
font-stretch | Selects a normal, condensed, or expanded face from a font. |
font-style | Defines the font style for the text. |
font-variant | Specify the font variant. |
font-weight | Specify the font weight of the text. |
list-style | Defines the display style for a list and list elements. |
list-style-image | Specifies the image to be used as a list-item marker. |
list-style-position | Specifies the position of the list item marker. |
list-style-type | Specifies the marker style for a list-item. |
margin | Sets the margin on all four sides of the element. |
margin-bottom | Sets the bottom margin of the element. |
margin-left | Sets the left margin of the element. |
margin-right | Sets the right margin of the element. |
margin-top | Sets the top margin of the element. |
column-count | Specifies the number of columns in a multi-column element. |
column-fill | Specifies how columns will be filled. |
column-gap | Specifies the gap between the columns in a multi-column element. |
column-rule | Specifies a straight line, or “rule”, to be drawn between each column in a multi-column element. |
column-rule-color | Specifies the color of the rules drawn between columns in a multi-column layout. |
column-rule-style | Specifies the style of the rule drawn between the columns in a multi-column layout. |
column-rule-width | Specifies the width of the rule drawn between the columns in a multi-column layout. |
column-span | Specifies how many columns an element spans across in a multicolumn layout. |
column-width | Specifies the optimal width of the columns in a multi-column element. |
columns | A shorthand property for setting column-width and column-count properties. |
column-count | Specifies the number of columns in a multi-column element. |
outline | Sets the width, style, and color for all four sides of an element’s outline. |
outline-color | Sets the color of the outline. |
outline-offset | Set the space between an outline and the border edge of an element. |
outline-style | Sets a style for an outline. |
outline-width | Sets the width of the outline. |
padding | Sets the padding on all four sides of the element. |
padding-bottom | Sets the padding to the bottom side of an element. |
padding-left | Sets the padding to the left side of an element. |
padding-right | Sets the padding to the right side of an element. |
padding-top | Sets the padding to the top side of an element. |
page-break-after | Insert a page breaks after an element. |
page-break-before | Insert a page breaks before an element. |
page-break-inside | Insert a page breaks inside an element. |
border-collapse | Specifies whether table cell borders are connected or separated. |
border-spacing | Sets the spacing between the borders of adjacent table cells. |
caption-side | Specify the position of table’s caption. |
empty-cells | Show or hide borders and backgrounds of empty table cells. |
table-layout | Specifies a table layout algorithm. |
border-collapse | Specifies whether table cell borders are connected or separated. |
direction | Define the text direction/writing direction. |
tab-size | Specifies the length of the tab character. |
text-align | Sets the horizontal alignment of inline content. |
text-align-last | Specifies how the last line of a block or a line right before a forced line break is aligned when text-align is justify. |
text-decoration | Specifies the decoration added to text. |
text-decoration-color | Specifies the color of the textdecoration- line. |
text-decoration-line | Specifies what kind of line decorations are added to the element. |
text-decoration-style | Specifies the style of the lines specified by the text-decoration-line property |
text-indent | Indent the first line of text. |
text-justify | Specifies the justification method to use when the text-align property is set to justify. |
text-overflow | Specifies how the text content will be displayed, when it overflows the block containers. |
text-shadow | Applies one or more shadows to the text content of an element. |
text-transform | Transforms the case of the text. |
line-height | Sets the height between lines of text. |
vertical-align | Sets the vertical positioning of an element relative to the current text baseline. |
letter-spacing | Sets the extra spacing between letters. |
word-spacing | Sets the spacing between words. |
white-space | Specifies how white space inside the element is handled. |
word-break | Specifies how to break lines within words. |
word-wrap | Specifies whether to break words when the content overflows the boundaries of its container. |
backface-visibility | Specifies whether or not the “back” side of a transformed element is visible when facing the user. |
perspective | Defines the perspective from which all child elements of the object are viewed. |
perspective-origin | Defines the origin (the vanishing point for the 3D space) for the perspective property. |
transform | Applies a 2D or 3D transformation to an element. |
transform-origin | Defines the origin of transformation for an element. |
transform-style | Specifies how nested elements are rendered in 3D space. |
transition | Defines the transition between two states of an element. |
transition-delay | Specifies when the transition effect will start. |
transition-duration | Specifies the number of seconds or milliseconds a transition effect should take to complete. |
transition-property | Specifies the names of the CSS properties to which a transition effect should be applied. |
transition-timing-function | Specifies the speed curve of the transition effect. |
display | Specifies how an element is displayed onscreen. |
position | Specifies how an element is positioned. |
top | Specify the location of the top edge of the positioned element. |
right | Specify the location of the right edge of the positioned element. |
bottom | Specify the location of the bottom edge of the positioned element. |
left | Specify the location of the left edge of the positioned element. |
float | Specifies whether or not a box should float. |
clear | Specifies the placement of an element in relation to floating elements. |
z-index | Specifies a layering or stacking order for positioned elements. |
overflow | Specifies the treatment of content that overflows the element’s box. |
overflow-x | Specifies how to manage the content when it overflows the width of the element’s content area. |
overflow-y | Specifies how to manage the content when it overflows the height of the element’s content area. |
resize | Specifies whether or not an element is resizable by the user. |
clip | Defines the clipping region. |
visibility | Specifies whether or not an element is visible. |
cursor | Specify the type of cursor. |
box-shadow | Applies one or more drop-shadows to the element’s box. |
box-sizing | Alter the default CSS box model. |
animation | Specifies the behavior of all animations. |
animation-delay | Specifies when the animation will start with a delay. |
animation-direction | Specifies whether the animation should play forward, backward, or in alternate cycles. |
animation-duration | Specifies the number of seconds or milliseconds an animation should take to complete one cycle. |
animation-fill-mode | Specifies how a CSS animation should apply styles to its target before and after it is executing. |
animation-iteration-count | Specifies the number of times an animation cycle should be played before stopping. |
animation-name | Specifies the name of @keyframes defined animations that should be applied to the selected element. |
animation-play-state | Specifies whether the animation is running or paused. |
animation-timing-function | Specifies how a CSS animation should progress over the duration of each cycle. |
HTML Essentials
<html>…</html> | The first and last tag of an HTML document. All other tags lie between these opening and closing tags. |
<head>…</head> | Specifies the collection of metadata for the document. |
<title>…</title> | Describes the title for the page and shows up in the browser’s title bar. |
<body>…</body> | Includes all content that will be displayed on the webpage. |
<base/> | Mentions the base URL and all relative links to the document. |
<meta/> | For extra information about the page like author, publish date, etc. |
<link/> | Links to external elements like style sheets. |
<style>…</style> | Contains document style information like CSS (Cascading Style Sheets). |
<script>…</script> | Contains links to external scripts. |
<strong>…</strong> OR <b>…</b> | Makes text bold. |
<em>…</em> | Italicizes text and makes it bold. |
<i>…</i> | Italicizes text but does not make it bold. |
<strike>…</strike> | Strikethrough text. |
<cite>…</cite> | Cites an author of a quote. |
<del>…</del> | Labels a deleted portion of a text. |
<ins>…</ins> | Shows a section that has been inserted into the content. |
<blockquote>…</blockquote> | For displaying quotes. Often used with the <cite> tag. |
<q>…</q> | For shorter quotes. |
<abbr>…</abbr> | For abbreviations and full-forms. |
<address>…</address> | Specifies contact details. |
<dfn>…</dfn> | For definitions. |
<code>…</code> | For code snippets. |
<sub>…</sub> | For writing subscripts. |
<sup>…</sup> | For writing superscripts. |
<small>…</small> | For reducing the text size and marking redundant information in HTML5. |
<h1…h6>…</h1…h6> | Different levels of headings. H1 is the largest and H6 is the smallest. |
<div>…</div> | For dividing content into blocks. |
<span>…</span> | Includes inline elements, like an image, icon, emoticon, without ruining the formatting of the page. |
<p>…</p> | Contains plain text. |
<br/> | Creates a new line. |
<hr/> | Draws a horizontal bar to show end of the section. |
<ol>…</ol> | For ordered list of items. |
<ul>…</ul> | For unordered list of items. |
<li>…</li> | For individual items in a list. |
<dl>…</dl> | List of items with definitions. |
<dt>…</dt> | The definition of a single term inline with body content. |
<dd>…</dd> | The description for the defined term. |
<a href=””>…</a> | Anchor tag for hyperlinks. |
<a href=”mailto:”>…</a> | Tag for linking to email addresses. |
<a href=”tel://###-###”>…</a> | Anchor tag for listing contact numbers. |
<a name=”name”>…</a> | Anchor tag for linking to another part of the same page. |
<a href=”#name”>…</a> | Navigates to a div section of the webpage. (Variation of the above tag) |
<img /> | For displaying image files. |
Attribute for the <img> tag | |
src=”url” | Link to the source path of the image. |
alt=”text” | The text displayed when a mouse is hovered over the image. |
height=”” | Image height in pixels or percentages. |
width=”” | Image width in pixels or percentages. |
align=”” | Relative alignment of the image on the page. |
border=”” | Border thickness of the image. |
<map>…</map> | Link to a clickable map. |
<map name=””>…</map> | Name of the map image. |
<area /> | The image area of an image map. |
Attribute for the <area> tag | |
shape=”” | Shape of the image area. |
coords=”” | Coordinates of the map image area. |
<form>…</form> | The parent tag for an HTML form. |
Attributes for the <form> tag | |
action=”url” | The URL where form data is submitted. |
method=”” | Specifies the form submission protocol (POST or GET). |
enctype=”” | The data encoding scheme for POST submissions. |
autocomplete | Specifies if form autocomplete is on or off. |
novalidate | Specifies whether the form should be validated before submission. |
accept-charsets | Specifies character encoding for form submissions. |
target | Shows where the form submission response will be displayed. |
<fieldset>…</fieldset> | Groups related elements in the form/ |
<label>…</label> | Specifies what the user should enter in each form field. |
<legend>…</legend> | A caption for the fieldset element. |
<input /> | Specifies what type of input to take from the user. |
Attributes for the <input> tag | |
type=”” | Determines the type of input (text, dates, password). |
name=”” | Specifies the name of the input field. |
value=”” | Specifies the value in the input field. |
size=”” | Sets the number of characters for the input field. |
maxlength=”” | Sets the limit of input characters allowed. |
required | Makes an input field compulsory. |
width=”” | Sets width of the input field in pixels. |
height=”” | Sets height of the input field in pixels. |
placeholder=”” | Describes expected field value. |
pattern=”” | Specifies a regular expression, which can be used to look for patterns in the user’s text. |
min=”” | The minimum value allowed for an input element. |
max=”” | The maximum value allowed for an input element. |
disabled | Disables the input element. |
<textarea>…</textarea> | For capturing longer strings of data from the user. |
<select>…</select> | Specifies a list of options which the user can choose from. |
Attributes for the <select> tag | |
name=”” | Specifies name for a dropdown list. |
size=”” | Number of options given to the user. |
multiple | Sets whether the user can choose multiple options from the list. |
required | Specifies whether choosing an option/s is necessary for form submission. |
autofocus | Specifies that a drop-down list automatically comes into focus after a page loads. |
<option>…</option> | Defines items in a dropdown list. |
value=”” | Displays the text for any given option. |
selected | Sets default option that is displayed. |
<button>…</button> | Tag for creating a button for form submission. |
<object>…</object> | Describes the embedded filetype. |
Attributes for the <object> tag | |
height=”” | The height of the object. |
width=”” | The width of the object. |
type=”” | The type of media the object contains. |
<iframe>…</iframe> | An inline frame for embedding external information. |
name=”” | The name of the iFrame. |
src=”” | The source URL for the content inside the frame. |
srcdoc=”” | The HTML content within the frame. |
height=”” | The height of the iFrame. |
width=”” | The width of the iFrame. |
<param /> | Adds extra parameters to customize the iFrame. |
<embed>…</embed> | Embeds external application or plugin. |
Attributes for the <object> tag | |
height=”” | Sets the height of the embed. |
width=”” | Sets the width of the embed. |
type=”” | The type or format of the embed. |
src=”” | The source path of the embedded file. |
<table>…</table> | Defines all content for a table. |
<caption>…</caption> | A description of the table. |
<thead>…</thead> | Headers for each column in the table. |
<tbody>…</tbody> | Defines the body data for the table. |
<tfoot>…</tfoot> | Describes the content for the table’s footer. |
<tr>…</tr> | Content for a single row. |
<th>…</th> | The data in a single header item. |
<td>…</td> | Content within a single table cell. |
<colgroup>…</colgroup> | Groups columns for formatting. |
<col> | A single column of information. |
<header>…</header> | Specifies the webpage header. |
<footer>…</footer> | Specifies the webpage footer. |
<main>…</main> | Marks main content of the webpage. |
<article>…</article> | Specifies an article. |
<aside>…</aside> | Specifies sidebar content of a page. |
<section>…</section> | Specifies a particular section in the webpage. |
<details>…</details> | For describing extra information. |
<summary>…</summary> | Used as a heading for the above tag. Is always visible to the user. |
<dialog>…</dialog> | Creates a dialog box. |
<figure>…</figure> | Used for including charts and figures. |
<figcaption>…</figcaption> | Describes a <figure> element. |
<mark>…</mark> | Highlights a specific part of the text. |
<nav>…</nav> | Set of navigation links on a webpage. |
<menuitem>…</menuitem> | A particular item from a list or a menu. |
<meter>…</meter> | Measures data within a given range. |
<progress>…</progress> | Places a progress bar and tracks progress. |
<rp>…</rp> | Displays text that do not support Ruby annotations. |
<rt>…</rt> | Displays East Asia typography character details. |
<ruby>…</ruby> | A Ruby annotation for East Asian typography. |
<time>…</time> | Identifies time and date. |
<wbr> | A line break within the content. |
" " | Quotation Marks |
< < | Lesser than sign (<) |
> > | Greater than sign (>) |
  | Non-breaking space |
© © | Copyright symbol |
™ û | Trademark symbol |
@ Ü | “at” symbol (@) |
& & | Ampersand symbol (&) |
• ö | Small bullet |
Javascript Commands
Concat() | Join several arrays into one |
copyWithin() | Copy array elements within the array, to and from specified positions |
idexOf() | Return the primitive value of the specified object |
includes() | Check if an array contains the specified element |
join() | Combine elements of an array into a single string and return the string |
entries() | Return a key/value pair Array Iteration Object |
every() | Check if every element in an array passes a test |
fill() | Fill the elements in an array with a static value |
filter() | Create a new array with every element in an array that pass a test |
find() | Return the value of the first element in an array that pass a test |
forEach() | Call a function for each array element |
from() | Create an array from an object |
lastIndexOf() | Give the last position at which a given element appears in an array |
pop() | Remove the last element of an array |
push() | Add a new element at the end |
reverse() | Sort elements in descending order |
reduce() | Reduce the values of an array to a single value (going left-to-right) |
reduceRight() | Reduce the values of an array to a single value (going right-to-left) |
shift() | Remove the first element of an array |
slice() | Pull a copy of a portion of an array into a new array of 4 24 |
sort() | Sort elements alphabetically |
splice() | Add elements in a specified way and position |
unshift() | Add a new element to the beginning |
toString() | Convert a Boolean value to a string, and return the result |
valueOf() | Return the first position at which a given element appears in an array |
toSource() | Return a string representing the source code of the object |
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
(…) | Grouping operator (operations within brackets are executed earlier than those outside) |
% | Modulus (remainder) |
++ | Increment numbers |
— | Decrement numbers |
== | Equal to |
=== | Equal value and equal type |
!= | Not equal |
!== | Not equal value or not equal type |
> | Greater than |
< | Lesser than |
>= | Greater than or equal to |
<= | Lesser than or equal to |
? | Ternary operator |
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
& | AND statement |
| | OR statement |
~ | NOT |
^ | XOR |
<< | Left shift |
>> | Right shift |
>>> | Zero fill right shift |
alert() | Output data in an alert box in the browser window |
confirm() | Open up a yes/no dialog and return true/false depending on user click |
console.log() | Write information to the browser console (good for debugging purposes) |
document.write() | Write directly to the HTML document |
prompt() | Create a dialog for user input |
decodeURI() | Decode a Uniform Resource Identifier (URI) created by encodeURI or similar |
decodeURIComponent() | Decode a URI component |
encodeURI() | Encode a URI into UTF-8 |
encodeURIComponent() | Same but for URI components |
eval() | Evaluate JavaScript code represented as a string |
isFinite() | Determine whether a passed value is a finite number |
isNaN() | Determine whether a value is an illegal number |
Number() | Convert an object’s value to a number |
parseFloat() | Parse a string and return a floating point number |
parseInt() | Parse a string and return an integer |
for | The most common way to create a loop in JavaScript |
while | Set up conditions under which a loop executes |
do while | Similar to the while loop, however, it executes at least once and performs a check at the end to see if the condition is met to execute again |
break | Stop and exit the cycle if certain conditions are mets |
continue | Skip parts of the cycle if certain conditions are met |
\’ | Single quote |
\” | Double quote |
\\ | Backslash |
\b | Backspace |
\f | Form feed |
\n | New line |
\r | Carriage return |
\t | Horizontal tabulator |
\v | Vertical tabulator |
charAt() | Return a character at a specified position inside a string |
charCodeAt() | Give the unicode of character at that position |
concat() | Concatenate (join) two or more strings into one |
fromCharCode() | Return a string created from the specified sequence of UTF-16 code units |
indexOf() | Provide the position of the first occurrence of specified text within a string |
lastIndexOf() | Same as indexOf() but with the last occurrence, searching backwards |
match() | Retrieve the matches of a string against a search pattern |
replace() | Find and replace specified text in a string |
search() | Execute a search for a matching text and return its position |
slice() | Extract a section of a string and return it as a new string |
split() | Split a string object into an array of strings at a specified position |
startsWith() | Check whether a string begins with specified characters |
substr() | Similar to slice() but extracts a substring depended on a specified number of characters |
substring() | Similar to slice() but can’t accept negative indices |
toLowerCase() | Convert strings to lowercase |
toUpperCase() | Convert strings to uppercase |
valueOf() | Return the primitive value (that has no properties or methods) of a string object |
e | Evaluate replacement |
i | Perform case-insensitive matching |
g | Perform global matching |
m | Perform multiple line matching |
s | Treat strings as single line |
x | Allow comments and whitespace in pattern |
U | Ungreedy pattern |
[abc] | Find any of the characters in the brackets |
[^abc] | Find any character not in the brackets |
[0-9] | Find digit specified in the brackets |
[A-z] | Find any character from uppercase A to lowercase z |
(a|b|c) | Find any of the alternatives separated with | |
. | Find a single character, except newline or line terminator |
\w | Word character |
\W | Non-word character |
\d | A digit |
\D | A non-digit character |
\s | Whitespace character |
\S | Non-whitespace character |
\b | Find a match at the beginning/end of a word |
\B | Find a match not at the beginning/end of a word |
\0 | NUL character |
\n | A new line character |
\f | Form feed character |
\r | Carriage return character |
\t | Tab character |
\v | Vertical tab character |
\xxx | Character specified by an octal number xxx |
\xdd | Latin character specified by a hexadecimal number dd |
\udddd | Unicode character specified by a hexadecimal number dddd |
n+ | Match any string that contains at least one n |
n* | Any string that contains zero or more occurrences of n |
n? | Any string that contains zero or one occurrences of n |
n{X} | Any string that contains a sequence of X n’s |
n{X,Y} | Strings that contains a sequence of X to Y n’s |
n{X,} | Matches any string that contains a sequence of at least X n’s |
n$ | Any string with n at the end of it |
^n | String with n at the beginning of it |
?=n | Any string that is followed by a specific string n |
?!n | String that is not followed by a specific string n |
MAX_VALUE | Maximum numeric value representable in JavaScript |
MIN_VALUE | Smallest positive numeric value representable in JavaScript |
NaN | “Not-a-Number” value |
NEGATIVE_INFINITY | Negative Infinity value |
POSITIVE_INFINITY | Positive Infinity value |
toExponential() | Return a string with a rounded number written as exponential notation |
toFixed() | Return string of a number with a specified number of decimals |
toPrecision() | Return string of a number written with a specified length |
toString() | Return a number as a string |
valueOf() | Return a number as a number |
E | Euler’s number |
LN2 | Natural logarithm of 2 |
LN10 | Natural logarithm of 10 |
LOG2E | Base 2 logarithm of E |
LOG10E | Base 10 logarithm of E |
PI | The number PI |
SQRT1_2 | Square root of 1/2 |
SQRT2 | Square root of 2 |
abs(x) | Return the absolute (positive) value of x |
acos(x) | Arccosine of x, in radians |
asin(x) | Arcsine of x, in radians |
atan(x) | Arctangent of x as a numeric value |
atan2(y,x) | Arctangent of the quotient of its arguments |
ceil(x) | Value of x rounded up to its nearest integer |
cos(x) | Cosine of x (x is in radians) |
exp(x) | Value of Ex |
floor(x) | Value of x rounded down to its nearest integer |
log(x) | Natural logarithm (base E) of x |
max(x,y,z,…,n) | Number with highest value |
min(x,y,z,…,n) | Number with lowest value |
pow(x,y) | X to the power of y |
random() | Random number between 0 and 1 |
round(x) | Value of x rounded to its nearest integer |
sin(x) | Sine of x (x is in radians) |
sqrt(x) | Square root of x |
tan(x) | Tangent of an angle |
Date() | Create a new date object with the current date and time |
Date(2017, 5, 21, 3, 23, 10, 0) | Create a custom date object. The numbers represent year, month, day, hour, minutes, seconds, milliseconds. You can omit anything you want except for year and month. |
Date(“2017-06-23”) | Date declaration as a string |
getDate() | Get the day of the month as a number (1-31) |
getDay() | Get the weekday as a number (0-6) |
getFullYear() | Get the year as a four digit number (yyyy) |
getHours() | Get the hour (0-23) |
getMiliseconds() | Get the millisecond (0-999) |
getMinutes() | Get the minute (0-59) |
getMonth() | Get the month as a number (0-11) |
getSeconds() | Get the second (0-59) |
getTime() | Get the time (milliseconds since January 1, 1970) |
getUTCDate() | Day (date) of the month in the specified date according to universal time (also available for day, month, fullyear, hours, minutes etc.) |
parse | Parse a string representation of a date, and return the number of milliseconds since January 1, 1970 |
setDate() | Set the day as a number (1-31) |
setFullYear() | Set the year (optionally month and day) |
setHours() | Set the hour (0-23) |
setMiliseconds() | Set the milliseconds (0-999) |
setMinutes() | Set the minutes (0-59) |
setMonth() | Set the month (0-11) |
setSeconds() | Set the seconds (0-59) |
setTime() | Set the time (milliseconds since January 1, 1970) |
setUTCDate() | Set the day of the month for a specified date according to universal time (also available for day, month, fullyear, hours, minutes etc.) |
attributes | Live collection of all attributes registered to an element |
baseURI | Absolute base URL of an HTML element |
childNodes | Collection of an element’s child nodes |
firstChild | First child node of an element |
lastChild | Last child node of an element |
nextSibling | Next node at the same node tree level |
nodeName | Name of a node |
nodeType | Type of a node |
nodeValue | Value of a node |
ownerDocument | Top-level document object for current node |
parentNode | Parent node of an element |
previousSibling | Node immediately preceding the current one |
textContent | Textual content of a node and its descendants |
appendChild() | Add a new child node to an element as the last child node |
cloneNode() | Clone HTML element |
compareDocumentPosition() | Compare the document position of two elements |
getFeature() | Return an object which implements the APIs of a specified feature |
hasAttributes() | Return true if an element has any attributes, else return false |
hasChildNodes() | Return true if an element has any child nodes, else return false |
insertBefore() | Insert a new child node before a specified, existing child node |
isDefaultNamespace() | Return true if a specified namespaceURI is the default, else return false |
isEqualNode() | Check if two elements are equal |
isSameNode() | Check if two elements are the same node |
isSupported() | Return true if a specified feature is supported on the element |
lookupNamespaceURI() | Return the namespaceURI associated with a given node |
lookupPrefix() | Return a DOMString containing the prefix for a given namespaceURI, if present |
normalize() | Join adjacent text nodes and remove empty text nodes in an element |
removeChild() | Remove a child node from an element |
replaceChild() | Replace a child node in an element |
getAttribute() | Return the specified attribute value of an element node |
getAttributeNS() | Return string value of the attribute with the specified namespace and name |
getAttributeNode() | Get the the specified attribute node |
getAttributeNodeNS() | Return the attribute node for the attribute with the given namespace and name |
getElementsByTagName() | Provide a collection of all child elements with the specified tag name |
getElementsByTagNameNS() | Return a live HTML collection of elements with a certain tag name belonging to the given namespace |
hasAttribute() | Return true if an element has any attributes, else return false |
hasAttributeNS() | Provide a true/false value indicating whether the current element in a given namespace has the specified attribute |
removeAttribute() | Remove a specified attribute from an element |
removeAttributeNS() | Remove the specified attribute from an element within a certain namespace |
removeAttributeNode() | Take away a specified attribute node and return the removed node |
setAttribute() | Set or change the specified attribute to a specified value |
setAttributeNS() | Add a new attribute or change the value of an attribute with the given namespace and name |
setAttributeNode() | Set or change the specified attribute node |
setAttributeNodeNS() | Add a new namespaced attribute node to an element |
closed | Check whether a window has been closed or not and return true or false |
defaultStatus | Set or return the default text in the statusbar of a window |
document | Return the document object for the window |
frames | Return all <frame> elements in the current window |
history | Provide the History object for the window |
innerHeight | Inner height of a window’s content area |
innerWidth | Inner width of the content area |
length | Return the number of <frame> elements in the window |
location | Return the location object for the window |
name | Set or return the name of a window |
navigator | Return the Navigator object for the window |
opener | Return a reference to the window that created the window |
outerHeight | Outer height of a window, including toolbars/scrollbars |
outerWidth | Outer width of a window, including toolbars/scrollbars |
pageXOffset | Number of pixels by which the document has been scrolled horizontally |
pageYOffset | Number of pixels by which the document has been scrolled vertically |
parent | Parent window of the current window |
screen | Return the Screen object for the window |
screenLeft | Horizontal coordinate of the window (relative to screen) |
screenTop | Vertical coordinate of the window |
screenX | Same as screenLeft but needed for some browsers |
screenY | Same as screenTop but needed for some browsers |
self | Return the current window |
status | Set or return the text in the statusbar of a window |
top | Return the topmost browser window |
alert() | Display an alert box with a message and an OK button |
blur() | Remove focus from the current window |
clearInterval() | Clear a timer set with setInterval() |
clearTimeout() | Clear a timer set with setTimeout() |
close() | Close the current window |
confirm() | Display a dialog box with a message and OK and Cancel buttons |
focus() | Set focus to the current window |
moveBy() | Move a window relative to its current position |
moveTo() | Move a window to a specified position |
open() | Open a new browser window |
print() | Print the content of the current window |
prompt() | Display a dialog box that prompts the visitor for input |
resizeBy() | Resize the window by the specified number of pixels |
resizeTo() | Resize the window to a specified width and height |
scrollBy() | Scroll the document by a specified number of pixels |
scrollTo() | Scroll the document to specified coordinates |
setInterval() | Call a function or evaluate an expression at specified intervals |
setTimeout() | Call a function or evaluate an expression after a specified interval |
stop() | Stop the window from loading |
availHeight | Return the height of the screen (excluding the Windows Taskbar) |
availWidth | Return the width of the screen (excluding the Windows Taskbar) |
colorDepth | Return the bit depth of the color palette for displaying images |
height | The total height of the screen |
pixelDepth | The color resolution of the screen in bits per pixel |
width | The total width of the screen |
onclick | When user clicks on an element |
oncontextmenu | When user right-clicks on an element to open a context menu |
ondblclick | When user double-clicks on an element |
onmousedown | When user presses a mouse button over an element |
onmouseenter | When user moves pointer onto an element |
onmouseleave | When user moves pointer away from an element |
onmousemove | When user moves pointer while it is over an element |
onmouseover | When user moves pointer onto an element or one of its children |
onmouseout | When user moves pointer away from an element or one of its children |
onmouseup | When user releases a mouse button while over an element |
onkeydown | When user is pressing a key down |
onkeypress | When user starts pressing a key |
onkeyup | When user releases a key |
onabort | When loading of media is aborted |
onbeforeunload | Before the document is about to be unloaded |
onerror | When an error occurs while loading an external file |
onhashchange | When the anchor part of a URL has changed |
onload | When an object has loaded |
onpagehide | When user navigates away from a webpage |
onpageshow | When user navigates to a webpage |
onresize | When user resizes document view |
onscroll | When user is scrolling an element’s scrollbar |
onunload | When a page has unloaded |
onblur | When an element loses focus |
onchange | When the content of a form element changes (for <input>, <select>, and <textarea>) |
onfocus | When an element gets focus |
onfocusin | When an element is about to get focus |
onfocusout | When an element is about to lose focus |
oninput | User input on an element |
oninvalid | When an element is invalid |
onreset | When a form is reset |
onsearch | When a user types something in a search field (for <input=”search”>) |
onselect | When user selects some text (for <input> and <textarea>) |
onsubmit | When a form is submitted |
ondrag | When user drags an element |
ondragend | When user has finished dragging the element |
ondragenter | When the dragged element enters a drop target |
ondragleave | When the dragged element leaves the drop target |
ondragover | When the dragged element is on top of the drop target |
ondragstart | When user starts to drag an element |
ondrop | Dragged element is dropped on the drop target |
oncopy | When user copies content of an element |
oncut | When user cuts an element’s content |
onpaste | When user pastes content in an element |
onabort | When media loading is aborted |
oncanplay | When browser can start playing media (e.g. a file has buffered enough) |
oncanplaythrough | When browser can play through media without stopping |
ondurationchange | When duration of media changes |
onended | When media has reached its end |
onerror | When an error occurs while loading an external file |
onloadeddata | When media data is loaded |
onloadedmetadata | When metadata (like dimensions and duration) is loaded |
onloadstart | When browser starts looking for specified media |
onpause | When media is paused either by user or automatically |
onplay | When media has been started or is no longer paused |
onplaying | When media is playing after having been paused or stopped for buffering |
onprogress | When browser is in the process of downloading media |
onratechange | When playing speed of media changes |
onseeked | When user has finished moving/skipping to a new position in media |
onseeking | When user starts moving/skipping |
onstalled | When browser is trying to load unavailable media |
onsuspend | When browser is intentionally not loading media |
ontimeupdate | The playing position has changed (e.g. because of fast forward) |
onvolumechange | When media volume has changed (including mute) |
onwaiting | When media has paused but is expected to resume (for example, buffering) |
animationend | When CSS animation is complete |
animationiteration | When CSS animation is repeated |
animationstart | When CSS animation has started |
transitionend | When CSS transition is complete |
onmessage | When a message is received through the event source |
onoffline | When browser starts to work offline |
ononline | When browser starts to work online |
onpopstate | When the window’s history changes |
onshow | When a <menu> element is shown as a context menu |
onstorage | When a Web Storage area is updated |
ontoggle | When user opens or closes the <details> element |
onwheel | When mouse wheel rolls up or down over an element |
ontouchcancel | When screen touch is interrupted |
ontouchend | When user’s finger goes off touch screen |
ontouchmove | When user drags a finger across the screen |
Visual Studio Code Shortcuts
Open Command Palette | Ctrl + Shift + P |
Open app settings | Ctrl + , |
Display keyboard shortcuts | Ctrl + K, Ctrl + S |
Switch to Extensions pane | Ctrl + Shift + X |
New file | Ctrl + N |
New window | Ctrl + Shift + N |
Close file | Ctrl + F4 |
Close window | Ctrl + Shift + F4 |
Toggle Full Screenmode | F11 |
Toggle sidebar visibility | Ctrl + B |
Open file | Ctrl + O |
Save file | Ctrl + S |
Save as… | Ctrl + Shift + S |
Save all files | Ctrl + K, S |
Close all | Ctrl + K, Ctrl + W |
Reopen last closed | Ctrl + Shift + T |
Copy selection or current line | Ctrl + C |
Cut selection or current line | Ctrl + X |
Paste | Ctrl + V |
Delete line | Ctrl + Shift + K |
Go to beginning of line | Home |
Go to end of line | End |
Go to beginning of file | Ctrl + Home |
Go to end of file | Ctrl + End |
Move line up or down | Alt + Up/Down |
Indent line | Ctrl + ] |
Outdent line | Ctrl + [ |
Comment out line | Ctrl + / |
Comment out region | Shift + Alt + A |
Fold region | Ctrl + Shift + [ |
Unfold region | Ctrl + Shift + ] |
Fold all subregions | Ctrl + K, Ctrl + [ |
Unfold all subregions | Ctrl + K, Ctrl + ] |
Fold all regions | Ctrl + K, Ctrl + O |
Unfold all regions | Ctrl + K, Ctrl + J |
Go to file | Ctrl + P |
Go to line | Ctrl + G |
Show all symbols | Ctrl + T |
Go to symbol | Ctrl + Shift + O |
Go to next error or warning | F8 |
Go to previous error or warning | Shift + F8 |
Show Problems panel | Ctrl + Shift + M |
Go back | Alt + Left |
Go forward | Alt + Right |
Open Find dialog | Ctrl + F |
Open Replace dialog | Ctrl + H |
Replaces in files | Ctrl + Shift + H |
Find next | F3 |
Find previous | Shift + F3 |
Select all matches for search term | Alt + Enter |
Add current selection to Find match | Ctrl + D |
Move previous selection to next Find match | Ctrl + K, Ctrl + D |
Select current line | Ctrl + L |
Select all instances of current selection | Ctrl + Shift + L |
Select all matches of current word | Ctrl + F2 |
Expand selection | Shift + Alt + Right Arrow |
Shrink selection | Shift + Alt + Left Arrow |
Insert cursor | Alt + Click |
Insert cursor above or below current line | Ctrl + Alt + Up/Down Arrow |
Undo last cursor | Ctrl + U |
Insert cursor at the end of each selected line | Shift + Alt + I |
Split editor | Ctrl + \ |
Focus on editor pane 1, 2, or 3 | Ctrl + 1/2/3 |
Focus on next/previous editor pane | Ctrl + K, Ctrl + Right/Left Arrow |
Move editor left | Move editor left |
Move editor right | Move editor right |
Show integrated terminal | Ctrl + ‘ |
Create new terminal instance | Ctrl + Shift + ‘ |
Scroll up/down | Ctrl + Up/Down Arrow |
Scroll to top/bottom | Ctrl + Home/End |
Close file | Cmd + W |
Toggle full screen | Cmd + Ctrl + F |
Go back | Cmd + – |
Go forward | Cmd + Shift + – |
Find next | Cmd + G |
Find previous | Cmd + Shift + G |
Expand selection | Cmd + Ctrl + Shift + Right Arrow |
Shrink selection | Cmd + Ctrl + Shift + Left Arrow |
Move editor left | Cmd + K, Cmd + Shift + Left |
Move editor right | Cmd + K, Cmd + Shift + Right |
Show integrated terminal | Ctrl + ‘ |
Create new terminal instance | Ctrl + Shift + ‘ |
Raspberry Pi Commands
Command | Result |
---|---|
cat [name] | Show the contents of the file [name] |
cd .. | Change to parent directory |
cd [path] | Move to the directory at [path] |
cd / | Change to root directory |
cd ~ | Change to your home directory – usually “/home/<username>” |
chmod [who][+,-,=][permissions] [name] | Change the permissions for a file |
chmod 777 [name] | Allow all users to read, write and execute the file [name] |
chmod u+x [name] | Allow the user to execute [name] |
cp -r [from] [to] | Copy all files and subdirectories from source [from] to destination [to] |
cp [from] [to] | Copy a file from source [from] to destination [to] |
find | Search for files and their contents |
grep ‘string’ [name] | Search inside one or more files for occurrences of ‘string’ |
head [name] | Return all occurrences of ‘string’ within file [name] |
ls | List the contents of the current directory |
ls -a | List all files including hidden files |
ls -l | List the contents of the current directory with more file information |
ls [path] | List the contents of the directory found at [path] |
man [command] | Open the manual/help page for [command] |
man man | Open the manual/help page for the ‘man’ command (helpception) |
mkdir [name] | Create a directory called [name] in the current working directory |
mv -r [from] [to] | Move all files and directories from source [from] to destination [to] |
mv [from] [to] | Move a file from source [from] to destination [to] |
pwd | Show the name of the current working directory |
python/python3 –version | Shows you what version of Python you currently have installed |
rm -r * | Remove all files and directories from the current working directory |
rm [name] | Remove the specified file |
rm * | Remove all files from the current working directory |
rmdir [name] | Remove the empty directory [name] from the current working directory |
sudo [command] | Superuser do. Execute [command] with elevated privileges (Allows you to do things you usually wouldn’t have access to) |
sudo apt-get install [package] | Install a package |
sudo apt-get update | Update the list of packages |
sudo apt-get upgrade | Upgrade the installed packages – must be run after sudo apt-get update |
sudo chown pi:root [name] | Change the owner of the file [name] to user ‘pi’ and set the group to ‘root’ |
sudo raspi-config | Launch the Raspberry Pi configuration menu |
sudo reboot | Safely restart your Pi |
sudo shutdown -h now | Safely shutdown your Pi immediately |
sudo su | Places you in the root directory with root user access – be careful with this! |
tail [name] | Show the end of file [name] |
tar -cvzf [name] [path] | Create compressed file [name] from the contents of [path] |
tar -xvzf [name] | Extract the contents of the compressed file [name] |
wget [uri] | Download the file found at [uri] on the internet |
Command | Result |
---|---|
import RPi.GPIO as GPIO | Import the RPi.GPIO module into the python sketch |
GPIO.setmode(GPIO.BCM) | Use Broadcom pin numbers (GPIO 14, GPIO 15 etc) |
GPIO.setmode(GPIO.BOARD) | Use board pin numbers (4,5, 8 etc) |
GPIO.getmode() | Returns current pin numbering mode (BCM, BOARD, or None) |
GPIO.setup([pin number], GPIO.IN) | Set up the pin at [pin number] to be an input |
GPIO.setup([pin number], GPIO.IN, pull_up_down=GPIO.PUD_DOWN) | Set up the pin at [pin number] to be an input with internal pull down resistance |
GPIO.setup([pin number], GPIO.IN, pull_up_down=GPIO.PUD_UP) | Set up the pin at [pin number] to be an input with internal pull up resistance |
GPIO.setup([pin number], GPIO.OUT) | Set up the pin at [pin number] to be an output |
GPIO.setup([pin number], GPIO.OUT, initial=1) | Set up the pin at [pin number] to be an output with the initial value ‘1’ |
GPIO.output([pin number], 1) | Set [pin number]’s value to 1. Note that 1, GPIO.HIGH and True are the same thing |
GPIO.output([pin number], 0) | Set [pin number]’s value to 0. Note that 0, GPIO.LOW and False are the same thing |
i = GPIO.input([pin number]) | Set the variable i to the value of [pin number] |
if GPIO.input([pin number]): | Use the value of [pin number] as a boolean in code |
GPIO.cleanup() | Reset all GPIO pins (good practice to call before leaving any program) |
GPIO.VERSION | Returns current RPi.GPIO version |
Command | Result |
---|---|
LEDs | |
from gpiozero import LED | Import the LED section of the gpiozero library |
led = LED(17) | Assign the ‘led’ variable to an LED on pin GPIO 17 |
led.on() | Turn on the LED stored in the ‘led’ variable |
led.off() | Turn off the LED stored in the ‘led’ variable |
led.toggle() | Toggle the LED stored in the ‘led’ variable (if it’s off, turn it on and vice versa) |
Motors | |
from gpiozero import Motor | Import the Motor section of the gpiozero library |
motor = Motor(17, 18) | Assign the variable ‘motor’ to a Motor object containing the forward and backward drive pin numbers |
motor.forward() | Activate the forward pin of the variable ‘motor’ |
motor.backward() | Activate the backward pin of the variable ‘motor’ |
motor.reverse() | Reverse the current motor direction |
motor.stop() | Stop the motor |
Buzzer | |
from gpiozero import Buzzer | Import the Buzzer section of the gpiozero library |
bz = Buzzer(3) | Assign the variable bz to a Buzzer on pin GPIO3 |
bz.on() | Turn the buzzer on |
bz.off() | Turn the buzzer off |
bz.toggle() | Toggle the buzzer’s state (if it’s off, turn it on and vice versa) |
Servo | |
from gpiozero import Servo | Import the Servo section of the gpiozero library |
servo = Servo(17) | Assign the ‘servo’ variable to a Servo on GPIO 17 |
servo.min() | Move the servo to its minimum value |
servo.mid() | Move the servo to its middle value |
servo.max() | Move the servo to its maximum value |
servo.value = 0.5 | Move the servo to a set numerical point (min = -1, max = 1) |
Command | Result |
---|---|
raspistill | Command to take a still image with attached camera, modify with arguments below |
–width, -w | Set image width <size> |
–height, -h | Set image height <size> |
–quality, -q | Set JPEG quality <0 to 100> (75 is most common) |
–raw, -r | Inserts raw Bayer data from the camera into the JPEG metadata |
–output, -o | Output filename <filename> (required for saving) |
–latest, -l | Add latest frame to filename <filename> |
–verbose, -v | Verbose debugging information during run |
–timeout, -t | Set a time to wait before capturing an image. |
–encoding, -e | Encoding to use for output file – jpg, gif, bmp, or png |
raspivid | Command to take a video using attached camera, modify with arguments below |
–width, -w | Set image width <size> (between 64px – 1920px) |
–height, -h | Set image height <size> (between 64px – 1080px) |
–bitrate, -b | Set bitrate in bits per second (i.e 15 Mbits/s = 15000000) |
–output, -o | Output filename <filename> (required for saving) |
–verbose, -v | Verbose debugging information during run |
–timeout, -t | Set a time to wait before capturing video |
–framerate, -fps | Specify the frames per second for recording |
SQL Commands
Command | Description | Example |
---|---|---|
SELECT | Basic query building block to retrieve data. | SELECT 1 FROM table_name; |
SELECT * | Using * with SELECT returns all columns. | SELECT * FROM table_name; |
SELECT column | Specify exact columns with their name. | SELECT column_name FROM table_name; |
SELECT table.column | Reference a column from a specific table. | SELECT table_name.column_name FROM table_name, table_2_name; |
FROM | Specify where to find data. | SELECT column_name FROM table_name; |
AS | Temporarily alias a table name or column to a new name. | SELECT new_table_name.*, column_name AS new_column FROM table_name AS new_table_name; |
WHERE | Filter results with a condition. | SELECT * FROM table_name WHERE column_name = ‘value’; |
AND | Use multiple conditions with a WHERE clause. Results must match all conditions. | SELECT * FROM table_name WHERE column_name < 10 AND column_name > 1; |
OR | Use multiple conditions with a WHERE clause. Results only need to match one condition. | SELECT * FROM table_name WHERE column_name < 10 OR column_name = 15; |
ORDER BY | Order the results by a column. The database chooses how to order. | SELECT * FROM table_name ORDER BY column_name; |
ORDER BY column ASC | Order the results by a column in ascending order. | SELECT * FROM table_name ORDER BY column_name ASC; |
ORDER BY column DESC | Order the results by a column in descending order. | SELECT * FROM table_name ORDER BY column_name DESC; |
LIMIT | Restrict the number of results returned. | SELECT * FROM table_name LIMIT 5; |
OFFSET | Skip the first OFFSET number of rows. Often used with LIMIT. | SELECT * FROM table_name LIMIT 5 OFFSET 10; |
SUBQUERY | Run a query to retrieve data for another query. | SELECT column FROM table_name where column_name IN (SELECT column_2_name FROM table_2_name); |
COUNT | Count the number of rows that match the query. | SELECT COUNT(column_name) FROM table_name; |
MAX | Return the highest value in a numeric column. | SELECT MAX(column_name) FROM table_name; |
MIN | Return the lowest value in a numeric column. | SELECT MIN(column_name) FROM table_name; |
SUM | Sum the values of a numeric column. | SELECT SUM(column_name) FROM table_name; |
AVG | Calculate the average value for a numeric column. | SELECT AVG(column_name) FROM table_name; |
HAVING | Used with aggregate functions instead of the WHERE clause. | SELECT COUNT(column_name) FROM table_name HAVING column_name > 10; |
GROUP BY | Used to refine an aggregate result. | SELECT COUNT(column_name) FROM table_name GROUP BY column_2_name; |
LIKE | Case-sensitive search for a pattern with a wildcard operator (%). | SELECT column_name FROM table_name WHERE column_name LIKE ‘%VALUE%’; |
ILIKE | Case-insensitive search for a pattern with a wildcard operator (%). | SELECT column_name FROM table_name WHERE column_name ILIKE ‘%value%’; |
BETWEEN | Search for a value between two values. Works with dates or numbers. | SELECT column_name FROM table_name WHERE column_name BETWEEN 1 AND 10; |
> | Search for values greater than a condition. | SELECT column_name FROM table_name WHERE column_name > 10; |
>= | Search for values greater or equal to a condition. | SELECT column_name FROM table_name WHERE column_name >= 10; |
< | Search for values less than a condition. | SELECT column_name FROM table_name WHERE column_name < 10; |
<= | Search for values less than or equal to a condition. | SELECT column_name FROM table_name WHERE column_name <= 10; |
= | Search for values matching a condition exactly. | SELECT column_name FROM table_name where column_name = 10; |
<> | Search for values not equal to a condition. | SELECT column_name FROM table_name WHERE column_name <> 10; |
UNION | Combine two unique queries (with the same columns) into one result. | SELECT column_name FROM table_name UNION SELECT column_2_name FROM table_2_name; |
UNION ALL | Combine two queries (with the same columns) into one result. Duplicates allowed. | SELECT column_name FROM table_name UNION ALL SELECT column_2_name FROM table_2_name; |
IN | Shorthand for WHERE. Specifies multiple OR conditions. | SELECT column_name FROM table_name where column_name IN (‘A’, ‘B’, ‘C’); |
NOT IN | Shorthand for WHERE. Specifies multiple OR conditions (inverted) or not equal to. | SELECT column_name FROM table_name where column_name NOT IN (‘A’, ‘B’, ‘C’); |
IS NULL | Check for empty values. | SELECT column_name FROM table_name WHERE column_name IS NULL; |
IS NOT NULL | Check for no empty values. | SELECT column_name FROM table_name WHERE column_name IS NOT NULL; |
INTERSECT | Return results which match two queries. | SELECT column_name FROM table_name INTERSECT SELECT column_2_name FROM table_2_name; |
MINUS | Return results in one query which are not in another query. | SELECT column_name FROM table_name MINUS SELECT column_2_name FROM table_2_name; |
ON | Used to specify the column to compare and match results. | SELECT * FROM table_name LEFT OUTER JOIN table_2_name ON table_name.column_name = table_2_name.column_name; |
USING | Shorthand for ON, used when the column name is the same in both tables. | SELECT * FROM table_name LEFT OUTER JOIN table_2_name ON table_name.column_name = table_2_name.column_2_name; |
LEFT OUTER JOIN | All the results from the left table, with only the matching results from the right table. | SELECT * FROM table_name LEFT OUTER JOIN table_2_name ON table_name.column_name = table_2_name.column_2_name; |
LEFT OUTER JOIN (WITH NULL) | (With null) All the results from the left table but not in the right table. | SELECT * FROM table_name LEFT OUTER JOIN table_2_name ON table_name.column_name = table_2_name.column_2_name WHERE table_2_name.column_2_name IS NULL; |
INNER JOIN | All the results that match in both the left and right tables. | SELECT * FROM table_name INNER JOIN table_2_name ON table_name.column_name = table_2_name.column_2_name; |
FULL OUTER JOIN | All the results from both the left and right tables. | SELECT * FROM table_name FULL OUTER JOIN table_2_name ON table_name.column_name = table_2_name.column_2_name; |
FULL OUTER JOIN (WITH NULL) | (With null) All the results from both the left and right tables excluding results in both tables. | SELECT * FROM table_name FULL OUTER JOIN table_2_name ON table_name.column_name = table_2_name.column_2_name WHERE table_name.column_name IS NULL OR table_2_name.column_2_name IS NULL; |
RIGHT OUTER JOIN | All the results from the right table, with only the matching results from the left table. | SELECT * FROM table_2_name RIGHT OUTER JOIN table_name ON table_2_name.column_2_name = table_name.column_name; |
RIGHT OUTER JOIN (WITH NULL) | (With null) All the results from the right table but not in the left table. | SELECT * FROM table_2_name RIGHT OUTER JOIN table_name ON table_2_name.column_2_name = table1. |
CREATE TABLE | Create a new table. | CREATE TABLE table_name (column_name datatype column_2_name datatype); |
NULL | Allow empty values for this field. | CREATE TABLE table_name (column_name column_name datatype NULL); |
NOT NULL | Don’t allow empty values for this field. | CREATE TABLE table_name (column_name column_name datatype NOT NULL); |
DEFAULT | A value to populate the field with if one is not supplied. | CREATE TABLE table_name (column_name datatype DEFAULT ‘makeuseof’); |
AS | Create a new table based on the structure of an existing table. The new table will contain the data from the old table. | CREATE TABLE table_2_name AS SELECT * FROM table_name; |
ALTER TABLE (ADD COLUMN) | Add a new column to an existing table. | ALTER TABLE table_name ADD COLUMN column_2_name datatype; |
ALTER TABLE (DROP COLUMN) | Remove a column from an existing table. | ALTER TABLE table_name DROP COLUMN column_2_name; |
ALTER TABLE (ALTER COLUMN) | Change the datatype of an existing column. | ALTER TABLE table_2_name ALTER COLUMN column_name datatype; |
ALTER TABLE (RENAME COLUMN) | Rename an existing column. | ALTER TABLE table_name RENAME COLUMN column_name TO new_column_name datatype; |
ALTER TABLE (RENAME TABLE) | Rename an existing table. | RENAME TABLE table_name TO new_table_name; |
ALTER TABLE (MODIFY NULL) | Allow null values for a column. | ALTER TABLE table_name MODIFY column_name datatype NULL; |
ALTER TABLE (MODIFY NOT NULL) | Prevent null values for a column. | ALTER TABLE table_name MODIFY column_name datatype NOT NULL; |
DROP TABLE | Delete a table and all its data. | DROP TABLE table_name; |
TRUNCATE TABLE | Delete all the data in a table, but not the table itself. | TRUNCATE TABLE table_name; |
PRIMARY KEY | A value that uniquely identifies a record in a table. A combination of NOT NULL and UNIQUE. | CREATE TABLE table_name (column_name datatype column_2_name datatype, PRIMARY KEY (column_name, column_2_name)); |
FOREIGN KEY | References a unique value in another table. Often a primary key in the other table. | CREATE TABLE table_name (column_name datatype column_2_name datatype, FOREIGN KEY (column_name) REFERENCES table_2_name (column_2_name)); |
UNIQUE | Enforce unique values for this column per table. | CREATE TABLE table_name (column_name datatype column_2_name datatype, UNIQUE(column_name, column_2_name)); |
CHECK | Ensure values meet a specific condition. | CREATE TABLE table_name (column_name datatype column_2_name datatype, CHECK(column_name > 10)); |
INDEX (CREATE) | Optimize tables and greatly speed up queries by adding an index to a column. | CREATE INDEX index_name ON table_name(column_name); |
INDEX (CREATE UNIQUE) | Create an index that does not allow duplicate values. | CREATE UNIQUE INDEX index_name ON table_name(column_name); |
INDEX (DROP) | Remove an index. | DROP INDEX index_name; |
INSERT (SINGLE VALUE) | Add a new record to a table. | INSERT INTO table_name(column_name) VALUES(value_1); |
INSERT (MULTIPLE VALUES) | Add several new records to a table. | INSERT INTO table_name(column_name) VALUES(value_1),(value_2); |
INSERT (SELECT) | Add records to a table, but get the values from an existing table. | INSERT INTO table_name(column_name) SELECT * FROM table_2_name; |
UPDATE (ALL) | Modify all existing records in a table. | UPDATE table_name SET column_name = 10; |
UPDATE (WHERE) | Modify existing records in a table which match a condition. | UPDATE table_name SET column_name = 10 WHERE column_2_name = 5; |
DELETE (ALL) | Remove all records from a table. | DELETE FROM table_name; |
DELETE (WHERE) | Remove records from a table which match a condition. | DELETE FROM table_name WHERE column_name = 5; |
CREATE TRIGGER | Create a trigger. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
CREATE TRIGGER (OR MODIFY) | Create a trigger, or update an existing trigger if one is found with the same name. | CREATE OR MODIFY TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
WHEN (BEFORE) | Run the trigger before the event happens. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
WHEN (AFTER) | Run the trigger after the event happens. | CREATE TRIGGER trigger_name AFTER INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
EVENT (INSERT) | Run the trigger before or after an insert happens. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
EVENT (UPDATE) | Run the trigger before or after an update happens. | CREATE TRIGGER trigger_name BEFORE UPDATE ON table_name FOR EACH ROW EXECUTE stored_procedure; |
EVENT (DELETE) | Run the trigger before or after a delete happens. | CREATE TRIGGER trigger_name BEFORE DELETE ON table_name FOR EACH ROW EXECUTE stored_procedure; |
ON | Specify which table to target with this trigger. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
TRIGGER_TYPE (FOR EACH ROW) | Execute the trigger for every row changed. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
TRIGGER_TYPE (FOR EACH STATEMENT) | Execute the trigger once per SQL statement, regardless of how many rows are altered. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW STATEMENT stored_procedure; |
EXECUTE | Keyword to indicate the end of the main trigger definition. | CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW EXECUTE stored_procedure; |
DROP TRIGGER | Delete a trigger. | DROP TRIGGER trigger_name; |
CREATE VIEW | Create a new view. | CREATE VIEW view_name(column_name) AS SELECT * FROM table_name; |
AS | Define where to retrieve the data for a view. | CREATE VIEW view_name(column_name) AS SELECT * FROM table_name; |
WITH CASCADED CHECK OPTION | Ensure any data modified through a view meets the rules defined by the rule. Apply this to any other views. | CREATE VIEW view_name(column_name) AS SELECT * FROM table_name WITH CASCADED CHECK OPTION; |
WITH LOCAL CHECK OPTION | Ensure any data modified through a view meets the rules defined by the rule. Ignore this for any other views. | CREATE VIEW view_name(column_name) AS SELECT * FROM table_name WITH LOCAL CHECK OPTION; |
CREATE RECURSIVE VIEW | Create a recursive view (one that refers to a recursive common table expression). | CREATE RECURSIVE VIEW view_name(column_name) AS SELECT * FROM table_name; |
CREATE TEMPORARY VIEW | Create a view that exists for the current session only. | CREATE TEMPORARY VIEW view_name(column_name) AS SELECT * FROM table_name; |
DROP VIEW | Delete a view. | DROP VIEW view_name; |
WITH | Create a new common table expression. | WITH cte_name (column_name) AS (SELECT * FROM table_name) SELECT * FROM cte_name; |
AS | Specify the data to use in the CTE. | WITH cte_name (column_name) AS (SELECT * FROM table_name) SELECT * FROM cte_name; |
,(COMMA) | Chain multiple CTEs. | WITH cte_name (column_name) AS (SELECT * FROM table_name), cte_2_name (column_2_name) AS (SELECT * FROM table_2_name) SELECT * FROM cte_name; |
Python RegEx Shortcuts
pip install package | Install an online library | pip install pandas |
virtualenv name | Use virtaulenv to create a virtual environment | virtualenv myproject |
mkvirtualenv name | Use virtual environment wrapper to create virtual environment | mkvirtualenv myproject |
python file.py | Run the commands in a Python file | “python my_file.py |
pip freeze | List out all the installed packages in a virtual environment | pip freeze |
pip freeze > somefiles | Copy all installed libraries in a single file | pip freeze > requirements.txt |
where | Find the installation path of Python | where python |
–version | Check the version of a package | python –version |
.exe | Run a Python shell | python.exe |
with open(file, ‘w’) | Write to an existing file and overwrite its existing content | with open(‘regex.txt’, ‘w’) as wf: wf.write(“Hello World!”) |
with open(file, ‘r’) | Open a file as read-only | with open(‘regex.txt’, ‘r’) as rf: print(rf.read() |
with open(file, ‘a’) | Write to a file without overwriting its existing content | with open(‘regex.txt’, ‘a’) as af: af.write(“\nHello Yes!”) |
file.close | Close a file if it’s not in use | af=open(‘regex.txt’) af.close |
exit | Exit the Python shell | exit() |
Expression | Action | Example |
---|---|---|
print() | Display the result of a command | x=”Hello world” print(x) output: Hello world |
input() | Collect inputs from users | print(input(“what is your name?”)) output: what is your name? |
type() | Find the type of a variable | x=”Regular expressions” type(x) output: <class ‘str’> |
len() | Find the number of items in a variable | len([1, 2, 3]) output: 3 |
\ | Escape a character that changes the intent of a line of code | print(“I want you to add\”\””) output: I want you to add”” |
\n | Break a string character to start on the next line | print(“This is a line \n This is a second line”) output: This is a line This is a second line |
def function_name(parameter): commands | Initiate a function with an optional parameter | def yourName(x): print(x+1) |
lambda | Call an anonymous function | add_3_to = lambda y: y+3 print(add_3_to(4)) output: 7 |
return | Return a result from a function | def yourName(x): return x+1 |
class | Create a Python object | class myClass: def myFunc(x): |
def _init_ | Initialize the attrributes of a class | class myClass: def _init_(self, attributes…) |
“_init_.py | Save a file containing a module so that it’s read successfully in another Python file | Rename a file containing a module as: “_init_.py |
int() | Convert a variable to integer | int(1.234) output: 1 |
str() | Convert a variable to string | str(1.234) output: ‘1.234’ |
float() | Convert a variable to float | float(23) output: 23.0 |
dict(Counter()) | Convert a list or a tupple into a dictionary after sorting with a Python built-in Counter | from collections import Counter dict(Counter([1,1,2,1,2,3,3,4])) output: {1: 3, 2: 2, 3: 2, 4: 1} |
round() | Round up the output of an operation to the nearest whole number | round(23.445) output: 23 |
round(operation or number, decimal places) | Round up the output of an operation to a specific number of decimal places | round(23.4568, 2) output: 23.46 |
if: | Initiate a conditional statement | if 2<3: print(“Two is smaller”) |
elif: | Make a counterstatement when the if statement is False | if 2<3: print(“Two is smaller”) elif 2==3: print(“Go on”) |
else: | Make a final counterstatement if other conditions are False | if 2<3: print(“Two is smaller”) elif 2==3: print(“Go on”) else: print(“Three is greater”) |
continue | Ignore a condition and execute the rest of the loop | a=[1, 4, -10, 6, 8] for b in a: if b<=0: continue print(b) output: 1 4 6 8 |
break | Terminate the flow of a loop with a given condition | a=[1, 4, -10, 6, 8] for b in a: if b>=6: break print(b) output: 1 4 -10 |
pass | Ignore a set of prior instructions | for b in a: pass |
try, except | Try a block of code, else, raise a defined exception | try: print(a) except: print(“An error occured!”) output: An error occured! |
finally | Execute a final code when the try and the except blocks fail | try: print(a) except: print(d) finally: print(“You can’t print an undefined variable”) output: You can’t print an undefined variable |
raise Exception() | Raise an exception that stops the command when execution isn’t possible | a=7+2 if a<10: raise Exception(“Oh! You didn’t get a score of 10”) |
import x | Import a whole module or library | import math |
from x import y | Import a library x from a file, or a class y | from scipy.stats import mode |
as | Customize an expression to your preferred name | import pandas as pd |
in | Check if a value is present in a variable | x=[1, 4, 6, 7] if 5 in x: print(“There is a five”) else: print(“There is no five”) output: There is no five |
is | Check if two variables refer to a single element | x=[1, 4, 6, 7] x=b print(x is b) True |
None | Declare a null value | x=None |
< | Check if one value is lesser than another | 5<10 output: True |
> | Check if one value is more than another | 5>10 output: False |
<= | Check if a value is lesser or equal to another | 2*2<=3 output: False |
>= | Check if a value is greater or equal to another | 2*2>=3 output: True |
“== | Check if a value is exactly equal to the other | 3==4 output: False |
!= | Ascertain that a value is not equal to the other | 3!=4 output: True |
import re | Import Python’s built-in regular expressions | import re re.findall(“strings”, variable) |
a|b | Check if either of two elements are present in a string | import re someText=”Hello regular expression” a=re.findall(“regular|Hello”, someText) print(a) output: [‘Hello’, ‘regular’] |
string$ | string$ | Check if a variable ends with a set of strings import re someText=”Hello regular expression” a=re.findall(“expression$”, someText) output: [‘expression’] |
^string | Check if a variable starts with a set of strings | import re someText=”Hello regular expression” a=re.findall(“^Hello”, someText) print(a) output: [‘Hello’] |
string.index() | Check the index position of a string character | a= “Hello World” a.index(‘H’) output: 0 |
string.capitalize() | Capitalize the first character in a set of strings | a= “Hello World” a.capitalize() output: ‘Hello world’ |
string.swapcase() | Print the first letter of each word as a lower case and the others as upper case | a= “Hello World” a.swapcase() output: ‘hELLO wORLD’ |
string.lower() | Convert all the strings to a lowercase | a= “Hello World” a.lower() output: ‘hello world’ |
string.upper() | Convert all strings to uppercase | a= “Hello World” a.upper() output: ‘HELLO WORLD’ |
string.startswith() | Check if a string starts with a particular character | a= “Hello World” a.startswith(‘a’) output: False |
string.endswith() | Check if a string ends with a particular character | a= “Hello World” a.endswith(‘d’) output: True |
string.split() | Separate each word into a list | a= “Hello World” a.split() output: [‘Hello’, ‘world’] |
strings {}’.format() | Display an output as string | a=3+4 print(“The answer is {}”.format(a)) output: The answer is 7 |
is not None | Check if the value of a variable is not empty | def checknull(a): if a is not None: return “its full!” else: return “its empty!” |
x%y | Find the remainder (modulus) of a division | 9%4 output: 1 |
x//y | Find the quotient of a division | 9//4 output: 2 |
“= | Assign a value to a variable | a={1:5, 3:4} |
“+ | Add elements together | [“a two”] + [“a one”] output: [‘a two’, ‘a one’] 1+3 output=4 |
“- | Find the difference between a set of numbers | 3-4 output=-1 |
“* | Find the product of a set of numbers | 3*4 output:12 |
a+=x | Add x to variable a without assigning its value to a new variable | a=2 a+=3 output: 5 |
a-=x | Subsract x from variable a without assigning it to a new variable | a=3 a-=2 output: 1 |
a*=x | Find the product of variable a and x without assigning the resullt to a new variable | a=[1, 3, 4] a*=2 output: [1, 3, 4, 1, 3, 4] |
x**y | Raise base x to power y | 2**3 output: 8 |
pow(x, y) | Raise x to the power of y | pow(2, 3) output: 8 |
abs(x) | Convert a negative integer to its absolute value | abs(-5) output: 5 |
x**(1/nth) | Find the nth root of a number | 8**(1/3) output: 2 |
a=b=c=d=x | Assign the same value to multiple variables | a=b=c=d=”Hello world” |
x, y = y, x | Swap variables | x = [1, 2] y = 3 x, y = y, x print(x, y) output: 3 [1, 2] |
for | Loop through the elements in a variable | a=[1, 3, 5] for b in a: print(b, “x”, “2”, “=”, b*2) output: |
while | Keep looping through a variable, as far as a particular condition remains True | a=4 b=2 while b<=a: print(b, “is lesser than”, a) b+=1 output: |
range() | Create a range of positive integers between x and y | x=range(4) print(x) range(0, 4) for b in x: print(b) output: |
sum() | Iterate through the elements in a list | print(sum([1, 2, 3])) output:6 |
sum(list, start) | Return the sum of a list with an added element | print(sum([1, 2, 3], 3)) output: 9 |
[] | Make a list of elements | x=[‘a’, 3, 5, ‘h’, [1, 3, 3], {‘d’:3}] |
() | Create a tupple—tupples are immutable | x=(1, 2, ‘g’, 5) |
{} | Create a dictionary | a={‘x’:6, ‘y’:8} |
x[a:b] | Slice through a list | x=[1, 3, 5, 6] x[0:2] output: [1, 3] |
x[key] | Get the value of a key in dictionary x | a={‘x’:6, ‘y’:8} print(a[‘x’]) output: 6 |
x.append() | Add a list of values to an empty list | x=[1] x.append([1,2,3]) print(x) output: [1, [1,2,3]] |
x.extend() | Add a list of values to continue an existing list without necessarily creating a nested list | x=[1,2] x.extend([3,4,6,2]) print(x) output: [1, 2, 3, 4, 6, 2] |
del(x[a:b]) | Delete an item completely from a list at a specific index | x=[1,2,3,5] del(x[0:2]) print(x) output: [2,3,5] |
del(x[key]) | Delete a key and a value completely from a dictionary at a specific index | y={1:3, 2:5, 4:6, 8:2} del(y[1], y[8]) print(y) output= {2:5, 4:6} |
dict.pop() | Pop out the value of a key and remove it from a dictionary at a specific index | a={1:3, 2:4, 5:6} a.pop(1) output: 3 |
dict.popitem() | Pop out the last item from a dictionary and delete it | a={1:2, 4:8, 3:5} a.popitem() output: (3, 5) print(a) output: {1:2, 4:8} |
list.pop() | Pop out a given index from a list and remove it from a list | a=[1, 3, 2, 4, 1, 6, 6, 4] a.pop(-2) output: 6 print(a) output: [1, 3, 2, 4, 1, 6, 4] |
clear() | Empty the elements of a list or a dictionary | x=[1, 3, 5] x.clear() print(x) output: [] |
remove() | Remove an item from a list | x=[1, 5, 6, 7] x.remove(1) output: [5, 6, 7] |
insert() | Insert elements into a list | x=[3, 5, 6] x.insert(1, 4) print(x) output: [1, 4, 3, 5, 6] |
sort(reverse=condition) | Reverse the direction of the elements in a list | x=[1, 3, 5, 6] x.sort(reverse=True) print(x) output: [6, 5, 3, 1] |
update() | Update a dictionary by changing its first element and adding any other item to its end | x={1:3, 5:6} x.update({1:4, 8:7, 4:4}) print(x) output: {1: 4, 5: 6, 8: 7, 4: 4} |
keys() | Show all the keys in a dictionary | a={1:2, 4:8} a.keys() output: dict_keys([1, 4]) |
values() | Show all the values in a dictionary | a={1:2, 4:8} a.values() output: dict_values([2, 8]) |
items() | Display the keys and the values in a dictionary | a={1:2, 4:8} a.items() output: dict_items([(1, 2), (4, 8)]) |
get(key) | Get the value of an item in a dictionary by its key | a={1:2, 4:8, 3:5} a.get(1) output: 2 |
setdefault(key) | Return the original value of an element to a dictionary | a.setdefault(2) |
f={**a, **b} | Merge two dictionaries | a={‘x’:6, ‘y’:8} b={‘c’:5, ‘d’:3} f={**a, **y} print(f) output:{‘x’: 6, ‘y’: 8, ‘c’: 5, ‘d’: 3} |
remove() | Remove the first matching value of an element from a list without minding its index | a=[1, 3, 2, 4, 4, 1, 6, 6, 4] a.remove(4) print(a) output: [1, 3, 2, 4, 1, 6, 6, 4] |
memoryview(x) | Access the internal buffers of an object | a=memoryview(object) |
bytes() | Convert a memory buffer protocol into bytes | bytes(a[0:2]) |
bytearray() | Return an array of bytes | bytearray(object) |
# | Write a single line of comment or prevent a line of code from being executed | # Python regex cheat sheet |
“””””” | Write a multi-line comment | “””The Python regex cheat sheet is good for beginners It’s equally a great refresher for experts””” |