Python CheatSheet

If you're looking to take your Python programming skills to the next level, our professional and comprehensive Python cheat sheet is just what you need. With clear and concise explanations of syntax, data structures, functions, and more, this cheat sheet is an invaluable tool for developers of all levels.

Whether you're a beginner or an experienced programmer, our Python cheat sheet provides you with essential information that can save you time and dramatically improve your coding capabilities. When you have a quick reference to commonly used commands and concepts right at your fingertips, you'll be able to work more efficiently and confidently on projects of all sizes.

So why wait? Download our expertly crafted Python cheat sheet today and give your coding skills the boost they deserve!


Table of Content




# Getting started Python


What is Python ?

Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.

Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library.

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

  • web development (server-side).
  • software development.
  • mathematics.
  • system scripting.

Data Types

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

Variables

yourAge = 26      # yourAge variable now is of type int
yourName = "William Jack" # yourName variable now is now of type str
print(name)
# Result: William Jack

Slicing a String

yourMsg = "Hello, Wellcome to bestforstudy !"
print(yourMsg[2:5])
# Result: llo

Lists

yourList = []
yourList.append(1) # Your list now is List int
yourList.append(2) # Your list now is List int

# Print out the list
for item in mylist:
    print(item)
# Result: 1
# Result: 2

If Else

number = 500
if number > 100:
    print("number is greater than 100")
else:
    print("number is not greater than 100")
# Result: number is greater than 100

Loops

for item in range(100):
    if item == 50: 
        break
    print(item)
else:
    print("Finish loop !!")

Functions

def yourFunction():
    print("This is inside your function")

# execute function
yourFunction()
# Result: This is inside your function

File Handling

