NAVIGATE

RESOURCES

CHEATSHEETS

INFO

Python3 Cheatsheet

A ready-to-use page to support your daily code development in Python3!

Python3

img
Python logo

Python 3 is a versatile and powerful high-level programming language known for its simplicity, readability, and ease of use. It offers a rich set of libraries and frameworks, making it suitable for a wide range of applications, including web development, data analysis, machine learning, artificial intelligence, scientific computing, and automation. Python's clean syntax and dynamic typing promote rapid development and prototyping, while its extensive standard library provides robust support for various tasks. With a vibrant community and active development, Python 3 continues to evolve, remaining one of the most popular languages among developers worldwide.

Importing libraries

0
1
2
3
4
# Modules and Packages
import module_name
from module_name import function_name
from module_name import *

Variables

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Variables and Data Types
intVar = 10
strVar = "Some text"
boolVar = True
floatVar = 3.14
listVar = [1, 3, 5, "Text element", 3.4526]
multidimListVar = [ [[2,3,4],[6,7,8],[10,15,20]] , [[11,22,33],[66,77,88],[100,150,200]] , [[0,-1,-2],["strange","c",3.14],[2,2,2]] ]
tupleVar = (1, 4, 6, 7)
dictVar = {"key":"value", "4":"value2", "Some key data": "Some value data"}

# Integer Variable Base
decVar = 423
hexVar = 0xfe34
binVar = 0b0110101
octVar = 0o3216

Operations

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Arithmetics
a = 45
b = 3
resA = a+b     # Sum
resB = a-b     # Subtraction
resC = a*b     # Multiplication
resD = a/b     # Integer division
resE = a**b    # Power (a^b)
resF = a%b     # Modulus

# Bitwise Operators
a = 0x01f3
b = 0x243
resA = a&b     # Bitwise AND
resB = a|b     # Bitwise OR
resC = a^b     # Bitwise XOR
resD = ~a      # Bitwise NOT
resE = a<<3    # Left shift
resF = a>>3    # Right shift

# Shorthand Operators
a += 32        # Update a with the result of a+32
a -=45         # Update a with the result of a-45
a *= 21        # Update a with the result of a/21
a /= 12        # Update a with the result of a/12
a &= 0b11110   # Update a with the result of a&0b11110
a |= 0x3fe     # Update a with the result of a|0x3fe
a ^= 0x43f     # Update a with the result of a^0x43f
a <<= 3        # Update a with the result of a<<3
a >>= 2        # Update a with the result of a>>2

Operations on Vectorial Data Structures

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#Strings
strVar = "Here's a string!"
strVar = strVar + " Now I'm adding another string!"
substrVar1 = strVar[:17]    # substrVar1 contains characters from the 1st (included) to the 17th character (not included)
substrVar2 = strVar[18:]    # substrVar1 contains characters from the 18th (included) to the last character (included)
substrVar3 = strVar[10:16]  # substrVar1 contains characters from the 10th (included) to the 16th character (not included)
tokensVar1 = strVar.split(" ")      # Split string with the given character; this returns a list
tokensVar2 = strVar.split(" ",2)    # Split string with the given character with a maximum of 2 times (first 2 occurrences)
newStrVar1 = strVar.replace("!","!!!")   # Replace all occurrences of a char sequence with another char sequence
newStrVar2 = strVar.replace("!","!!!",1) # Replace just the first occurrence of a char sequence with another char sequence

# Lists
listVar = [2, 3, 4, 5, 6, 7, 2, 2, 8, 9, 10]
listVar.pop()              # Remove the last item from the list
listVar.append(10)         # Append 10 as last item
listVar.count()            # Return the number of items in the list
listVar.remove(2)          # Remove the first occurrence of element 2
listVar.sort()             # Sort in ascending order
listVar.sort(reverse=True) # Sort in descending order
listVar = ["a", "ab", "abcdef", "abc", "abcdefghi"]
listVar.sort(key=len)      # String length based ascending order
newList = listVar[:2]     # newList contains elements of listVar from the 1st (included) to the 2nd one (not included)
newList = listVar[2:]     # newList contains elements of listVar from the 2nd (included) to the last one (included)
newList = listVar[2:3]    # newList contains elements of listVar from the 2nd (included) to the 3rd one (not included)

