Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python cheatsheet

The document is a comprehensive Python cheatsheet that serves as a one-page reference for the Python 3 programming language. It covers various topics including data types, functions, file handling, loops, and advanced data structures like heaps and queues. The cheatsheet provides code snippets and explanations for quick reference to essential Python programming concepts.

Uploaded by

Ramcharan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python cheatsheet

The document is a comprehensive Python cheatsheet that serves as a one-page reference for the Python 3 programming language. It covers various topics including data types, functions, file handling, loops, and advanced data structures like heaps and queues. The cheatsheet provides code snippets and explanations for quick reference to essential Python programming concepts.

Uploaded by

Ramcharan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

QuickRef.ME Search for cheatsheet ⌘ K Stars 6.

6k Follow Me

Python cheatsheet
The Python cheat sheet is a one-page reference sheet for the Python 3 programming language.

# Getting Started
Introduction Hello World Variables

Python (python.org) >>> print("Hello, World!") age = 18 # age is of type int


Hello, World! name = "John" # name is now of type str
Learn X in Y minutes (learnxinyminutes.com) print(name)

Regex in python (quickref.me)


Python can't declare a variable without
The famous "Hello World" program in Python assignment.

Data Types Slicing String Lists

str Text >>> msg = "Hello, World!" mylist = []


>>> print(msg[2:5]) mylist.append(1)
int, float, complex Numeric
llo mylist.append(2)
for item in mylist:
list, tuple, range Sequence
print(item) # prints out 1,2
dict Mapping
See: Strings See: Lists
set, frozenset Set

bool Boolean If Else Loops

bytes, bytearray, memoryview Binary num = 200 for item in range(6):


if num > 0: if item == 3: break
print("num is greater than 0") print(item)
else: else:
print("num is not greater than 0") print("Finally finished!")

See: Data Types See: Flow control See: Loops

Functions File Handling

>>> def my_function(): with open("myfile.txt", "r", encoding='utf8') as file:


... print("Hello from a function") for line in file:
... print(line)
>>> my_function()
Hello from a function

See: Functions See: File Handling

Arithmetic Plus-Equals f-Strings (Python 3.6+)

result = 10 + 30 # => 40 counter = 0 >>> website = 'Quickref.ME'


result = 40 - 10 # => 30 counter += 10 # => 10 >>> f"Hello, {website}"
result = 50 * 5 # => 250 counter = 0 "Hello, Quickref.ME"
result = 16 / 4 # => 4.0 (Float Division) counter = counter + 10 # => 10
result = 16 // 4 # => 4 (Integer Division) >>> num = 10
result = 25 % 2 # => 1 message = "Part 1." >>> f'{num} + 10 = {num + 10}'
result = 5 ** 3 # => 125 '10 + 10 = 20'
# => Part 1.Part 2.
The / means quotient of x and y, and the // message += "Part 2."
means floored quotient of x and y, also see
StackOverflow See: Python F-Strings

# Python Built-in Data Types


Strings Numbers Booleans

hello = "Hello World" x = 1 # int my_bool = True


hello = 'Hello World' y = 2.8 # float my_bool = False
z = 1j # complex
multi_string = """Multiline Strings bool(0) # => False
Lorem ipsum dolor sit amet, >>> print(type(x)) bool(1) # => True
consectetur adipiscing elit """ <class 'int'>

See: Strings

Lists Tuple Set

list1 = ["apple", "banana", "cherry"] my_tuple = (1, 2, 3) set1 = {"a", "b", "c"}
list2 = [True, False, False] my_tuple = tuple((1, 2, 3)) set2 = set(("a", "b", "c"))
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))

See: Lists Similar to List but immutable Set of unique items/objects

Dictionary - Casting

