Cheat Sheets

Everything You Need to Know About Python

Lesson

Here are all the import Python language features you need to know.

Basics

These are all the built-in data structure types in Python:

You can convert between types like this:

Here are very basic operations that you should know:

You can conditionally set a value using if statement, called a "Ternary Operator".

You can set multiple variables at the same time, which is particularly useful when you want to swap variables with each other. Here are a few examples (this is called "object destructuring"):

Loops + Ifs

Comprehensions

Python has nice syntax for creating arrays. Here's an example that shows the general logic you can use (this is called a "List Comprehension"):

Here are some more examples:

Generator Comprehensions are the same as List Comprehensions, except they generate values lazily and can stop early. To do a generator comprehension, just use () instead of [].

Note that () can mean a tuple, or it can mean a generator depending on context.

Functions

To create a function, you use the def keyword:

All variables declared inside a function are local. You need to use the nonlocal keyword if you want to use variables that appear outside of a function. Here's an example:

You only have to worry about using nonlocal with primitive types like with numbers. This is because objects are automatically globally scoped. See below for details.

You can also declare a function in-line, using the keyword lambda. You don't have to do this, it's just for convenience. The following 2 functions are the same:

Booleans

Anything can be used as a boolean. Values of None, 0, and empty data structures like [] evaluate to False, and everything else evaluates to True.

The any() function check if any value is true, and the all() function checks if all values are true.

Strings

Strings come with the useful built-in functions .split(x), .join(x), ord(x), and chr(x).

Misc

To write an expression over multiple lines, you can escape newlines with \, or you can wrap the expression in parentheses.

You can select parts of an array or string very easily, called "splicing". Specify the start index, end index, and/or step size that you want to make. Here are some examples:

Almost everything in Python is a pointer. Whenever you write A=B, Python points A to B. See Pointers for more.

Python Reference

Here's a refrence to the offical Python docs: https://docs.python.org/3/library/index.html. The Built-in Functions and Built-in Types sections are the most useful parts to skim, although it's totally optional reading. The docs are not formatted in a very readable way.

Mark as Completed:
Submits:
test
Test your code to get an output here!