with open("yourFile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)

# yourFile.txt: this is path where your file locate
# encoding: is encoding when handle your file. At here, it is utf-8 encoding

Arithmetic

result = 15 + 35 # => 50
result = 45 - 15 # => 30
result = 50 * 10  # => 500
result = 16 / 4  # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2  # => 1
result = 5 ** 3  # => 125

Plus-Equals

# this way
counterNumber = 5
counterNumber += 15 # Result: 20

# Equal to this way
counterNumber = 5
counterNumber = counterNumber + 15  # Result: 20

# Plus Equals with String
message = "Welcome to "
message += "bestforstudy.com"
# Result: Welcome to bestforstudy.com

f-Strings (Python 3.6+)

yourWebsite = 'bestforstudy.com'
f"Hello, Welcome to {website}"
# Result: "Hello, Welcome to bestforstudy.com"

num = 100
f'{num} + 10 = {num + 10}'
# Result: '10 + 10 = 20'

# Data Types Python


Strings

message = "First way to declare a String"
message = 'Another way to declare a String'

multilineString = """First way to declare multiple line String,
Hello everyone,
This is an example !!!"""

multilineString = '''First way to declare multiple line String,
Hello everyone,
This is an example !!!'''

Numbers

x = 10    # int type
y = 5.9  # float type
z = 3j   # complex type

print(type(x))
# Result: class 'int'

Booleans

yourBool = True 
yourBool = False

bool(0)     # Result: False
bool(1)     # Result True

Lists

yourList1 = ["tank", "car", "plan"]
yourList2 = [True, False, False]
yorList3 = [1, 2, 6, 9, 0]
yourList4 = list((4, 6, 8, 7,3, 0))

Tuple

yourTuple = (3, 5, 7)
yourTuple = tuple((3, 5, 7))

Set

yourSet1 = {"a", "b", "c", "d", "e"}   
yourSet2 = set(("a", "b", "c", "d", "e"))

Dictionary

# Empty Dict
your_empty_dict = {}

a = {"one": 1, "two": 2, "three": 3}
a["one"]
# Result: 1

# Your dict key
a.keys()
your_dict_keys(['one', 'two', 'three'])

# Your dict value
a.values()
your_dict_values([1, 2, 3])

# Add a key:val to dict
a.update({"four": 4})
a.keys()

# Your Result after add key:val
your_dict_keys(['one', 'two', 'three', 'four'])
a['four']
# Result: 4

Casting

# Integers
x = int(10)  # value of x is 10
y = int(1.5) # value of y is 1
z = int("30") # value of z is 30

# Floats
x = float(11)     # value of x is 11.0
y = float(2.9)   # value of y is 2.9
z = float("2")   # value of z is 2.0
w = float("5.2") # value of w is 5.2

# Strings
x = str("string1") # value of x is 'string1'
y = str(200)    # value of y is '200'
z = str(2.0)  # value of z is '2.0'

# String Python


Array-like

yourString = "Hello, Wellcome to bestforstudy.com"

print(yourString[1])
# Result: e

print(yourString[-1])
# Result: m

Looping

for char in "HelloWorld":
   print(char)
#Result: 
H
e
l
l
o
W
o
r
l
d

String Length

yourString = "bestforstudy.com"
print(len(yourString))
# Result: 18

Multiple copies

yourString = '===+'
n = 8
yourString * n

# Result:
'===+===+===+===+===+===+===+===+'

Check String

yourFullString = "bestforstudy.com"
yourSubString = "cheatsheet"

if yourSubString in yourFullString:
    print("Your String Found!")
else:
    print("Your String Not found!")

# Result: Your String Found!

Concatenates

# First way
str1="Hello"
str2="World"
str=str1+str2
print(str)
# Result: HelloWorld

# Second way
str1="Hello"
str1=str1*3
print("Concatenated same string:",str1)

Formatting

# First way
name = "William"
print("Hello, %s!" % name)
# Result: Hello William!

name = "Yasuo"
age = 29
print("%s is %d years old." % (name, age))
# Result: Yasuo is 29 years old.

# Second way using format() method
txt1 = "My name is {fname}, I'm {age}".format(fname = "William", age = 40)
txt2 = "My name is {0}, I'm {1}".format("John",15)
txt3 = "My name is {}, I'm {}".format("John",30)

Input

yourName = input("Please, Enter your name: ")
>>> Please, Enter your name: Rec
name
'Rec'

Join

yourString = ",".join(["Banana", "Apple", "Orange"])
print(yourSring)

# Result: Banana,Apple,Orange

Endswith

"bestforstudy.com".endswith(".com")
# Result: True

# Python F-Strings (Since Python 3.6+)


What is f-Strings in Python ?

New in version 3.6.

A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.

f-Strings usage

myWebsite = 'bestforstudy.com'
print(f"Hello, {myWebsite}")
# Result: "Hello, bestforstudy.com"

num = 1num = 100
f'{num} + 10 = {num + 10}'
# Result: '10 + 10 = 20'

f"""She said {"I'm Jess"}"""
# Result: "She said I'm Jess"

f'5 {"{stars}"}'
# Result: '5 {stars}'
f'{{5}} {"stars"}'
# Result: '{5} stars'

name = 'Jhin'
age = 30
f"""Hello!
     I'm {name}.
     I'm {age}."""
# Result: "Hello!\n    I'm Jhin.\n    I'm 30."

f-Strings Fill Align

# [width]
f'{"width":11}'
# Result: 'width       '

# fill left
f'{"left":*>10}'   
# Result: '******left'

# fill right
f'{"right":*<10}'   
# Result: 'right******'

# fill center
f'{"center":*^10}'   
'***center***'

# fill with numbers
f'{12345:0>10}'    
# Result: '0000012345'

f-Strings Type

# binary type
f'{10:b}'        
# Result: '1010'

# octal type
f'{10:o}'        
# Result: '12'

# hexadecimal type
f'{200:x}'       
# Result: 'c8'

f'{200:X}'
# Result: 'C8'

# scientific notation
f'{345600000000:e}' 
# Result: '3.456000e+11'

# character type
f'{65:c}'       
# Result: 'A'

# [type] with notation (base)
f'{10:#b}'      
# Result: '0b1010'

f'{10:#o}'
# Result: '0o12'

f'{10:#x}'
# Result: '0xa'

F-Strings Others

# negative numbers
f'{-13579:0=10}'  
# Result: '-000013579'

# [0] shortcut (no align)
f'{13579:010}'    
# Result: '0000013579'

f'{-13579:010}'
# Result: '-000012345'

# [.precision]
import math       
math.pi
# Result: 3.141592653589793

f'{math.pi:.2f}'
# Result: '3.14'

# [grouping_option]
f'{4000000:,.2f}' 
# Result: '4,000,000.00'

f'{5000000:_.2f}'
# Result: '5_000_000.00'

# percentage
f'{0.25:0%}'      
# Result: '25.000000%'

f'{0.25:.0%}'
# Result: '25%'

F-Strings Sign

# [sign] (+/-)
f'{13579:+}'      
# Result: '+13579'

f'{-13579:+}'
# Result: '-13579'

f'{-13579:+10}'
# Result: '    -13579'

f'{-13579:+010}'
# result: '-000013579'

# Lists in Python


How to Define ?

list1 = []
print(list1)
# Result: []

list2 = [4, 5, 6]
print(list2)
# Result: [4, 5, 6]

list3 = list((1, 2, 3))
print(list3)
# Result: [1, 2, 3]

list4 = list(range(1, 11))
print(list4)
# Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

Generate

# First way to generate list with condition
list(filter(lambda x : x % 2 == 1, range(1, 20)))
# Result: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

# Second way to generate list with condition
list(filter(lambda x: x > 6, [3, 4, 5, 6, 7, 8, 9, 10]))
# Result: [7, 8, 9, 10]

# Third way to generate list with condition
[x ** 2 for x in range (1, 11) if  x % 2 == 1]
# Result: [1, 9, 25, 49, 81]

# Final way to generate list with condition
[x for x in [3, 4, 5, 6, 7, 8, 9, 10] if x > 6]
# Result: [7, 8, 9, 10]

Append

# Empty list
li = []

li.append(10)
print(li)
# Result: [10]

li.append(20)
print(li)
# Result: [10, 20]

li.append(4)
print(li)
# Result: [10, 20, 4]

li.append(30)
print(li)
# Result: [10, 20, 4, 30]

Remove

li = ['a', 'b', 'c']
print(li.pop())
# Result: 'c'

print(li)
# Result: ['a', 'b']

del li[0]
print(li)
# Result: ['b']

Access

li = ['apple', 'banana', 'coconut', 'durian']

# Get first value
print(li[0])
'apple'

# Get last value
li[-1]
print('durian')

# This will raise error
print(li[4])
# Traceback (most recent call last): 
# File "<stdin>", line 1, in <module>
# IndexError: list index out of range

Concatenating

# First way
yourList = [10, 30, 50]
yourList.extend([90, 11, 13])
print(yourList)
# Result: [10, 30, 50, 90, 11, 13]

# Second way
yourList = [10, 30, 50]
yourList + [90, 11, 13]
# Result: [10, 30, 50, 90, 11, 13]

Count

# Define a list
li = [3, 1, 3, 2, 5]
print(li.count(3))
# Result: 2

Repeating

li = ['abc'] * 3
print(li)
['abc', 'abc', 'abc']

Sort & Reverse

# Define a list
li = [35, 15, 36, 23, 50]
li.sort()
print(li)
# Result: [15, 23, 35, 36, 50]

li.reverse()
print(li)
# Result: [50, 36, 35, 23, 15]

List Slicing

# Syntax of list slicing:
a_list[start:end]
a_list[start:end:step]

# Slicing
a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
a[2:5]
['bacon', 'tomato', 'ham']
a[-5:-2]
['egg', 'bacon', 'tomato']
a[1:4]
['egg', 'bacon', 'tomato']


# Omitting index
a[:4]
['spam', 'egg', 'bacon', 'tomato']
a[0:4]
['spam', 'egg', 'bacon', 'tomato']
a[2:]
['bacon', 'tomato', 'ham', 'lobster']
a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']


# With a stride
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
a[0:6:2]
['spam', 'bacon', 'ham']
a[1:6:2]
['egg', 'tomato', 'lobster']
a[6:0:-2]
['lobster', 'tomato', 'egg']
a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

# Flow control in Python


Basic

number = 15
if number > 12:
    print("number is bigger than 10.")
elif num < 12:
    print("number is smaller than 10.")
else:
    print("num is equal 12.")
# Result: number is bigger than 10.

One line

numberA = 330
numberB = 200
result = "numberA" if numberA > numberB else "numberB"
print(result)
# Result: numberA

else if

value = True
if not value:
    print("Value is False")
elif value is None:
    print("Value is None")
else:
    print("Value is True")

# Loops in Python


Basic

numberArr = [1, 2, 3, 4, 5, 6, 7]
for number in numberArr:
    print(number)
# Result: 1, 2, 3, 4, 5, 6, 7

With index

sports = ["swimming", "football", "baseball"]
for i, value in enumerate(sports):
    print(i, value)

While

number = 0
while number < 10:
    # Write your logic here ....
    print(number)
    number += 1  # Shorthand for number = number + 1

Break

for letter in 'Python':     
   if letter == 'h':
      break
   print 'Current Letter :', letter

# Result: 
# Current Letter : P
# Current Letter : y
# Current Letter : t

Continue

for i in range(9):
  if i == 3:
    continue
  print(i)
# Result: 0, 1, 2, 4, 5, 6, 7, 8

Range

for i in range(4):
    print(i) 
# Result: 0 1 2 3

for i in range(4, 8):
    print(i) 
# Result: 4 5 6 7

for i in range(4, 10, 2):
    print(i) 
# Result: 4 6 8

With zip()

yourName = ['Harry', 'Petter', 'Alex']
age = [14, 35, 25]
for n, a in zip(name, age):
    print('%s is %d years old' %(n, a))
# Result: 
# Harry is 14 years old
# Petter is 35 years old
# Alex is 25 years old

List Comprehension

result = [x**2 for x in range(10) if x % 2 == 0]
 
print(result)
# [0, 4, 16, 36, 64]

# Functions in Python


Basic Define

def basicFunc():  
    print('Hello, Wellcome to bestforstudy.com!')

Return Function

def addFunc(x, y):
    print("x is %s, y is %s" %(x, y))
    return x + y

addFunc(10, 25)    
# Result: 35

Positional arguments

def varargs(*args):
    return args

varargs(1, 2, 3)  
# Result: (1, 2, 3)

Keyword arguments

def keyword_args(**kwargs):
    return kwargs

keyword_args(big="foot", loch="ness")
# Result {"big": "foot", "loch": "ness"}

Returning multiple

def swap(x, y):
    return y, x

x = 1
y = 2
x, y = swap(x, y)  
# Result: x = 2, y = 1

Default Value

def add(x, y=10):
    return x + y

add(5)      
# Result: 15

add(5, 20)  
# Result: 25

Anonymous functions

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

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

# Modules in Python


Import modules

import math

print(math.sqrt(16))  
# Result: 4.0

From a module

from math import ceil, floor

print(ceil(3.7))   
# Result: 4.0

print(floor(3.7))  
# Result: 3.0

Import all

from functions import *

print(cube(3))

Shorten module

import math as m

math.sqrt(16) == m.sqrt(16)
# Result: True

Functions and attributes

import math

dir(math)


Best Suggest