5.1. Python and Jupyter Shortcuts#

There are a few operations that you use (or will use) that we should revisit to ensure we’re approaching them in the most efficient way possible.

Assignment Operators#

You’ve probably seen that cryptography and loops have required us to frequently use a variable as a running total, to which you repeatedly add or append values. We may have seen something like:

counter = counter + 1

or

ciphertext = ciphertext + char

To simplify this syntax, you could instead have used the following commands, which are called assignment operators:

counter += 1

or

ciphertext += char

The += command, perhaps not surprisingly, adds the value of the object on the right of the symbol to the value of the object on the left of the symbol and then sets it equal to the new value. This operator works like addition for integers and floats, and like concatenation for strings. For integers and floats there are similar commands for subtraction (-=), multiplication (*=), and division (/=). Since there are no equivalent operations for strings, these operators do not work with strings. Here’s a table of valid assignment operators in Python.

Operator

Example

Same as

+=

x += 2

x = x + 2

-=

x -= 2

x = x - 2

*=

x *= 2

x = x * 2

/=

x /= 2

x = x / 2

%=

x %= 2

x = x % 2

//=

x //= 2

x = x // 2

**=

x **= 2

x = x ** 2

While these operators don’t add any new functionality, they will save you some keystrokes when you don’t have to type your variable names repeatedly.

Conditional Branching#

Instead of typing:

if variable_name == True:
    ...

you can type just:

if variable_name:
    ...

Since the if statement is checking to see if the operation resolves to True or False, just supplying a bool object accomplishes this quicker without having to compare it to True or False.

Jupyter Notebook Tips and Shortcuts#

There are a few keyboard shortcuts that could save you time when working in Jupyter Lab.

  • tab: the tab button will auto-complete an object name that you are typing. It will look to see if there are any other objects defined in the notebook that match the name you’ve started to type and finish it when you press tab. If there are multiple names that could match, it will present a list. This is a useful feature not only to save time, but to avoid typos.

  • crtl+enter: this will run the currently selected cell and keep it selected when finished

  • shift+enter: this will run the currently selected cell and advance to the next cell when finished. If there is no additional cells, one will be created

There are also a few additional tips for customizing the editor:

  • Dark Mode: you can enable dark mode by choosing [Settings] and then [JupyterLab Theme] and selecting “JupyterLab Dark”

  • Autoclose Brackets: by default JupyterLab will automatically close parentheses, brackets, and quotes. This feature can be toggled off under the [Settings] menu.