Integers
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
x = int(1) # x will be 1
>>> a["one"]
y = int(2.8) # y will be 2
1
z = int("3") # z will be 3
>>> a.keys()
dict_keys(['one', 'two', 'three'])
Floats
>>> a.values()
dict_values([1, 2, 3]) x = float(1) # x will be 1.0
>>> a.update({"four": 4}) y = float(2.8) # y will be 2.8
>>> a.keys() z = float("3") # z will be 3.0
dict_keys(['one', 'two', 'three', 'four']) w = float("4.2") # w will be 4.2
>>> a['four']
4 Strings

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
Key: Value pair, JSON like object z = str(3.0) # z will be '3.0'

# Python Advanced Data Types


Heaps Stacks and Queues

import heapq from collections import deque

myList = [9, 5, 4, 1, 3, 2] q = deque() # empty


heapq.heapify(myList) # turn myList into a Min Heap q = deque([1, 2, 3]) # with values
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap q.append(4) # append to right side
q.appendleft(0) # append to left side
heapq.heappush(myList, 10) # insert 10 print(q) # => deque([0, 1, 2, 3, 4])
x = heapq.heappop(myList) # pop and return smallest item
print(x) # => 1 x = q.pop() # remove & return from right
y = q.popleft() # remove & return from left
Negate all values to use Min Heap as Max Heap print(x) # => 4
print(y) # => 0
myList = [9, 5, 4, 1, 3, 2] print(q) # => deque([1, 2, 3])
myList = [-val for val in myList] # multiply by -1 to negate
heapq.heapify(myList) q.rotate(1) # rotate 1 step to the right
print(q) # => deque([3, 1, 2])
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)

Deque is a double-ended queue with O(1) time for


Heaps are binary trees for which every parent node has a value less than or equal to any of its children. Useful append/pop operations from both sides. Used as
for accessing min/max value quickly. Time complexity: O(n) for heapify, O(log n) push and pop. See: Heapq stacks and queues. See: Deque

# Python Strings
Array-like Looping Slicing string

>>> hello = "Hello, World" >>> for char in "foo": ┌───┬───┬───┬───┬───┬───┬───┐


>>> print(hello[1]) ... print(char) | m | y | b | a | c | o | n |
e f └───┴───┴───┴───┴───┴───┴───┘
>>> print(hello[-1]) o 0 1 2 3 4 5 6 7
d o -7 -6 -5 -4 -3 -2 -1

Get the character at position 1 or last Loop through the letters in the word "foo" >>> s = 'mybacon'
>>> s[2:5]
'bac'
String Length Multiple copies >>> s[0:2]
'my'
>>> hello = "Hello, World!" >>> s = '===+'
>>> print(len(hello)) >>> n = 8
13 >>> s * n >>> s = 'mybacon'
'===+===+===+===+===+===+===+===+' >>> s[:2]
'my'
The len() function returns the length of a string
>>> s[2:]
'bacon'
Check String Concatenates
>>> s[:2] + s[2:]
'mybacon'
>>> s = 'spam' >>> s = 'spam' >>> s[:]
>>> s in 'I saw spamalot!' >>> t = 'egg' 'mybacon'
True >>> s + t
>>> s not in 'I saw The Holy Grail!' 'spamegg'
>>> s = 'mybacon'
True >>> 'spam' 'egg'
>>> s[-5:-1]
'spamegg'
'baco'
>>> s[2:6]
'baco'
Formatting

With a stride
name = "John"
print("Hello, %s!" % name)
>>> s = '12345' * 5
>>> s
name = "John" '1234512345123451234512345'
age = 23 >>> s[::5]
print("%s is %d years old." % (name, age)) '11111'
>>> s[4::5]
format() Method '55555'
>>> s[::-5]
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36) '55555'
txt2 = "My name is {0}, I'm {1}".format("John", 36) >>> s[::-1]
txt3 = "My name is {}, I'm {}".format("John", 36) '5432154321543215432154321'

Input Join Endswith

