Python is one of the most popular and versatile programming languages in the world today. It is an interpreted, high-level, general-purpose language that emphasizes code readability.
Whether you are interested in web development, data science, or simple automation, here is a comprehensive breakdown of everything Python.
Python’s design philosophy is centered around the phrase: "There should be one—and preferably only one—obvious way to do it."
Easy to Read: Python uses English keywords and clean indentation rather than curly braces or semicolons, making it look almost like "executable pseudocode."
Interpreted: You don't need to compile your code into machine language before running it. An interpreter executes the code line-by-line, which makes debugging faster.
Dynamically Typed: You don't have to declare the type of a variable (like int or string) when you create one. Python figures it out at runtime.
Multi-paradigm: It supports procedural, object-oriented (OOP), and functional programming styles.
One of Python's greatest strengths is its massive collection of libraries and frameworks.
Field Popular Libraries / Frameworks
Web Development Django, Flask, FastAPI
Data Science Pandas, NumPy, Matplotlib
Machine Learning TensorFlow, PyTorch, Scikit-learn
Automation/Scripting Selenium, Beautiful Soup, PyAutoGUI
Game Development Pygame
When you run a Python script, it goes through a specific lifecycle to turn your text into action.
Source Code: You write code in a .py file.
Bytecode: The Python interpreter compiles your code into an intermediate format called Bytecode (stored in .pyc files).
Python Virtual Machine (PVM): The PVM reads the bytecode and executes it on your specific operating system.
import os
import tempfile
def multiplication_routine():
try:
# 1. Accept 2 numeric inputs
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# 2. Store and multiply
result = num1 * num2
output_text = f"Result of {num1} x {num2} = {result}"
# 3. Output to display screen
print("\n--- Display Output ---")
print(output_text)
# 4. Output to Printer
print("\nSending to printer...")
send_to_printer(output_text)
except ValueError:
print("Error: Please enter valid numeric values.")
def send_to_printer(text):
# Create a temporary file to hold the print data
temp_file = tempfile.mktemp(".txt")
with open(temp_file, "w") as f:
f.write(text)
# Windows command to print (using the default printer)
# Note: For Linux/macOS, use 'lpr' instead of 'start /min notepad /p'
try:
os.system(f'start /min notepad /p {temp_file}')
print("Print job sent successfully.")
except Exception as e:
print(f"Failed to print: {e}")
if __name__ == "__main__":
multiplication_routine()
Python Coding Syntax
python --version ---> version
python ---> python command line
exit() ---> exit
# this is a comment
"""This is a
multiline docstring."""
if 5 > 2:
print("Five is greater than two!")
x = 5 # x is of type int
y = "John" # y is of type str
print(x)
print(y)
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
x = 5
y = 10
print(x + y)
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
a = "Hello, World!"
print(a[1])
b = "Hello, World!"
print(b[2:5])
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
a = "Hello, World!"
print(len(a))
print(a.lower())
print(a.upper())
print(a.replace("H", "J"))
print(a.split(",")) # returns ['Hello', ' World!']
print("Enter your name:")
x = input()
print("Hello, " + x)
Arithmetic
+, -, *, /, %, **, //
Assignment
=, +=, -=, *=, /=, %=, //=, **=
&=, |=, ^=, >>=, <<=
Comparison
==, !=, >, <, >=, <=,
Logical
and, or, not
Identity
is, is not
Membership
in, not in
Bitwise
&, |, ^, ~, <<, >>
Order is changeable and duplicated allowed
thislist = ["apple", "banana", "cherry"]
print(thislist)
print(len(thislist))
print(thislist[1])
for x in thislist:
print(x)
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
thislist.append("orange")
thislist.insert(1, "orange")
thislist.remove("banana")
thislist.pop() ---> removes item specified of last item
del thislist[0]
del thislist ---> delete the list
thislist.clear() ---> empties the list
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
append()
clear()
copy()
count()
extend()
index()
insert()
pop()
remove()
reverse()
sort()
Order is unchangeable and duplicates allowed
thistuple = ("apple", "banana", "cherry")
print(thistuple)
print(thistuple[1])
thistuple[1] = "blackcurrant"
# The values will remain the same:
print(thistuple)
for x in thistuple:
print(x)
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
print(len(thistuple))
del thistuple
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
count()
index()
Unordered, Unindexed
thisset = {"apple", "banana", "cherry"}
print(thisset)
for x in thisset:
print(x)
print("banana" in thisset)
thisset.add("orange")
thisset.update(["orange", "mango", "grapes"])
print(len(thisset))
thisset.remove("banana")
thisset.discard("banana")
x = thisset.pop()
thisset.clear()
del thisset
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
add()
clear()
copy()
difference()
difference_update()
discard()
intersection()
intersection_update()
isdisjoint()
issubset()
issuperset()
pop()
remove()
symmetric_difference()
symmetric_difference_update()
union()
update()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
x = thisdict.get("model")
thisdict["year"] = 2018
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])
for x in thisdict.values():
print(x)
for x, y in thisdict.items():
print(x, y)
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
print(len(thisdict))
thisdict["color"] = "red"
print(thisdict)
thisdict.pop("model")
thisdict.popitem()
del thisdict["model"]
del thisdict
thisdict.clear()
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
clear()
copy()
fromkeys()
get()
items()
keys()
pop()
popitem()
setdefault()
update()
values()
Logical Conditions
a == b
a != b
a < b
a <= b
a > b
a >= b
a = 33
b = 200
if b > a:
print("b is greater than a")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
if a > b: print("a is greater than b")
print("A") if a > b else print("B")
print("A") if a > b else print("=") if a == b else print("B")
if a > b and c > a:
print("Both conditions are True")
if a > b or a > c:
print("At least one of the conditions is True")
i = 1
while i < 6:
print(i)
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Iterates over a sequence (list, tuple, dictionary, set or string)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
Break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
for x in range(6):
print(x)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3): ---> increment sequence with 3
print(x)
for x in range(6):
print(x)
else:
print("Finally finished!")
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Block of code
def my_function():
print("Hello from a function")
my_function()
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Small anonymous function
Can only have one expression
x = lambda a : a + 10
print(x(5))
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
def myfunc(n):
return lambda a : a * n
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
List is used
cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
cars[0] = "Toyota"
x = len(cars)
for x in cars:
print(x)
cars.append("Honda")
cars.pop(1)
cars.remove("Volvo")
append()
clear()
copy()
count()
extend()
index()
insert()
pop()
remove()
reverse()
sort()
Class is like object constructor
class MyClass: ---> create class
x = 5
p1 = MyClass() ---> create object
print(p1.x)
__init__() function ---> executed when class is initiated
-----------------------------------------
---> self param is a reference to class itself
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
-----------------------------------------
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self): ---> object methods
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
-----------------------------------------
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
p1.age = 40
print(p1.age)
-----------------------------------------
del p1.age
del p1
Object that contains countable number of values
Methods: __iter__() ___next__()
iter method to get iterator
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
mystr = "banana"
for x in mystr:
print(x)
-----------------------------------------
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
-----------------------------------------
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
-----------------------------------------
Code library
-----------------------------------------
---> file mymodule.py - create module
def greeting(name):
print("Hello, " + name)
---> use a module
import mymodule
mymodule.greeting("Jonathan")
-----------------------------------------
---> mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
---> use a module
import mymodule as mx
a = mx.person1["age"]
print(a)
-----------------------------------------
import platform
x = platform.system()
print(x)
x = dir(platform)
print(x)
-----------------------------------------
---> mymodule.py
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
---> use a module
from mymodule import person1
print (person1["age"])
-----------------------------------------
Date in not python data type
import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
x = datetime.datetime(2020, 5, 17)
print(x)
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Strftime format code
%a ---> short weekday
%A ---> weekday
%w ---> weekday as a number
%d ---> day of the month
%b ---> short month
%B ---> Month
%m ---> month as a number
%y ---> short year
%Y ---> year
%H ---> hour - 24 hour format
%I ---> hour - 12 hour format
%p ---> AM/PM
%M ---> minutes
%S ---> Seconds
%f ---> microsecond
%z ---> UTC offset
%Z ---> Timezone
%j ---> Day number of year
%U ---> Week number of year - Sunday first
%W ---> Week number of year - Monday first
%c ---> local version of date and time
%x ---> local version of date
%X ---> local version of time
%% ---> A % character
Built in package called json
----------------------------------------- json to python
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
----------------------------------------- python to json
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
-----------------------------------------
Python to json
Dict, list, tuple, string, int, float, True, False, None
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
-----------------------------------------
import json
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
-----------------------------------------
json.dumps(x, indent=4) ---> format the result
---> change default separator
json.dumps(x, indent=4, separators=(". ", " = "))
----> order the result
json.dumps(x, indent=4, sort_keys=True)
Built in package re
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
RegEx functions
findall ---> list containing matches
search ---> match object
split ---> list where string was split at match
sub ---> replaces one or many matches
str = "The rain in Spain"
x = re.findall("ai", str)
print(x)
str = "The rain in Spain"
x = re.search("\s", str)
print("The first white-space character is located in position:", x.start())
str = "The rain in Spain"
x = re.search("Portugal", str)
print(x)
str = "The rain in Spain"
x = re.split("\s", str)
print(x)
str = "The rain in Spain"
x = re.split("\s", str, 1)
print(x)
str = "The rain in Spain"
x = re.sub("\s", "9", str)
print(x)
PIP
Package manager - https://pypi.org/
pip install camelcase
import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
Lets you test block of codes for errors
try:
print(x)
except:
print("An exception occurred")
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
4 diff methods: r, a, w, x
Mode: t, b
f = open("demofile.txt")
f = open("demofile.txt", "rt")
f = open("demofile.txt", "r")
print(f.read())
print(f.read(5))
print(f.readline())
f = open("demofile.txt", "r")
for x in f:
print(x)
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
f = open("myfile.txt", "x")
f = open("myfile.txt", "w")
import os
os.remove("demofile.txt")
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
os.rmdir("myfolder")
https://www.mysql.com/downloads/
python -m pip install mysql-connector ---> MySQL driver
import mysql.connector
# Create connection
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
# list databases
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
# create DB
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
# connecting to database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
# create a table
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# check if table exists
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
# primary key
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
# alter table
mycursor = mydb.cursor()
mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
# insert
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
# insert many
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
# row ID
print("1 record inserted, ID:", mycursor.lastrowid)
# select
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
mycursor.execute("SELECT * FROM customers LIMIT 5")
mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# fetch one record
myresult = mycursor.fetchone()
# select with wildcard
sql = "SELECT * FROM customers WHERE address LIKE '%way%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# prevent SQL onjection - escape query values
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# delete record
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
# avoid SQL injection
sql = "DELETE FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
#drop table
sql = "DROP TABLE customers"
sql = "DROP TABLE IF EXISTS customers"
mycursor.execute(sql)
# update records
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = %s WHERE address = %s"
val = ("Valley 345", "Canyon 123")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
# inner join
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# left join
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id"
# right join
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
RIGHT JOIN products ON users.fav = products.id"
NumPy
Numeric processing - Large Array
Linear Algebra
(Matlab) - Matrix Computation, Linear Algenbra, Machine Learning
SciPy