Python Cheatsheet

Introduction Hello World Variables Data Types Strings Numbers Lists Tuples Sets Dictionaries Slicing Comprehensions Control Flow Loops

Introduction

Introduction

Hello World

Hello World
>>> print("Hello, World!")
Hello, World!

The famous "Hello World" program in Python.

Variables

Variables
age = 18         # age is of type int
name = "John"     # name is now of type str
print(name)

Python can't declare a variable without assignment.

Data Types

Data Types
Type Description
str Text
int, float, complex Numeric
list, tuple, range Sequence
dict Mapping
set, frozenset Set
bool Boolean
bytes, bytearray, memoryview Binary

Slicing String

Slicing String
>>> msg = "Hello, World!"
>>> print(msg[7:9])
llo

Lists

Lists
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
    print(item) # prints out 1,2

If Else

If Else
num = 200
if num > 0:
    print("num is greater than 0")
else:
    print("num is not greater than 0")

Loops

Loops
for item in range(5):
    if item == 3: break
    print(item)
else:
    print("Finally finished!")

Strings

Strings
s = "Hello"
print(s.upper())  # 'HELLO'
print(s.lower())  # 'hello'
print(s.replace("l", "x"))  # 'Hexxo'
print(s[1:4])  # 'ell'

Numbers

Numbers
a = 5
b = 2.5
print(a + b)  # 7.5
print(a // 2)  # 2 (floor division)
print(a ** 3)  # 125 (power)

Tuples

Tuples
t = (1, 2, 3)
print(t[1])  # 2
print(t.count(2))  # 1

Sets

Sets
s = {1, 2, 3}
s.add(4)
print(s)  # {1, 2, 3, 4}

Dictionaries

Dictionaries
d = {"a": 1, "b": 2}
print(d["a"])  # 1
d["c"] = 3

Slicing

Slicing
lst = [0, 1, 2, 3, 4]
print(lst[1:4])    # [1, 2, 3]
print(lst[-2:])    # [3, 4]
print(lst[::-1])   # [4, 3, 2, 1, 0]

List Comprehensions

Comprehensions
squares = [x*x for x in range(5)]  # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]

Control Flow

Control Flow
x = 10
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

Loops

Loops
for i in range(3):
    print(i)
for idx, val in enumerate(['a', 'b']):
    print(idx, val)
while x > 0:
    x -= 1