>>> name = input("Enter your name: ") >>> "#".join(["John", "Peter", "Vicky"]) >>> "Hello, world!".endswith("!")
Enter your name: Tom 'John#Peter#Vicky' True
>>> name
'Tom'

Get input data from console

# Python F-Strings (Since Python 3.6+)


f-Strings usage f-Strings Fill Align f-Strings Type

>>> website = 'Quickref.ME' >>> f'{"text":10}' # [width] >>> f'{10:b}' # binary type
>>> f"Hello, {website}" 'text ' '1010'
"Hello, Quickref.ME" >>> f'{"test":*>10}' # fill left >>> f'{10:o}' # octal type
'******test' '12'
>>> num = 10 >>> f'{"test":*<10}' # fill right >>> f'{200:x}' # hexadecimal type
>>> f'{num} + 10 = {num + 10}' 'test******' 'c8'
'10 + 10 = 20' >>> f'{"test":*^10}' # fill center >>> f'{200:X}'
'***test***' 'C8'
>>> f"""He said {"I'm John"}""" >>> f'{12345:0>10}' # fill with numbers >>> f'{345600000000:e}' # scientific notation
"He said I'm John" '0000012345' '3.456000e+11'
>>> f'{65:c}' # character type
>>> f'5 {"{stars}"}' 'A'
'5 {stars}' >>> f'{10:#b}' # [type] with notation (bas
>>> f'{{5}} {"stars"}' '0b1010'
'{5} stars' >>> f'{10:#o}'
'0o12'
>>> name = 'Eric' >>> f'{10:#x}'
>>> age = 27 '0xa'
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."

it is available since Python 3.6, also see:


Formatted string literals

F-Strings Others F-Strings Sign

>>> f'{-12345:0=10}' # negative numbers >>> f'{12345:+}' # [sign] (+/-)


'-000012345' '+12345'
>>> f'{12345:010}' # [0] shortcut (no align) >>> f'{-12345:+}'
'0000012345' '-12345'
>>> f'{-12345:010}' >>> f'{-12345:+10}'
'-000012345' ' -12345'
>>> import math # [.precision] >>> f'{-12345:+010}'
>>> math.pi '-000012345'
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # [grouping_option]
'1,000,000.00'
>>> f'{1000000:_.2f}'
'1_000_000.00'
>>> f'{0.25:0%}' # percentage
'25.000000%'
>>> f'{0.25:.0%}'
'25%'

# Python Lists
Defining Generate

>>> li1 = [] >>> list(filter(lambda x : x % 2 == 1, range(1, 20)))


