Converter Web ToolsConverter WebTools

Python Cheat Sheet — Syntax Basics

This Python cheat sheet covers the basics — variables, data structures, loops, functions and common string methods — for quick reference.

Basics

CodeWhat it does
x = 5Variable
print(x)Output
len(s)Length
type(x)Type of a value
range(5)0,1,2,3,4
input()Read a line

Data structures

CodeWhat it does
lst = [1, 2, 3]List
d = {"a": 1}Dictionary
t = (1, 2)Tuple
s = {1, 2}Set
lst.append(x)Add to list
d.get("a")Dict value
[x*2 for x in lst]List comprehension

Control flow

CodeWhat it does
if x > 0:Condition
for i in lst:Loop over items
while x < 5:While loop
def f(a, b):Define a function
return xReturn a value

Related tools & charts