Value Keywords

True

False

None

Click on the images to expand the view

boolean

The first two are of a type called boolean. Boolean values in programming are used in cases where the outcome is either one or two possibilities, the possibilities in this case being True or False. You couldn't have a value that is both true and false at the same time. This situation is comparable to your room light swicth which can only ever either be on or off.

In Python a variable is also cosidered equal (==) to True if it contains a value which is not 0. This means you could have a variable of a different type (int, str, list etc.) which contains a value which is not 0 but would be considered True just because it's not empty.

NoneType

The None Value is of type NoneType (which is not synonymous to 0), so the variable fruits = 0 and fruits = None are two very different variables (Note: they couldn't exist seperately simulteneously within the same scope due to having same names, python would instead update the value of the variable). The variable with the value None is therefore not same a 0 which is on type integer. Try the code in the image attached.

Variable Keywords

global

nonlocal

del

Click on the images to expand the view

global

If you need to modify a variable that isn't defined in a function but is defined in the global scope, then you'll need to use the global keyword. This works by specifying in the function which variables need to be pulled into the function from the global scope.

A basic example is incrementing a global variable with a function call. You can do that with the global keyword. This is is happening to the variable your_name in the demonstrative example in the attached image.

del

del is used in Python to unset a variable or name. You can use it on variable names, but a more common use is to remove indexes from a list or dictionary. To unset a variable, use del followed by the variable you want to unset. The image to the left shows the implementation in syntax.

nonlocal

The nonlocal keyword is similar to global in that it allows you to modify variables from a different scope. With global, the scope you're pulling from is the global scope. With nonlocal, the scope you're pulling from is the parent scope. The syntax is similar to global. See what's happening with the department variable in the demonstrative example in the image attached.

Operator Keywords

and

or

not

is

in

Click on the images to expand the view

and

The Python keyword and is used to determine if both the left and right operands are truthy or falsy. If both operands are truthy, then the result will be truthy. If one is falsy, then the result will be falsy.

<left-handside> and <right-handside>

Note that the results of an and statement will not necessarily be True or False. This is because of the quirky behavior of and. Rather than evaluating the operands to their Boolean values, and simply returns <left-handside> if it is falsy or else it returns <right-handside>. The results of an and statement could be passed to bool() to get the explicit True or False value, or they could be used in a conditional if statement.

or

Python's or keyword is used to determine if at least one of the operands is truthy. An or statement returns the first operand if it is truthy and otherwise returns the second operand.

<left-handside> or <right-handside>

Just like the and keyword, or doesn't convert its operands to their Boolean values. Instead, it relies on their truthiness to determine the results.

not

Python's not keyword is used to get the opposite Boolean value of a variable

is

Python's is keyword is an identity check. This is different from the == operator, which checks for equality. Sometimes two things can be considered equal but not be the exact same object in memory. The is keyword determines whether two objects are exactly the same object.

in

Python's in keyword is a powerful containment check, or membership operator. Given an element to find and a container or sequence to search, in will return True or False indicating whether the element was found in the container

Control Flow Keywords

if

elif

else

Click on the images to expand the view

if

The if keyword is used to start a conditional statement. An if statement allows you to write a block of code that gets executed only if the expression after if is truthy. The syntax for an if statement starts with the keyword if at the beginning of the line, followed by a valid expression that will be evaluated for its truthiness value.

elif

The elif statement looks and functions like the if statement, with two major differences:

  • Using elif is only valid after an if statement or another elif.
  • You can use as many elif statements as you need.

In other programming languages, elif is either else if (two separate words) or elseif (both words mashed together). When you see elif in Python, think else if.

else

The else statement, in conjunction with the Python keywords if and elif, denotes a block of code that should be executed only if the other conditional blocks, if and elif, are all falsy.

Iteration Keywords

for

continue

break

else

while

Click on the images to expand the view

for

The most common loop in Python is the for loop. It's constructed by combining the Python keywords for and in explained earlier.

continue

Python also has a continue keyword for when you want to skip to the next loop iteration. Like in most other programming languages, the continue keyword allows you to stop executing the current loop iteration and move on to the next iteration.

break

If you need to exit a loop early, then you can use the break keyword. This keyword will work in both for and while loops

else

In addition to using the else keyword with conditional if statements, you can also use it as part of a loop. When used with a loop, the else keyword specifies code that should be run if the loop exits normally, meaning break was not called to exit the loop early

while

Python's while loop uses the keyword while and works like a while loop in other programming languages. As long as the condition that follows the while keyword is truthy, the block following the while statement will continue to be executed over and over again

Structure Keywords

def

class

with

as

pass

lambda

Click on the images to expand the view

def

Python's keyword def is used to define a function or method of a class. The basic syntax for defining a function with def looks like the demostrative example in the image.

class

To define a class in Python, you use the class keyword. The general syntax for defining a class with class is as shown in the image attached.

with

Context managers are a really helpful structure in Python. Each context manager executes specific code before and after the statements you specify. To use one, you use the with keyword.

If you wanted to open a file, do something with that file, and then make sure that the file was closed correctly, then you would use a context manager. Consider this example in which new_file.txt contains a list of names, one per line. See the code in the image attached.

as

If you want access to the results of the expression or context manager passed to with or an import statement, you'll need to alias it using as. You may have also seen as used to alias imports and exceptions, and this is no different. The alias is available in the with block

pass

Since Python doesn't have block indicators to specify the end of a block (like other languages the likes of Javascript use { } to indicate where the block scope starts and ends), the pass keyword is used to specify that the block is intentionally left blank. It's the equivalent of a no-op, or no operation. Here are a few examples of using pass to specify that the block is blank.

lambda

The lambda keyword is used to define a function that doesn't have a name and has only one statement, the results of which are returned. Functions defined with lambda are referred to as lambda functions.

Return Keywords

return

yield

Click on the images to expand the view

return

Python's return keyword is valid only as part of a function defined with def. When Python encounters this keyword, it will exit the function at that point and return the results of whatever comes after the return keyword. You can even use the return return multiple times in a function. This allows you to have multiple exit points in your function. A classic example of when you would want to have multiple return statements is the following recursive solution to calculating factorial.

yield

The yield keyword in python is kind of like the return keyword in that it specifies what gets returned from a function. However, when a function has a yield statement, what gets returned is a generator. The generator can then be passed to Python's built-in next() to get the next value returned from the function.

When you call a function with yield statements, Python executes the function until it reaches the first yield keyword and then returns a generator. These are known as generator functions.

Import Keywords

import

from

as

Click on the images to expand the view

For those tools that, unlike Python keywords and built-ins, are not already available to your Python program, you'll need to import them into your program. There are many useful modules available in Python's standard library that are only an import away. There are also many other useful libraries and tools available in PyPI that, once you've installed them into your environment, you'll need to import into your programs. The following are brief descriptions of the three Python keywords used for importing modules into your program.

import

Python's import keyword is used to import, or include, a module for use in your Python program. Basic usage syntax looks like the example attached.

from

The from keyword is used together with import to import something specific from a module

as

The as keyword is used to alias an imported module or tool. It's used together with the Python keywords import and from to change the name of the thing being imported. This is a better alternative to just importing everything from a module, and it allows you to shorten the name of the module being imported.

Exception-Handling Keywords

try

except

raise

finally

else

assert

Click on the images to expand the view

try

Any exception-handling block begins with Python's try keyword. This is the same in most other programming languages that have exception handling.

The code in the try block is code that might raise an exception. Several other Python keywords are associated with try and are used to define what should be done if different exceptions are raised or in different situations. These are except, else, and finally.

A try block isn't valid unless it has at least one of the other Python keywords used for exception handling as part of the overall try statement

except

Python's except keyword is used with try to define what to do when specific exceptions are raised. You can have one or more except blocks with a single try.

Notice that the except keyword can also be used in conjunction with the as keyword. This has the same effect as the other uses of as, giving the raised exception an alias so you can work with it in the except block.

Even though it's syntactically allowed, try not to use except statements as implicit catchalls. It's better practice to always explicitly catch something, even if it's just Exception

raise

The raise keyword raises an exception. If you find you need to raise an exception, then you can use raise followed by the exception to be raised

finally

Python's finally keyword is helpful for specifying code that should be run no matter what happens in the try, except, or else blocks. To use finally, use it as part of a try block and specify the statements that should be run no matter what

else

You've learned that the else keyword can be used with both the if keyword and loops in Python, but it has one more use. It can be combined with the try and except Python keywords. You can use else in this way only if you also use at least one except block.

In this context, the code in the else block is executed only if an exception was not raised in the try block. In other words, if the try block executed all the code successfully, then the else block code would be executed.

assert

The assert keyword in Python is used to specify an assert statement, or an assertion about an expression. An assert statement will result in a no-op if the expression is truthy, and it will raise an AssertionError if the expression is falsy. To define an assertion, use assert followed by an expression