>>> li1 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[]
>>> li2 = [4, 5, 6] >>> [x ** 2 for x in range (1, 11) if x % 2 == 1]
>>> li2 [1, 9, 25, 49, 81]
[4, 5, 6]
>>> li3 = list((1, 2, 3)) >>> [x for x in [3, 4, 5, 6, 7] if x > 5]
>>> li3 [6, 7]
[1, 2, 3]
>>> li4 = list(range(1, 11)) >>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
>>> li4 [6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Append - List Slicing

>>> li = [] Syntax of list slicing:


>>> li.append(1)
>>> li a_list[start:end]
[1] a_list[start:end:step]
>>> li.append(2)
>>> li Slicing
[1, 2]
>>> li.append(4) >>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> li >>> a[2:5]
[1, 2, 4] ['bacon', 'tomato', 'ham']
>>> li.append(3) >>> a[-5:-2]
>>> li ['egg', 'bacon', 'tomato']
[1, 2, 4, 3] >>> a[1:4]
['egg', 'bacon', 'tomato']

Omitting index

Remove >>> a[:4]


['spam', 'egg', 'bacon', 'tomato']
>>> li = ['bread', 'butter', 'milk'] >>> a[0:4]
>>> li.pop() ['spam', 'egg', 'bacon', 'tomato']
'milk' >>> a[2:]
>>> li ['bacon', 'tomato', 'ham', 'lobster']
['bread', 'butter'] >>> a[2:len(a)]
>>> del li[0] ['bacon', 'tomato', 'ham', 'lobster']
>>> li >>> a
['butter'] ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

With a stride
Access

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']


>>> li = ['a', 'b', 'c', 'd']
>>> a[0:6:2]
>>> li[0]
['spam', 'bacon', 'ham']
'a'
>>> a[1:6:2]
>>> li[-1]
['egg', 'tomato', 'lobster']
'd'
>>> a[6:0:-2]
>>> li[4]
['lobster', 'tomato', 'egg']
Traceback (most recent call last):
>>> a
File "<stdin>", line 1, in <module>
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
IndexError: list index out of range
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

Concatenating Sort & Reverse Count

>>> odd = [1, 3, 5] >>> li = [3, 1, 3, 2, 5] >>> li = [3, 1, 3, 2, 5]


>>> odd.extend([9, 11, 13]) >>> li.sort() >>> li.count(3)
>>> odd >>> li 2
[1, 3, 5, 9, 11, 13] [1, 2, 3, 3, 5]
>>> odd = [1, 3, 5] >>> li.reverse()
>>> odd + [9, 11, 13] >>> li Repeating
[1, 3, 5, 9, 11, 13] [5, 3, 3, 2, 1]
>>> li = ["re"] * 3
>>> li
['re', 're', 're']

# Python Flow control


Basic One line else if

num = 5 >>> a = 330 value = True


if num > 10: >>> b = 200 if not value:
print("num is totally bigger than 10.") >>> r = "a" if a > b else "b" print("Value is False")
elif num < 10: >>> print(r) elif value is None:
print("num is smaller than 10.") a print("Value is None")
else: else:
print("num is indeed 10.") print("Value is True")

# Python Loops
Basic With index While

primes = [2, 3, 5, 7] animals = ["dog", "cat", "mouse"] x = 0


for prime in primes: # enumerate() adds counter to an iterable while x < 4:
print(prime) for i, value in enumerate(animals): print(x)
print(i, value) x += 1 # Shorthand for x = x + 1

Prints: 2 3 5 7 Prints: 0 dog 1 cat 2 mouse Prints: 0 1 2 3

Break Continue Range

x = 0 for index in range(3, 8): for i in range(4):


for index in range(10): x = index * 10 print(i) # Prints: 0 1 2 3
x = index * 10 if index == 5:
if index == 5: continue for i in range(4, 8):
break print(x) print(i) # Prints: 4 5 6 7
print(x)
for i in range(4, 10, 2):
Prints: 0 10 20 30 40 Prints: 30 40 60 70 print(i) # Prints: 4 6 8

With zip() for/else

words = ['Mon', 'Tue', 'Wed'] nums = [60, 70, 30, 110, 90]
nums = [1, 2, 3] for n in nums:
# Use zip to pack into a tuple list if n > 100:
for w, n in zip(words, nums): print("%d is bigger than 100" %n)
print('%d:%s, ' %(n, w)) break
else:
print("Not found!")

Prints: 1:Mon, 2:Tue, 3:Wed, Also see: Python Tips

# Python Functions
Basic Return Positional arguments

def hello_world(): def add(x, y): def varargs(*args):


print('Hello, World!') print("x is %s, y is %s" %(x, y)) return args
return x + y
varargs(1, 2, 3) # => (1, 2, 3)
add(5, 6) # => 11

Keyword arguments Returning multiple Default Value

def keyword_args(**kwargs): def swap(x, y): def add(x, y=10):


return kwargs return y, x return x + y

# => {"big": "foot", "loch": "ness"} x = 1 add(5) # => 15


keyword_args(big="foot", loch="ness") y = 2 add(5, 20) # => 25
x, y = swap(x, y) # => x = 2, y = 1

Anonymous functions

# => True
(lambda x: x > 2)(3)

# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)

# Python Modules
Import modules From a module Import all

import math from math import ceil, floor from math import *
print(math.sqrt(16)) # => 4.0 print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0

Shorten module Functions and attributes

import math as m import math


dir(math)
# => True
math.sqrt(16) == m.sqrt(16)

# Python File Handling


- Read file - String - Object

Line by line Write a string Write an object

with open("myfile.txt") as file: contents = {"aa": 12, "bb": 21} contents = {"aa": 12, "bb": 21}
for line in file: with open("myfile1.txt", "w+") as file: with open("myfile2.txt", "w+") as file:
print(line) file.write(str(contents)) file.write(json.dumps(contents))

With line number Read a string Read an object

file = open('myfile.txt', 'r') with open('myfile1.txt', "r+") as file: with open('myfile2.txt', "r+") as file:
for i, line in enumerate(file, start=1): contents = file.read() contents = json.load(file)
print("Number %s: %s" % (i, line)) print(contents) print(contents)

Delete a File Check and Delete Delete Folder

import os import os import os


os.remove("myfile.txt") if os.path.exists("myfile.txt"): os.rmdir("myfolder")
os.remove("myfile.txt")
else:
print("The file does not exist")

# Python Classes & Inheritance


Defining Constructors Method

class MyNewClass: class Animal: class Dog:


pass def __init__(self, voice):
self.voice = voice # Method of the class
# Class Instantiation def bark(self):
my = MyNewClass() cat = Animal('Meow') print("Ham-Ham")
print(cat.voice) # => Meow
charlie = Dog()
dog = Animal('Woof') charlie.bark() # => "Ham-Ham"
print(dog.voice) # => Woof

Class Variables Super() Function repr() method

class MyClass: class ParentClass: class Employee:


class_variable = "A class variable!" def print_test(self): def __init__(self, name):
print("Parent Method") self.name = name
# => A class variable!
print(MyClass.class_variable) class ChildClass(ParentClass): def __repr__(self):
def print_test(self): return self.name
x = MyClass() print("Child Method")
# Calls the parent's print_test() john = Employee('John')
# => A class variable! super().print_test() print(john) # => John
print(x.class_variable)

>>> child_instance = ChildClass()


User-defined exceptions
>>> child_instance.print_test()
Child Method class CustomError(Exception):
Parent Method pass

Polymorphism Overriding Inheritance

class ParentClass: class ParentClass: class Animal:


def print_self(self): def print_self(self): def __init__(self, name, legs):
print('A') print("Parent") self.name = name
self.legs = legs
class ChildClass(ParentClass): class ChildClass(ParentClass):
def print_self(self): def print_self(self): class Dog(Animal):
print('B') print("Child") def sound(self):
print("Woof!")
obj_A = ParentClass() child_instance = ChildClass()
obj_B = ChildClass() child_instance.print_self() # => Child Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
obj_A.print_self() # => A print(Yoki.legs) # => 4
obj_B.print_self() # => B Yoki.sound() # => Woof!

# Miscellaneous
Comments Generators Generator to list

# This is a single line comments. def double_numbers(iterable): values = (-x for x in [1,2,3,4,5])
for i in iterable: gen_to_list = list(values)
yield i + i
""" Multiline strings can be written
# => [-1, -2, -3, -4, -5]
using three "s, and are often used
print(gen_to_list)
as documentation.
"""

''' Multiline strings can be written


using three 's, and are often used
as documentation.
''' Generators help you make lazy code.

Handle exceptions

try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")

Related Cheatsheet Recent Cheatsheet


QuickRef.ME
Awk Cheatsheet Bash Cheatsheet Remote Work Revolution Homebrew Cheatsheet
Share quick reference and cheat sheet for
Quick Reference Quick Reference Quick Reference Quick Reference
developers.

中文版 #Notes
PyTorch Cheatsheet Taskset Cheatsheet
Quick Reference Quick Reference

© 2023 QuickRef.ME, All rights reserved.

You might also like