Skip to content

master Python3

programming-banner

Introduction

Python is one of the most popular programming languages in the world. It is an interpreted, high-level, general-purpose programming language that is used for web development, data analysis, machine learning, and more. Python 3 is the latest version of Python, and it comes with many new features and improvements. In this blog post, we will provide you with a cheatsheet of Python3 to help you get started with this powerful programming language.

programming-banner

Packages and Builtin Functions

dir()
float()
int()
len()
list()
max()
min()
print()
round()
str()
type()
abs()
help()

Data Types

<class "int">
<class "float">
<class "str">

x = 3+5j
x.real
x.imag
a = 3
b = 5
c = complex(a, b)

y = bytearray(6)
z = memoryview(bytes(5))

Operators

a = []
b = []
a is b
### False
a == b
### True

Dates

from datetime import date as d
d.today()
str(d.today())

Lists

l.pop()
l.pop(4)
l.append(9)
l.remove(9)
l.count(1)
l.reverse()
l.sort()
len(l)
l[-len(l)]
l[1:3]
l[1:]
l[-1:]
### last one
l[:-1]
### except last one
9 in l
3 not in l
range(1,9,2)

Tuples

### can't be modified
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers[0]
numbers[-2]
numbers[:-3]
numbers.count(2)
numbers.index(2)

Dictionaries

dict_detail = {}
dict_detail["first name"] = "Rob"

person_details = dict(first_name="Rob", surname="Mastrodomenico",
    gender="Male", favourite_food="Pizza")
personal_details.clear()
personal_details.items()
list(personal_details.items())[0]
personal_details.keys()
personal_details.values()

x = ('key1', 'key2', 'key3')
y = 0
res = dict.fromkeys(x, y)

Sets

### storing unique values
names = {'Tony','Peter','Natasha','Wanda'}
names = set(('Tony','Peter','Natasha','Wanda', 1, 2, 3))
names = set(['Tony','Peter','Natasha','Wanda', 1, 2, 3])
names = set('Wanda')
names.add('Steve')

names.union(more_names)

names & more_names
names.intersection(more_names)
names & more_names & even_more_names

names - more_names
names.difference(more_names)
names - more_names - even_more_names
names.difference(more_names, even_more_names)

names ^ more_names
names.symmetric_difference(more_names)
names | more_names
names.isdisjoint(more_names)
names.issubset(more_names)
names.issuperset(more_names)

names.pop()
names.add('Bruce')
names.remove('Tony')
### if not exists, return KeyError
names.discard('Sue')
### always return True no matter key exists or not
names.clear()

frozen_names = frozenset({'Tony','Peter','Natasha','Wanda'})
### cannot be altered

Strings

single_quote_string = 'string with a \' single quote'
single_quote_string = """string with a ' single quote"""
raw_string = r"This has a \n in it"
not_raw_string = "This has a \n in it"
name.lower()
name.upper()
name.split(" ")
match_details.replace(",",":")
match_details = ','.join(details)

Regular Expressions

import re
re.findall("[a-m]", name)
### find specific character
re.findall("\d", txt)
re.findall("[0-9]", txt)
### find integer
re.findall("he..o", txt)
re.findall("^start", txt)
re.findall("end$", txt)
re.findall("aix*", txt)
### ai followed by 0 or more x
re.findall("aix+", txt)
### ai followed by one or more x
re.findall("mo{2}", txt)
re.findall("avengers|heroes", txt)
re.findall("\s", txt)
### find space
re.split("\s", txt, maxsplit=2)
re.sub("\s", "9", txt, 3)
re.search("ai", txt)
  • \A: “\AIt”
  • \b: at the beginning or at the end of a word
  • \B: NOT at the beginning (or at the end) of a word
  • \d: digits (numbers from 0-9)
  • \D: DOES NOT contain digits
  • \s: white space character
  • \S: DOES NOT contain a white space character
  • \w: any word characters (characters from a to Z, digits from 0-9, and the underscore _ character)
  • \W: DOES NOT contain any word characters

Variables and Data Types

Variables are used to store data in a program. Python3 supports several data types, including integers, floats, strings, and boolean values. Here are some examples of how to declare and initialize variables in Python3:

x = 5    # integer
y = 3.14 # float
name = "John" # string
is_active = True # boolean

In Python3, variables do not need to be declared before they are used, unlike other programming languages such as C or Java. This makes Python3 code shorter and more readable.

Control Flow Statements

Control flow statements are used to control the flow of execution in a program. Python3 supports several control flow statements, including if-else statements, loops, and switch statements. Here are some examples of how to use control flow statements in Python3:

# if-else statement
if x > y:
    print("x is greater than y")
else:
    print("y is greater than x")

# for loop
for i in range(10):
    print(i)

# while loop
i = 0
while i < 10:
    print(i)
    i += 1

Python3 does not have a built-in switch statement, but it can be emulated with a dictionary.

Functions and Modules

Functions are reusable blocks of code that perform specific tasks. Modules are collections of functions that can be imported into a program. Python3 supports both functions and modules, and they can be used to organize and simplify code. Here are some examples of how to define functions and use modules in Python3:

# function definition
def add(x, y):
    return x + y

# module import
import math
print(math.sqrt(16))

In Python3, functions can have default argument values and can return multiple values. Modules can be used to import code from other files, making it easier to organize and reuse code.

Reference

  • The Python Book (Rob Mastrodomenico)
  • https://regexr.com
Leave a message