# Tuples - immutable list of elements
tupleVar = ("Some prime number", 2, 3, 5, 7, 11, 13, 17, 23, "Some float number", 3.14, 2.7) # Tuple definition. It can't be changed anymore!
nOccurr2 = tupleVar.count(2)    # Return the number of occurrences of element 2
indexOf2 = tupleVar.index(2)    # Return the index of first occurrence of element 2
anotherTuple = tupleVar[3:6]    # anotherTuple contains tupleVar elements, from the 3rd (included) to the sixth (not included)
tupleVar[4] = 9                 # THIS RAISES AN ERROR!

# Dictionaries
dictVar = {"Name":"John", "Surname":"Clayton", "Age":35, "Height"=1.81, "Signs":["Glasses", "Blonde-haired"]}
dictValue = dictVar["Name"]         # Get the value of a key
dictValue = dictVar.get("Name")     # Get the value of a key
dictVar["Name"] = "Michael"         # Update a value
dictVar.update({"Name":"Michael"})  # Update a value
dictVar["Foot"] = 8                 # Add a pair
dictVar.update({"Foot":8})          # Add a pair
values = dictVar.values()           # Returns all dictVar values 
keys = dictVar.keys()               # Returns all dictVar keys
dictVar.pop("Name")                 # Removes the key:value pair with specified key
dictVar.popitem()                   # Removes the last inserted pair
dictVar.clear()                     # Empties the whole dictionary

Control Flow

0
1
2
3
4
5
6
7
# if-else Control Flow
if condition:
    # code block
elif another_condition:
    # code block
else:
    # code block

Loops

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# for Loop
for item in iterable:
    # code block
    if condition:
        #code block
        continue
    else:
        #code block
        break

# while Loop    
while condition:
    # code block
    if condition:
        #code block
        continue
    else:
        #code block
        break

Functions

0
1
2
3
4
# Functions
def my_function(param1, param2=default_value):
    # code block
    return result

Exception Handling

0
1
2
3
4
5
6
7
8
9
10
11
12
13
# Exception Handling
try:
    # code block
except ExceptionType1 as e1:
    # handle exception1
except ExceptionType2 as e2:
    # handle exception2
except:
    # handle all the remaining exceptions
else:
    # code executed if no exception is risen
finally:
    # code always executed, both if an exception is risen or not

Comments

0
1
2
3
4
5
6
# This is a single-line comment

"""
This is a
multi-line comment
"""

Input/Output

0
1
2
user_input = input("Enter something: ")
print("You entered: ", user_input)

File handling

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#File Handling

"""
filename is a string containing the path+name of the file to be opened
mode can be r=read-only (default), w=write-only (old file with same name is replaced) 
            a=append, r+ = read-and-write, rb/wb/ab=read/write/append in binary mode
encoding is a string thta specifies the encoding of the file
"""

"""
Preferable way to open a file 
In this way, file is safely written, then closed (you don't have to call fp.close())
"""
with open(filename, mode, encoding) as fp:    
    # Do something with fp      

"""    
Another way to open a file
In this way, if close() is called immediately after write(), file could be closed before
all data is written! Use the first way instead
"""
fp = open(filename, mode,encoding)

fp.close()                  # Close the file, saving all modifications
fp.write("Hello, World!")   # Write the specified string in the file pointed by fp
fp.writelines(stringList)   # Write a list of strings (you must append \n to each line)
content = fp.read()         # Read the whole file content and store it in a variable
row = fp.readline()         # Read just one line of the file (read till \n)
rows = fp.readlines()       # Returns a list where elements are lines (split using \n as needle)
fp.seek(byteNumber)         # Move the file cursor to byteNumber position of the file
byteNumber = fp.tell()      # Return the position of the cursors

# Alternative way to read and elaborate one line at a time
for line in fp:
    # Do something with line

Share this page

Whatsapp Facebook LinkedIn Reddit Twitter Mail

Comments

Please, remember to always be polite and respectful in the comments section. In case of doubts, read this before posting.

Posted comments ⮧

Marian2025-01-06 16:25:58

Can you add info about the variables scope? I think it coul be helpful thanks

If you liked

🍵
♥