Basics of Python Programming
Basics of Python Programming
# Arithmetic Operators
a = 10
b = 3
c = a + b # Addition
d = a – b # Subtraction
e = a * b # Multiplication
f = a / b # Division
g = a // b # Floor division (quotient/integer, rounded down)
h = a % b # Modulo
i = a ** b # Exponentiation
# Comparison Operators
a = 10
b = 3
c = a == b # Equal to
d = a != b # Not equal to
e = a < b # Less than
f = a > b # Greater than
g = a <= b # Less than or equal to
h = a >= b # Greater than or equal to
# Logical Operators
a = 10
b = 3
c = (a > 5) and (b < 7) # Logical AND
d = (a > 5) or (b > 7) # Logical OR
e = not (a > b) # Logical NOT
4. Assignment Operators: Used to assign values to variables.
# Assignment Operators
a = 10 # Simple assignment
b += 3 # Add and assign
c -= 5 # Subtract and assign
d *= 2 # Multiply and assign
e /= 4 # Divide and assign
e //= 4 # Floor divide and assign
g %= 2 # Modulo and assign
h **= 2 # Exponentiate and assign
# Bitwise Operators
a & b # Bitwise AND
a | b # Bitwise OR
a ^ b # Bitwise XOR
~a # Bitwise NOT
a << b # Bitwise left shift
a >> b # Bitwise right shift
# Identity Operators
a = [1, 2, 3]
b = a
c = [1, 2, 3]
# Membership Operators
a = [1, 2, 3]
b = a
c = [1, 2, 3]
List of Operands
# Built-in Functions
# Numeric literals
x = 10 # Integers
y = -5 # Integers
x = 3.14 # Floats
y = 2.0 # Floats
x = 1e-10 # Floats
# Strings
name = “John”
y = “Hello, world!”
“””multi-line string”””
# Variables
x
y
result
# Booleans
is_raining = True
is_sunny = False
# Sets
my_set = {9, 10, 11, 12}
# Dictionaries (A data structure)
my_dict = {“key1”: “value1”, “key2”: “value2”, “Age”: 30}
# None
nothing = None
# Range object
range(5)
# Lambda function
lambda x: x + 1
# Functions
print() # Input and Output Functions
input()
# Methods
‘hello’.upper()
[1, 2, 3].upper(4)
Functions: Named blocks of code that perform a specific task. They are defined
using the ‘def’ keyword followed by the function name and any parameters e.g.
(a, b) that the function takes.
# Numeric Functions
# Built-in Functions
abs()
round()
max()
min()
pow()
divmod()
sum()
bin()
oct()
hex()
#Lambda Functions
lambda x: x**2
lambda x: x, y: x + y
lambda x: x.strip()
# String Functions
# Built-in Functions
len()
str()
format()
ord()
chr()
capitalize()
casefold()
center()
count()
endswith()
find()
index()
isalnum()
isalpha()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric()
isprintable()
isspace()
istitle()
isupper()
join()
ljust()
lower()
lstrip()
replace()
rfind()
rindex()
rjust()
rstrip()
split()
splitlines()
startswith()
strip()
swapcase()
title()
upper()
zfill()
#Lambda Functions
lambda x: x.upper()
lambda x: x.lower()
lambda x: x.strip()
# List Functions
list()
len()
max()
min()
sum()
sorted()
reversed()
enumerate()
zip()
all()
any()
filter()
map()
# Lambda Functions
lambda x: len(x)
lambda x: sorted(x)
lambda x: reversed(x)
lambda x: [i for i in x if i % 2 == 0]
lambda x: [i**2 for i in x]
# Dictionary Functions
# Built-in Functions
dict()
len()
keys()
values()
items()
clear()
copy()
fromkeys()
get()
pop()
popitem()
setdefault()
update()
# Lambda Functions
lambda x: len(x)
lambda x: sorted(x.keys())
lambda x: sorted(x.values())
lambda x: {k: v for k, v in x.items() if v > 0)
# Iteration Functions
# Built-in Functions
range()
iter()
next()
reversed()
# Lambda Functions
lambda x: x**2
lambda x: x.upper()
# Loops Functions
# Built-in Functions
for item in iterable
pass
while condition:
pass
range()
enumerate()
# Lambda Functions
lambda x: [i for i in x if i % 2 == 0]
lambda x: [i**2 for i in x]
lambda x: [(i, i**2 for i in x]
# Miscellaneous Functions
# Built-in Functions
print()
input()
globals()
locals()
zip()
sorted()
reversed()
hash()
sum()
sum()
len()
# Concurrency Functions
# Built-in Functions
threading.Thread()
threading.Lock()
threading.RLock()
threading.Condition()
threading.Event()
threading.Semaphore()
threading.Barrier()
queue.Queue()
queue.LifoQueue()
queue.PriorityQueue()
asyncio.run(my_coroutine())
def my_function():
print(“Function started”)
for i in range(5):
print(f”Function: {i}”)
print(“Function ended”)
my_thread = threading.Thread(target=my_function)
my_thread.start()
import multiprocessing # ‘multiprocessing.Process()’: This
function creates a new process to run a function.
def my_function():
print(“Function started”)
for i in range(5):
print(f”Function: {i}”)
print(“Function ended”)
my_process = multiprocessing.Process(target=my_function)
my_process.start()
import concurrent.futures #
‘concurrent.futures.ProcessPollExecutor()’: This function
creates a pool of processes to execute functions.
def my_function():
print(“Function started”)
for i in range(5):
print(f”Function: {i}”)
print(“Function ended”)
return x * 2
def thread_function(name):
print(“Thread”, name)
x = threading.Thread(target=thread_function, args=(“Thread-
1”,))
x.start()
# Lambda Functions
import concurrent.futures
# Decorator Functions
# Built-in Functions
staticmethod()
classmethod()
property()
@staticmethod
@classmethod
@property
@abstractmethod
app = Flask(__name__)
@app.route(‘/’)
def hello():
return ‘Hello, World!’
@csrf_exempt
def my_view(request):
return HttpResponse(‘Hello, World!’)
import wrap
@wrap.decorator
def my_decorator(wrapped, instance, args, kwargs):
# code to execute before the function call
result = wrapped(*args, **kwargs)
# code to execute after the function call
return result
@logger.catch
def my_function():
# code to execute
pass
@cached(ttl=60)
def my_function():
# code to execute
pass
@sleep_and_retry
@limits(calls=10, period=60)
def my_function():
# code to execute
pass
# Lambda Functions
def log_function_calls(func): # A decorator function that logs
the function call
def wrapper(*args, **kwargs)
print(f”Calling function {func.__name__}”)
return func(*args, **kwargs)
return wrapper
# Output
Calling function <lambda>
6
# Networking Functions
# Built-in Functions
socket.socket()
socket.create_connection()
socket.AF_INET()
socket.SOCK_STREAM()
socket.gethostmame()
socket.gethostbyname()
socket.gethostbyaddr()
socket.ntohs()
socket.ntohl()
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #
Creating a socket
import paramiko
import pycurl
- requests.get()
- requests.post()
- requests.put()
- requests.delete()
- urllib.request.urlopen()
- httplib2.Http()
- http.client.HTTPConnection()
- http.client.HTTPSConnection()
- ftplib.FTP()
- paramiko.SSHClient()
import requests
import aiohttp
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((‘www.google.com’, 80))
s.sendall(b’GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n’)
response = s.recv(4096)
s.close()
import paramiko
# Lambda Functions
import asyncio
loop = asyncio.get_event_loop()
async_lambda_call = lambda:
loop.run_until_complete(async_lambda())
async_lambda_call()
import socket
while True:
client, addr = tcp_server.accept()
client_handler(client)
re.match()
re.search()
re.findall()
re.finditer()
re.sub()
re.split()
import re
# Lambda Functions
import re
import datetime
# arrow
import arrow
utc = arrow.utcnow()
local = utc.to(‘US/Pacific’)
print(f”UTC: {utc}\nLocal: {Local}”)
# pendulum
import pendulum
now = pendulum.now(‘Europe/Paris’)
tomorrow = now.add(days=1)
print(f”Tomorrow: {tomorrow}\nTimezone:
{tomorrow.timezone_name}”)
# pytz
from datetime import datetime
import pytz
utc = pytz.utc
eastern = pytz.timezone('US/Eastern')
# Lambda Functions
# Get current date
import datetime
date1 = datetime.date(2022, 1, 1)
date2 = datetime.date(2022, 2, 3)
date_str = ‘2022-02-03’
# Math Functions
# Built-in Functions
math.ceil()
math.floor()
math.fabs()
math.factorial()
math.isclose()
math.isfinite()
math.isnan()
math.modf()
math.trunc()
math.gcd()
import math
# Basic operations
print(math.sqrt(16)) # square root: 4.0
print(math.pow(2, 3)) # power: 8.0
print(math.exp(1)) # exponential: 2.718281828459045
# Trigonometric functions
print(math.sin(math.pi / 2)) # sine 1.0
print(math.cos(math.pi / 2)) # cosine 6.123233995736766e-17
print(math.tan(math.pi / 4)) # tangent 0.9999999999999999
print(math.radians(90)) # degrees to radians:
1.5707963267948966
# Logarithmic functions
print(math.log(10)) # natural logarithm: 2.302585092994046
print(math.log(100)) # base 10 logarithm: 2.0
# Constants
print(math.pi) # pi: 3.14592653589793
print(math.e) # Euler’s number: 2.718281828459045
# Rounding functions
# Round a floating-point number to the nearest integer
print(round(3.14)) # 3
# Factorial Functions
import math
my_list = [1, 2, 3, 4, 5]
mean = np.mean(my_list)
print(mean)
# Lambda Functions
# 1. Squaring a number using a lambda function
square = lambda x: x**2
print(square(5)) # Output: 25
# Statistics Function
# Built-in Functions
numbers = [1, 2, 2, 3, 4, 4, 4, 5] # calculate mean, median,
mode of a list of numbers
mean = statistics.mean(numbers)
median = statistics.median(numbers)
mode = statistics.mode(numbers)
import statistics
# Mean
data = [1, 2, 3, 4, 5]
mean = statistics.mean(data)
print(“Mean:”, mean)
# Median
data = [1, 2, 3, 4, 5]
mean = statistics.median(data)
print(“Median:”, median)
# Mode
data = [1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
mode = statistics.mode(data)
print(“Mode:”, mode)
# Variance
data = [1, 2, 3, 4, 5]
variance = statistics.variance(data)
print(“Variance:”, variance)
# Standard deviation
data = [1, 2, 3, 4, 5]
stdev = statistics.stdev(data)
print(“Standard deviation:”, stdev)
# Output
Mean: 3
Median: 3
Mode: 5
Variance: 2.5
Standard deviation: 1.581138800841898
statistics.mean()
statistics.median()
statistics.stdev()
statistics.variance()
statistics.mode()
numpy.mean()
numpy.median()
numpy.std()
numpy.var()
numpy.corrcoef()
numpy.cov()
scipy.stats.mode()
scipy.stats.skew()
scipy.stats.kurtosis()
scipy.stats.ttest_1samp()
scipy.stats.ttest_ind()
scipy.stats.ttest_rel()
scipy.stats.chisquare()
scipy.stats.normaltest()
scipy.stats.shapiro()
data = [1, 2, 3, 4, 5]
mean = np.mean(data)
std_dev = np.std(data)
variance = np.var(data)
correlation = np.corrcoef(data)
hisogram = np.histogram(data)
data1 = [1, 2, 3, 4, 5]
data2 = [6, 7, 8, 9, 10]
t_stat, p_value = ttest_ind(data1, data2)
slope, intercept, r_value, p_value, std_err =
linregress(data1, data2)
normal_pdf = norm.pdf(data1)
import statistics
# Mean
mean = lambda data: statistics.mean(data)
# Median
median = lambda data: statistics.median(data)
# Mode
mode = lambda data: statistics.mode(data)
# Variance
variance = lambda data: statistics.variance(data)
# Standard deviation
stdev = lambda data: statistics.stdev(data)
# Correlation
correlation = lambda x, y: statistics.correlation(x, y)
# Hashing functions:
haslib.sha256(b’my_password’).hexdigest() # returns the SHA-
256 of the password as a hexadecimal string
haslib.md5(b’my_data).hexdigest() # returns the MD5 hash of
the data as a hexadecimal string
# Encryption/decryption:
import base64
from cryptography.fernet import Fernet
# Digital signatures:
import hashlib
from cryptography.hazmat.primitives.asymmetric import rsa,
padding
from cryptography.hazmat.primitives import serialization
import secrets
# Cryptographically secure random number generation functions
secrets.token_bytes(16) # returns a 16-byte (128-bit) random
number as bytes
secrets.token_hex(16) # returns a 32-character hexidecimal
string representing a 16-byte (128-bit) random number
secrets.token_urlsafe(16) # returns a URL-safe string
representing a 16-byte (128-bit) random number
import hmac
hmac.new(b’secret_key’, b’my_message’
,hashlib.sha256).hexdigest() # returns the HMAC of the message
using SHA-256 as the hash function
hashlib.md5()
hashlib.sha1()
haslib.sha224()
hashlib.sha256()
hashlib.sha384()
hashlib.sha512()
hmac.new()
cryptography.hazmat.primitives.asymmetric.rsa.generate_private
_key()
cryptography.hazmat.primitives.asymmetric.rsa.RSASignatureAlgo
rtithm()
cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey()
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey()
cryptography.hazmat.primitives.ciphers.modes.ECB()
cryptography.hazmat.primitives.ciphers.modes.CBC()
cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC()
cryptography.hazmat.primitives.serialization.load_der_private_
key()
cryptography.hazmat.primitives.serialization.load_der_public_k
ey()
cryptography.hazmat.primitives.serialization.load_pem_private_
key()
cryptography.hazmat.primitives.serialization.load_pem_public_k
ey()
# 1. PyCrypto:
from Crypto.Cipher import AES
# Encrypt plaintext
ciphertext = cipher.encrypt(plaintext)
# Decrypt ciphertext
decrypted_text = cipher.decrypt(ciphertext)
# 2. PyCryptodome:
from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes
# Encrypt plaintext
ciphertext = cipher.encrypt(plaintext)
# Decrypt ciphertext
decrypted_text = cipher.decrypt(ciphertext)
# Lambda Functions
print(generate_key())
image = Image.open(‘image.jpg’)
image.show()
# 2. Cropping an image
from PIL import Image
image = Image.open(‘image.jpg’)
image.crop((100, 100, 200, 200))
cropped_image.show()
# 3. Resizing an image
from PIL import Image
image = Image.open(‘image.jpg’)
image.crop((500, 500))
resized_image.show()
image = Image.open(‘image.jpg’)
grayscale_image = image.convert(‘L’)
grayscale_image.show()
# 5. Rotating an image
from PIL import Image
image = Image.open(‘image.jpg’)
image.rotate(45)
rotated_image.show()
# 1. Pillow
from PIL import Image
# OpenCV
import cv2
# Load image
image = cv2.imread('image.jpg')
# 3. scikit-image
from skimage import io, color
# Load image
image = io.imread(‘image.jpg’)
# 4. Mahotas
import mahotas
import numpy as np
# Load image
image = mahotas.imread('image.jpg')
# Load image
gray_image = np.mean(image, axis=2)
# 5. OpenCV
import cv2
# Load image
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Lambda Functions
# Pillow Library:
# 1. Applying a filter to an image using a lambda function
from PIL import Image, ImageFilter
image = Image.open('image.jpg')
image = Image.open('image.jpg')
image = Image.open('image.jpg')
# NumPy Library:
# Import NumPy library
import numpy as np
# Group the data by the 'category' column and compute the mean
of the 'value' column for each group
grouped = df.groupby('category')['value'].mean()
# Matplotlib Library:
# Import Matplotlib library
import matplotlib.pyplot as plt
# OpenCV Library:
# Import OpenCV library
import cv2
# Resizing an image
import cv2
image = cv2.imread(‘image.jpg’)
resized_image = resize(image, 500, 500)
image = cv2.imread('image.jpg')
draw_rectangle(image, (50, 50), (100, 100), (255, 0, 0), 2)
# scikit-image Library:
import numpy as np
from skimage import io, filters, transform
requests.get()
requests.post()
requests.put()
requests.delete()
BeautifulSoup()
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu',
input_shape=(32,)),
tf.keras.layers.Dense(10, activation='softmax')
])
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 50, 5)
self.fc1 = nn.Linear(4*4*50, 500)
self.fc2 = nn.Linear(500, 10)
svm.SVC()
LinearRegression()
import tensorflowsdrsx
import scikit-learn
tensorflow.keras.models.Sequential()
tensorflow.keras.layers.Dense()
tensorflow.keras.layers.Conv2D()
tensorflow.keras.layers.MaxPooling2D()
tensorflow.keras.layers.Flatten()
scikit-learn.model_selection.train_test_split()
scikit-learn.preprocessing.StandardScaler()
scikit-learn.cluster.KMeans()
# Lambda Functions
linreg = lambda X, y: np.linalg.inv(X.T @ X) @ X.T @ y #lambda
function for linear regression
r_squared = lambda y_true, y_pred: 1 – (np.sum((y_true –
y_pred)**2)/np.sum((y_true – np.mean(y_true))**2)) # lambda
function for calculating R^2 value
sigmoid = lambda z: 1 / (1 + np.exp(-z)) # lambda function for
sigmoid function
softmax = lambda z: np.exp(z) / np.sum(np.exp(z), axis=1,
keepdims=True) # lambda function for softmax function
nltk.word_tokenize()
nltk.sent_tokenize()
nltk.pos_tag()
nltk.ne_chunk()
nltk.download()
spacy.load()
spacy.Doc()
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer, WordNetLemmatizer
# Lambda Functions
remove_punctuation = lambda text: ‘’.join(char for char in
text if not char.isalnum())
remove_numbers = lambda text: ‘’.join(char for char in text if
not char.isdigit())
remove_whitespace = lambda text: ‘’.join(text.split())
import matplotlib
import seaborn
import plotly
matplotlib.pyplot.plot()
matplotlib.pyplot.scatter()
matplotlib.pyplot.hist()
seaborn.lineplot()
seaborn.scatterplot()
seaborn.distplot()
plotly.express.scatter()
plotly.express.line()
plotly.express.bar()
Variables: Names that refer to values or objects in Python. You can assign a value
to a variable using the ‘=’ operator.
x = 2
y = 3
Data Types: Integers, Floating-point numbers, strings, and Booleans. You can use
operators and functions to manipulate and combine these data types as needed.