✨ tensor parameter | AI Coding Glossary ✨
📖 A learned multi-dimensional array that a model updates during training to shape its computations.
🏷️ #Python
📖 A learned multi-dimensional array that a model updates during training to shape its computations.
🏷️ #Python
#PyQt5 #SQLite #DesktopApp #WarehouseManagement #ERP #Python
Lesson: Advanced Warehouse ERP with PyQt5, SQLite, and Reporting
This tutorial covers building a complete desktop Enterprise Resource Planning (ERP) application for warehouse management. It features persistent storage using SQLite, inventory control, sales and purchase invoice management, a production module, and the ability to export reports to CSV.
---
First, we create a dedicated file to handle all database interactions. This separation of concerns is crucial for a scalable application. Create a file named
---
Now, create the main application file,
Lesson: Advanced Warehouse ERP with PyQt5, SQLite, and Reporting
This tutorial covers building a complete desktop Enterprise Resource Planning (ERP) application for warehouse management. It features persistent storage using SQLite, inventory control, sales and purchase invoice management, a production module, and the ability to export reports to CSV.
---
#Step 1: Database Setup (database.py)First, we create a dedicated file to handle all database interactions. This separation of concerns is crucial for a scalable application. Create a file named
database.py.import sqlite3
import csv
DB_NAME = 'warehouse.db'
def connect():
return sqlite3.connect(DB_NAME)
def setup_database():
conn = connect()
cursor = conn.cursor()
# Inventory Table: Stores raw materials and finished goods
cursor.execute('''
CREATE TABLE IF NOT EXISTS inventory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
quantity INTEGER NOT NULL,
price REAL NOT NULL
)
''')
# Invoices Table: Tracks both sales and purchases
cursor.execute('''
CREATE TABLE IF NOT EXISTS invoices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL, -- 'SALE' or 'PURCHASE'
party_name TEXT, -- Customer or Supplier Name
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Invoice Items Table: Links items from inventory to an invoice
cursor.execute('''
CREATE TABLE IF NOT EXISTS invoice_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
invoice_id INTEGER,
item_id INTEGER,
quantity INTEGER NOT NULL,
price_per_unit REAL NOT NULL,
FOREIGN KEY (invoice_id) REFERENCES invoices (id),
FOREIGN KEY (item_id) REFERENCES inventory (id)
)
''')
conn.commit()
conn.close()
def get_inventory():
conn = connect()
cursor = conn.cursor()
cursor.execute("SELECT id, name, quantity, price FROM inventory ORDER BY name")
items = cursor.fetchall()
conn.close()
return items
def add_inventory_item(name, quantity, price):
conn = connect()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO inventory (name, quantity, price) VALUES (?, ?, ?)", (name, quantity, price))
conn.commit()
except sqlite3.IntegrityError:
# Item with this name already exists
return False
finally:
conn.close()
return True
def update_item_quantity(item_id, change_in_quantity):
conn = connect()
cursor = conn.cursor()
cursor.execute("UPDATE inventory SET quantity = quantity + ? WHERE id = ?", (change_in_quantity, item_id))
conn.commit()
conn.close()
def find_item_by_name(name):
conn = connect()
cursor = conn.cursor()
cursor.execute("SELECT * FROM inventory WHERE name = ?", (name,))
item = cursor.fetchone()
conn.close()
return item
# Add more functions here for invoices, etc. as we build the app.
# Hashtags: #SQLite #DatabaseDesign #DataPersistence #Python
---
#Step 2: Main Application Shell and Inventory TabNow, create the main application file,
main.py. We'll build the window, tabs, and fully implement the Inventory tab, which will read from and write to our SQLite database.❤1
import sys
import csv
from PyQt5.QtWidgets import *
import database as db # Import our database module
class WarehouseApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Warehouse ERP System")
self.setGeometry(100, 100, 1000, 700)
db.setup_database() # Ensure tables are created
self.tabs = QTabWidget()
self.setCentralWidget(self.tabs)
# Create tabs
self.inventory_tab = QWidget()
self.purchase_tab = QWidget() # Incoming
self.sales_tab = QWidget() # Outgoing
self.production_tab = QWidget()
self.reports_tab = QWidget()
self.tabs.addTab(self.inventory_tab, "Inventory")
# Add other tabs later...
self.setup_inventory_ui()
self.load_inventory_data()
def setup_inventory_ui(self):
layout = QVBoxLayout()
# Table view
self.inventory_table = QTableWidget()
self.inventory_table.setColumnCount(4)
self.inventory_table.setHorizontalHeaderLabels(['ID', 'Name', 'Quantity', 'Price'])
self.inventory_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
layout.addWidget(self.inventory_table)
# Form for adding new items
form = QFormLayout()
self.item_name = QLineEdit()
self.item_qty = QSpinBox()
self.item_qty.setRange(0, 99999)
self.item_price = QLineEdit()
form.addRow("Name:", self.item_name)
form.addRow("Quantity:", self.item_qty)
form.addRow("Price:", self.item_price)
add_btn = QPushButton("Add New Item")
add_btn.clicked.connect(self.add_item)
layout.addLayout(form)
layout.addWidget(add_btn)
self.inventory_tab.setLayout(layout)
def load_inventory_data(self):
items = db.get_inventory()
self.inventory_table.setRowCount(len(items))
for row_num, row_data in enumerate(items):
for col_num, data in enumerate(row_data):
self.inventory_table.setItem(row_num, col_num, QTableWidgetItem(str(data)))
def add_item(self):
name = self.item_name.text()
qty = self.item_qty.value()
price = float(self.item_price.text())
if not name:
QMessageBox.warning(self, "Input Error", "Item name cannot be empty.")
return
if db.add_inventory_item(name, qty, price):
self.load_inventory_data() # Refresh table
self.item_name.clear()
self.item_qty.setValue(0)
self.item_price.clear()
else:
QMessageBox.warning(self, "DB Error", f"Item '{name}' already exists.")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = WarehouseApp()
window.show()
sys.exit(app.exec_())
# Hashtags: #PyQt5 #GUI #CRUD #InventoryManagement
---
#Step 3: Purchase (Incoming) and Sales (Outgoing) TabsWe'll manage invoices. A purchase increases stock, and a sale decreases it. We need to add functions to
database.py first, then build the UI.Add to
database.py:❤1
def create_invoice(invoice_type, party_name, items):
conn = connect()
cursor = conn.cursor()
# Create the invoice record
cursor.execute("INSERT INTO invoices (type, party_name) VALUES (?, ?)", (invoice_type, party_name))
invoice_id = cursor.lastrowid
# Add items to the invoice and update inventory
for item in items:
item_id, quantity, price = item['id'], item['quantity'], item['price']
cursor.execute(
"INSERT INTO invoice_items (invoice_id, item_id, quantity, price_per_unit) VALUES (?, ?, ?, ?)",
(invoice_id, item_id, quantity, price)
)
# Update inventory quantity
change = quantity if invoice_type == 'PURCHASE' else -quantity
cursor.execute("UPDATE inventory SET quantity = quantity + ? WHERE id = ?", (change, item_id))
conn.commit()
conn.close()
return invoice_id
Add to
main.py's WarehouseApp class:# In __init__, add the tab and call the setup
self.tabs.addTab(self.purchase_tab, "Purchasing (Incoming)")
self.setup_purchase_ui()
# In __init__, add the sales tab and call setup
self.tabs.addTab(self.sales_tab, "Sales (Outgoing)")
self.setup_sales_ui()
# New methods for the class
def setup_purchase_ui(self):
# This is a simplified UI for demonstration
layout = QVBoxLayout()
form = QFormLayout()
self.supplier_name = QLineEdit()
self.purchase_item = QComboBox()
self.purchase_qty = QSpinBox()
self.purchase_qty.setRange(1, 1000)
form.addRow("Supplier Name:", self.supplier_name)
form.addRow("Item:", self.purchase_item)
form.addRow("Quantity:", self.purchase_qty)
add_purchase_btn = QPushButton("Record Purchase")
add_purchase_btn.clicked.connect(self.record_purchase)
layout.addLayout(form)
layout.addWidget(add_purchase_btn)
self.purchase_tab.setLayout(layout)
self.update_item_combos()
def setup_sales_ui(self):
# UI is very similar to purchase
layout = QVBoxLayout()
form = QFormLayout()
self.customer_name = QLineEdit()
self.sales_item = QComboBox()
self.sales_qty = QSpinBox()
self.sales_qty.setRange(1, 1000)
form.addRow("Customer Name:", self.customer_name)
form.addRow("Item:", self.sales_item)
form.addRow("Quantity:", self.sales_qty)
add_sale_btn = QPushButton("Record Sale")
add_sale_btn.clicked.connect(self.record_sale)
layout.addLayout(form)
layout.addWidget(add_sale_btn)
self.sales_tab.setLayout(layout)
def update_item_combos(self):
self.purchase_item.clear()
self.sales_item.clear()
items = db.get_inventory()
for item in items:
# Store the full item tuple as userData
self.purchase_item.addItem(item[1], userData=item)
self.sales_item.addItem(item[1], userData=item)
def record_purchase(self):
supplier = self.supplier_name.text()
item_data = self.purchase_item.currentData()
qty = self.purchase_qty.value()
if not supplier or not item_data:
QMessageBox.warning(self, "Input Error", "Please fill all fields.")
return
invoice_item = {'id': item_data[0], 'quantity': qty, 'price': item_data[3]}
db.create_invoice('PURCHASE', supplier, [invoice_item])
QMessageBox.information(self, "Success", "Purchase recorded successfully.")
self.load_inventory_data() # Refresh all UIs
self.update_item_combos()
def record_sale(self):
customer = self.customer_name.text()
item_data = self.sales_item.currentData()
qty_to_sell = self.sales_qty.value()
if not customer or not item_data:
QMessageBox.warning(self, "Input Error", "Please fill all fields.")
return
# Check for sufficient stock
if item_data[2] < qty_to_sell:
QMessageBox.critical(self, "Stock Error", f"Not enough {item_data[1]} in stock. Available: {item_data[2]}")
return
invoice_item = {'id': item_data[0], 'quantity': qty_to_sell, 'price': item_data[3]}
db.create_invoice('SALE', customer, [invoice_item])
QMessageBox.information(self, "Success", "Sale recorded successfully.")
self.load_inventory_data()
self.update_item_combos()
Note: This invoice UI is simplified to one item per invoice. A real app would use a table to build a multi-item invoice before saving.
---
#Step 4: Production Tab and ReportingThe production tab will consume raw materials to create a finished product. The reporting tab will export inventory data to a CSV file.
Add to
main.py's WarehouseApp class:# In __init__, add the tabs and call the setups
self.tabs.addTab(self.production_tab, "Production")
self.setup_production_ui()
self.tabs.addTab(self.reports_tab, "Reporting")
self.setup_reports_ui()
# Define Bill of Materials (can be moved to DB in a real app)
self.bill_of_materials = {
'Wooden Table': {'Wood Plank': 5, 'Varnish': 1},
'Wooden Chair': {'Wood Plank': 2, 'Nail': 10}
}
def setup_production_ui(self):
layout = QVBoxLayout()
form = QFormLayout()
self.product_to_make = QComboBox()
self.product_to_make.addItems(self.bill_of_materials.keys())
self.production_qty = QSpinBox()
self.production_qty.setRange(1, 100)
form.addRow("Product:", self.product_to_make)
form.addRow("Quantity:", self.production_qty)
produce_btn = QPushButton("Produce Items")
produce_btn.clicked.connect(self.run_production)
layout.addLayout(form)
layout.addWidget(produce_btn)
self.production_tab.setLayout(layout)
def run_production(self):
product_name = self.product_to_make.currentText()
qty_to_make = self.production_qty.value()
bom = self.bill_of_materials[product_name]
# 1. Check stock for all required materials
for material, required_qty in bom.items():
item_data = db.find_item_by_name(material)
if not item_data or item_data[2] < required_qty * qty_to_make:
QMessageBox.critical(self, "Production Halt", f"Not enough {material} in stock.")
return
# 2. If stock is sufficient, consume materials
for material, required_qty in bom.items():
item_data = db.find_item_by_name(material)
db.update_item_quantity(item_data[0], - (required_qty * qty_to_make))
# 3. Add finished product to inventory
finished_product = db.find_item_by_name(product_name)
if finished_product:
db.update_item_quantity(finished_product[0], qty_to_make)
else:
# You'd calculate a price here in a real app
db.add_inventory_item(product_name, qty_to_make, price=50.0)
QMessageBox.information(self, "Success", f"Produced {qty_to_make} of {product_name}.")
self.load_inventory_data()
self.update_item_combos()
def setup_reports_ui(self):
layout = QVBoxLayout()
label = QLabel("Select a report to export to CSV:")
self.report_type = QComboBox()
self.report_type.addItems(["Current Inventory", "Sales History"]) # Add more as needed
export_btn = QPushButton("Export Report")
export_btn.clicked.connect(self.export_report)
layout.addWidget(label)
layout.addWidget(self.report_type)
layout.addWidget(export_btn)
layout.addStretch()
self.reports_tab.setLayout(layout)
def export_report(self):
report = self.report_type.currentText()
path, _ = QFileDialog.getSaveFileName(self, "Save CSV", "", "CSV Files (*.csv)")
if not path:
return
try:
if report == "Current Inventory":
data = db.get_inventory()
headers = ['ID', 'Name', 'Quantity', 'Price']
with open(path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(data)
# Add other report types here
# elif report == "Sales History": ...
QMessageBox.information(self, "Success", f"Report exported to {path}")
except Exception as e:
QMessageBox.critical(self, "Export Error", f"An error occurred: {e}")
# Hashtags: #Production #Reporting #CSVExport #BusinessLogic
---
#Step 5: Final Results and DiscussionBy combining all the code from the steps above into
Results:
Data Persistence: Your inventory and invoice data is saved in
Integrated Workflow: Adding a purchase directly increases stock. A sale checks for and decreases stock. Production consumes raw materials and creates finished goods, all reflected in the central inventory table.
Separation of Concerns: The UI logic in
Reporting: You can easily export a snapshot of your current inventory to a CSV file for analysis in other programs like Excel or Google Sheets.
Discussion and Next Steps:
Scalability: While SQLite is excellent for small-to-medium applications, a large-scale, multi-user system would benefit from a client-server database like PostgreSQL or MySQL.
Invoice Complexity: The current invoice system is simplified. A real system would allow multiple items per invoice and store historical invoice data for viewing and printing.
User Interface (UI/UX): The UI is functional but could be greatly improved with better layouts, icons, search/filter functionality in tables, and more intuitive workflows.
Error Handling: The error handling is basic. A production-grade app would have more comprehensive checks for user input and database operations.
• Advanced Features: Future additions could include user authentication, supplier and customer management, barcode scanning, and more detailed financial reporting.
This project forms a powerful template for building custom internal business tools with Python.
#ProjectComplete #SoftwareEngineering #ERP #PythonGUI #BusinessApp
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
database.py and main.py, you have a robust, database-driven desktop application.Results:
Data Persistence: Your inventory and invoice data is saved in
warehouse.db and will be there when you restart the application.Integrated Workflow: Adding a purchase directly increases stock. A sale checks for and decreases stock. Production consumes raw materials and creates finished goods, all reflected in the central inventory table.
Separation of Concerns: The UI logic in
main.py is cleanly separated from the data logic in database.py, making the code easier to maintain and extend.Reporting: You can easily export a snapshot of your current inventory to a CSV file for analysis in other programs like Excel or Google Sheets.
Discussion and Next Steps:
Scalability: While SQLite is excellent for small-to-medium applications, a large-scale, multi-user system would benefit from a client-server database like PostgreSQL or MySQL.
Invoice Complexity: The current invoice system is simplified. A real system would allow multiple items per invoice and store historical invoice data for viewing and printing.
User Interface (UI/UX): The UI is functional but could be greatly improved with better layouts, icons, search/filter functionality in tables, and more intuitive workflows.
Error Handling: The error handling is basic. A production-grade app would have more comprehensive checks for user input and database operations.
• Advanced Features: Future additions could include user authentication, supplier and customer management, barcode scanning, and more detailed financial reporting.
This project forms a powerful template for building custom internal business tools with Python.
#ProjectComplete #SoftwareEngineering #ERP #PythonGUI #BusinessApp
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
✨ Build a Python MCP Client to Test Servers From Your Terminal ✨
📖 Follow this Python project to build an MCP client that discovers MCP server capabilities and feeds an AI-powered chat with tool calls.
🏷️ #intermediate #ai #projects
📖 Follow this Python project to build an MCP client that discovers MCP server capabilities and feeds an AI-powered chat with tool calls.
🏷️ #intermediate #ai #projects
❤1
✨ structured output | AI Coding Glossary ✨
📖 Model responses that conform to a specified format, such as a JSON Schema.
🏷️ #Python
📖 Model responses that conform to a specified format, such as a JSON Schema.
🏷️ #Python
✨ jailbreak | AI Coding Glossary ✨
📖 A method of prompting that bypasses model safety constraints to elicit disallowed or unintended behavior.
🏷️ #Python
📖 A method of prompting that bypasses model safety constraints to elicit disallowed or unintended behavior.
🏷️ #Python
Please open Telegram to view this post
VIEW IN TELEGRAM
#Python #Top60 #BuiltInFunctions
#1.
Prints the specified message to the screen.
#2.
Returns the number of items in an object.
#3.
Returns the type of an object.
#4.
Allows user input.
#5.
Converts a value to an integer number.
---
#Python #DataTypes #Conversion
#6.
Converts a value to a string.
#7.
Converts a value to a floating-point number.
#8.
Converts a value to a Boolean (True or False).
#9.
Converts an iterable (like a tuple or string) to a list.
#10.
Converts an iterable to a tuple.
---
#Python #Math #Functions
#11.
Returns the sum of all items in an iterable.
#12.
Returns the largest item in an iterable.
#13.
Returns the smallest item in an iterable.
#14.
Returns the absolute (positive) value of a number.
#15.
Rounds a number to a specified number of decimals.
---
#Python #Iterables #Functions
#16.
Returns a sequence of numbers, starting from 0 by default, and increments by 1.
#17.
Returns a new sorted list from the items in an iterable.
#18.
Returns an enumerate object, which contains pairs of index and value.
#19.
Returns an iterator that aggregates elements from two or more iterables.
#20.
Applies a given function to each item of an iterable and returns a map object.
#1.
print()Prints the specified message to the screen.
print("Hello, World!")Hello, World!
#2.
len()Returns the number of items in an object.
my_list = [1, 2, 3, 4]
print(len(my_list))
4
#3.
type()Returns the type of an object.
name = "Python"
print(type(name))
<class 'str'>
#4.
input()Allows user input.
username = input("Enter your name: ")
print("Hello, " + username)Enter your name: Alex
Hello, Alex
#5.
int()Converts a value to an integer number.
string_number = "101"
number = int(string_number)
print(number + 9)
110
---
#Python #DataTypes #Conversion
#6.
str()Converts a value to a string.
age = 25
print("My age is " + str(age))
My age is 25
#7.
float()Converts a value to a floating-point number.
integer_value = 5
print(float(integer_value))
5.0
#8.
bool()Converts a value to a Boolean (True or False).
print(bool(1))
print(bool(0))
print(bool("Hello"))
print(bool(""))
True
False
True
False
#9.
list()Converts an iterable (like a tuple or string) to a list.
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)
[1, 2, 3]
#10.
tuple()Converts an iterable to a tuple.
my_list = [4, 5, 6]
my_tuple = tuple(my_list)
print(my_tuple)
(4, 5, 6)
---
#Python #Math #Functions
#11.
sum()Returns the sum of all items in an iterable.
numbers = [10, 20, 30]
print(sum(numbers))
60
#12.
max()Returns the largest item in an iterable.
numbers = [5, 29, 12, 99]
print(max(numbers))
99
#13.
min()Returns the smallest item in an iterable.
numbers = [5, 29, 12, 99]
print(min(numbers))
5
#14.
abs()Returns the absolute (positive) value of a number.
negative_number = -15
print(abs(negative_number))
15
#15.
round()Rounds a number to a specified number of decimals.
pi = 3.14159
print(round(pi, 2))
3.14
---
#Python #Iterables #Functions
#16.
range()Returns a sequence of numbers, starting from 0 by default, and increments by 1.
for i in range(5):
print(i)
0
1
2
3
4
#17.
sorted()Returns a new sorted list from the items in an iterable.
unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(sorted_list)
[1, 1, 3, 4, 5, 9]
#18.
enumerate()Returns an enumerate object, which contains pairs of index and value.
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
#19.
zip()Returns an iterator that aggregates elements from two or more iterables.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
#20.
map()Applies a given function to each item of an iterable and returns a map object.
❤1
def square(n):
return n * n
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]
---
#Python #FunctionalProgramming #Keywords
#21.
filter()Constructs an iterator from elements of an iterable for which a function returns true.
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
[2, 4, 6]
#22.
lambdaCreates a small anonymous function.
multiply = lambda a, b: a * b
print(multiply(5, 6))
30
#23.
defKeyword used to define a function.
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
Hello, World!
#24.
returnKeyword used to exit a function and return a value.
def add(a, b):
return a + b
result = add(7, 8)
print(result)
15
#25.
isinstance()Checks if an object is an instance of a specified class.
number = 10
print(isinstance(number, int))
print(isinstance(number, str))
True
False
---
#Python #ControlFlow #Keywords
#26.
if, elif, elseUsed for conditional execution.
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")
Grade B
#27.
forUsed to iterate over a sequence (like a list, tuple, or string).
colors = ["red", "green", "blue"]
for color in colors:
print(color)
red
green
blue
#28.
whileCreates a loop that executes as long as a condition is true.
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
Count is 0
Count is 1
Count is 2
#29.
breakExits the current loop.
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
#30.
continueSkips the rest of the code inside the current loop iteration and proceeds to the next one.
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
---
#Python #StringMethods #TextManipulation
#31.
.upper()Converts a string into upper case.
message = "hello python"
print(message.upper())
HELLO PYTHON
#32.
.lower()Converts a string into lower case.
message = "HELLO PYTHON"
print(message.lower())
hello python
#33.
.strip()Removes any leading and trailing whitespace.
text = " some space "
print(text.strip())
some space
#34.
.split()Splits the string at the specified separator and returns a list.
sentence = "Python is fun"
words = sentence.split(' ')
print(words)
['Python', 'is', 'fun']
#35.
.join()Joins the elements of an iterable to the end of the string.
words = ['Python', 'is', 'awesome']
sentence = " ".join(words)
print(sentence)
Python is awesome
---
#Python #MoreStringMethods #Text
#36.
.replace()Returns a string where a specified value is replaced with another value.
text = "I like cats."
new_text = text.replace("cats", "dogs")
print(new_text)
I like dogs.
#37.
Returns
#38.
Returns
#39.
Searches the string for a specified value and returns the position of where it was found. Returns -1 if not found.
#40.
A way to embed expressions inside string literals.
---
#Python #ListMethods #DataStructures
#41.
Adds an element at the end of the list.
#42.
Removes the element at the specified position.
#43.
Removes the first item with the specified value.
#44.
Adds an element at the specified position.
#45.
Sorts the list in place.
---
#Python #DictionaryMethods #DataStructures
#46.
Creates a dictionary.
#47.
Returns a view object displaying a list of all the keys in the dictionary.
#48.
Returns a view object displaying a list of all the values in the dictionary.
#49.
Returns a view object displaying a list of a given dictionary's key-value tuple pairs.
#50.
Returns the value of the specified key. Provides a default value if the key does not exist.
---
#Python #ErrorHandling #FileIO
#51.
Used to handle errors and exceptions.
.startswith()Returns
True if the string starts with the specified value.filename = "document.pdf"
print(filename.startswith("doc"))
True
#38.
.endswith()Returns
True if the string ends with the specified value.filename = "image.jpg"
print(filename.endswith(".jpg"))
True
#39.
.find()Searches the string for a specified value and returns the position of where it was found. Returns -1 if not found.
text = "hello world"
print(text.find("world"))
6
#40.
f-string (Formatted String Literal)A way to embed expressions inside string literals.
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Alice is 30 years old.
---
#Python #ListMethods #DataStructures
#41.
.append()Adds an element at the end of the list.
fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits)
['apple', 'banana', 'cherry']
#42.
.pop()Removes the element at the specified position.
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1) # Removes 'banana'
print(fruits)
['apple', 'cherry']
#43.
.remove()Removes the first item with the specified value.
fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)
['apple', 'cherry', 'banana']
#44.
.insert()Adds an element at the specified position.
fruits = ['apple', 'cherry']
fruits.insert(1, 'banana')
print(fruits)
['apple', 'banana', 'cherry']
#45.
.sort()Sorts the list in place.
numbers = [3, 1, 5, 2]
numbers.sort()
print(numbers)
[1, 2, 3, 5]
---
#Python #DictionaryMethods #DataStructures
#46.
dict()Creates a dictionary.
my_dict = dict(name="John", age=36)
print(my_dict)
{'name': 'John', 'age': 36}#47.
.keys()Returns a view object displaying a list of all the keys in the dictionary.
person = {'name': 'Alice', 'age': 25}
print(person.keys())dict_keys(['name', 'age'])
#48.
.values()Returns a view object displaying a list of all the values in the dictionary.
person = {'name': 'Alice', 'age': 25}
print(person.values())dict_values(['Alice', 25])
#49.
.items()Returns a view object displaying a list of a given dictionary's key-value tuple pairs.
person = {'name': 'Alice', 'age': 25}
print(person.items())dict_items([('name', 'Alice'), ('age', 25)])#50.
.get()Returns the value of the specified key. Provides a default value if the key does not exist.
person = {'name': 'Alice', 'age': 25}
print(person.get('city', 'Unknown'))Unknown
---
#Python #ErrorHandling #FileIO
#51.
try, exceptUsed to handle errors and exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
result = "You can't divide by zero!"
print(result)
You can't divide by zero!
#52.
open()Opens a file and returns a file object.
# This code creates a file named "myfile.txt"
# No direct output, but a file is created.
file = open("myfile.txt", "w")
file.close()
print("File created and closed.")
File created and closed.
#53.
.write()Writes the specified string to the file.
file = open("myfile.txt", "w")
file.write("Hello, File!")
file.close()
# No direct output, but content is written to myfile.txt
print("Content written to file.")Content written to file.
#54.
.read()Reads the content of the file.
# Assuming "myfile.txt" contains "Hello, File!"
file = open("myfile.txt", "r")
content = file.read()
print(content)
file.close()
Hello, File!
#55.
withA context manager, often used with
open() to automatically handle file closing.with open("myfile.txt", "w") as f:
f.write("This is safer!")
# The file is automatically closed here.
print("File written and closed safely.")File written and closed safely.
---
#Python #Keywords #Advanced
#56.
importUsed to import modules.
import math
print(math.sqrt(16))
4.0
#57.
from ... importImports specific parts of a module.
from datetime import date
today = date.today()
print(today)
2023-10-27
(Note: Output date will be the current date)
#58.
inMembership operator. Checks if a value is present in a sequence.
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
print(10 in my_list)
True
False
#59.
delDeletes an object (variable, list item, dictionary entry, etc.).
my_list = [10, 20, 30]
del my_list[1] # delete item at index 1
print(my_list)
[10, 30]
#60.
passA null statement. It's used when a statement is required syntactically but you do not want any command or code to execute.
def my_empty_function():
pass # To be implemented later
my_empty_function() # This does nothing and produces no error
print("Function executed without error.")
Function executed without error.
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1
Top 30 Cyber Security Commands & Tools
#CyberSecurity #Reconnaissance #InfoGathering
#1.
Tests reachability of a host on an IP network and measures round-trip time.
#2.
Retrieves registration information for a domain name or IP address.
#3.
(Domain Information Groper) A tool for querying DNS servers.
#4.
Network Mapper. A powerful tool for network discovery, port scanning, and security auditing.
#5.
The "Swiss army knife" of networking. Can be used for port scanning, file transfer, and creating backdoors.
---
#CyberSecurity #Networking #Analysis
#6.
Displays active network connections, routing tables, and interface statistics.
#7.
Traces the network path (hops) to a remote host.
#8.
A powerful command-line packet analyzer that allows you to capture and display network traffic.
#9.
Displays and modifies the Address Resolution Protocol (ARP) cache, which maps IP addresses to MAC addresses.
#10.
A modern tool to show and manipulate routing, devices, policy routing, and tunnels. (Replaces
#CyberSecurity #Reconnaissance #InfoGathering
#1.
pingTests reachability of a host on an IP network and measures round-trip time.
ping -c 4 google.com
PING google.com (142.250.72.14) 56(84) bytes of data.
64 bytes from lhr48s23-in-f14.1e100.net (142.250.72.14): icmp_seq=1 ttl=118 time=8.53 ms
...
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
#2.
whoisRetrieves registration information for a domain name or IP address.
whois google.com
Domain Name: GOOGLE.COM
Registry Domain ID: 2138514_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.markmonitor.com
...
Registrant Organization: Google LLC
Registrant State/Province: CA
Registrant Country: US
#3.
dig(Domain Information Groper) A tool for querying DNS servers.
dig google.com
; <<>> DiG 9.18.1-1-Debian <<>> google.com
;; ANSWER SECTION:
google.com. 156 IN A 142.250.187.238
...
;; Query time: 12 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
#4.
nmapNetwork Mapper. A powerful tool for network discovery, port scanning, and security auditing.
nmap -sV -p 80,443 scanme.nmap.org
Starting Nmap 7.92 ( https://nmap.org ) at ...
Nmap scan report for scanme.nmap.org (45.33.32.156)
Host is up (0.16s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
443/tcp open ssl/http Apache httpd 2.4.7 ((Ubuntu))
#5.
netcat (nc)The "Swiss army knife" of networking. Can be used for port scanning, file transfer, and creating backdoors.
nc -zv scanme.nmap.org 80
Connection to scanme.nmap.org (45.33.32.156) 80 port [tcp/http] succeeded!
---
#CyberSecurity #Networking #Analysis
#6.
netstatDisplays active network connections, routing tables, and interface statistics.
netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 675/postgres
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 789/sshd
udp 0 0 0.0.0.0:68 0.0.0.0:* 654/dhclient
#7.
tracerouteTraces the network path (hops) to a remote host.
traceroute 8.8.8.8
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets
1 gateway (192.168.1.1) 1.234 ms 1.567 ms 1.890 ms
2 isp-router.net (10.0.0.1) 5.432 ms 5.678 ms 5.901 ms
...
10 142.251.52.221 (142.251.52.221) 10.112 ms 10.345 ms 10.578 ms
11 dns.google (8.8.8.8) 10.801 ms 10.923 ms 11.045 ms
#8.
tcpdumpA powerful command-line packet analyzer that allows you to capture and display network traffic.
sudo tcpdump -i eth0 -c 5 port 80
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
14:30:01.123456 IP my-pc.54321 > example.com.80: Flags [S], seq 123456789, win 64240, options [mss 1460,sackOK,TS val 10,ecr 0], length 0
... (4 more packets) ...
5 packets captured
#9.
arpDisplays and modifies the Address Resolution Protocol (ARP) cache, which maps IP addresses to MAC addresses.
arp -a
? (192.168.1.1) at 00:1a:2b:3c:4d:5e [ether] on eth0
? (192.168.1.105) at 98:76:54:32:10:fe [ether] on eth0
#10.
ipA modern tool to show and manipulate routing, devices, policy routing, and tunnels. (Replaces
ifconfig).ip addr show
❤1
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 ...
inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...
inet 192.168.1.100/24 brd 192.168.1.255 scope global dynamic eth0
---
#CyberSecurity #WebSecurity #Vulnerability
#11.
curlA tool to transfer data from or to a server, using various protocols. Essential for interacting with web APIs and inspecting HTTP headers.
curl -I http://example.com
HTTP/1.1 200 OK
Content-Encoding: gzip
Accept-Ranges: bytes
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Fri, 27 Oct 2023 10:00:00 GMT
Server: ECS (dcb/7F83)
Content-Length: 648
#12.
gobusterA fast tool used to brute-force URIs (directories and files), DNS subdomains, and virtual host names.
gobuster dir -u http://example.com -w /usr/share/wordlists/dirb/common.txt
===============================================================
Gobuster v3.5
===============================================================
[+] Url: http://example.com
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirb/common.txt
===============================================================
/index.html (Status: 200) [Size: 1256]
/images (Status: 301) [Size: 178] -> http://example.com/images/
/javascript (Status: 301) [Size: 178] -> http://example.com/javascript/
#13.
niktoA web server scanner which performs comprehensive tests against web servers for multiple items, including over 6700 potentially dangerous files/CGIs.
nikto -h http://scanme.nmap.org
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 45.33.32.156
+ Target Hostname: scanme.nmap.org
+ Target Port: 80
+ Start Time: ...
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ OSVDB-3233: /icons/README: Apache default file found.
#14.
sqlmapAn open-source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws.
sqlmap -u "http://testphp.vulnweb.com/listproducts.php?cat=1" --dbs
...
available databases [2]:
[*] information_schema
[*] acuart
#15.
whatwebIdentifies different web technologies including content management systems (CMS), blogging platforms, statistic/analytics packages, JavaScript libraries, web servers, and embedded devices.
whatweb scanme.nmap.org
http://scanme.nmap.org [200 OK] Apache[2.4.7], Country[UNITED STATES], HTTPServer[Ubuntu Linux][Apache/2.4.7 ((Ubuntu))], IP[45.33.32.156], Script, Title[Go ahead and ScanMe!], Ubuntu
---
#CyberSecurity #PasswordCracking #Exploitation
#16.
John the Ripper (john)A fast password cracker, currently available for many flavors of Unix, Windows, DOS, and OpenVMS.
# Assume 'hashes.txt' contains 'user:$apr1$A.B.C...$...'
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, 32/64 OpenSSL)
Press 'q' or Ctrl-C to abort, almost any other key for status
password123 (user)
1g 0:00:00:01 DONE (2023-10-27 10:15) 0.9803g/s 1234p/s 1234c/s
Session completed
#17.
hashcatAn advanced password recovery utility that can crack a wide variety of hash types using multiple attack modes (dictionary, brute-force, mask).
# -m 0 = MD5 hash type
hashcat -m 0 -a 0 hashes.md5 /usr/share/wordlists/rockyou.txt
...
Session..........: hashcat
Status...........: Cracked
Hash.Name........: MD5
Hash.Target......: 5f4dcc3b5aa765d61d8327deb882cf99
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
...
Recovered........: 1/1 (100.00%) Digests
#18.
hydraA parallelized login cracker which supports numerous protocols to attack. It is very fast and flexible.
hydra -l user -P /path/to/passwords.txt ftp://192.168.1.101
Hydra v9.1 (c) 2020 by van Hauser/THC - Please do not use in military projects
...
[21][ftp] host: 192.168.1.101 login: user password: password
1 of 1 target successfully completed, 1 valid password found
#19.
Metasploit Framework (msfconsole)An exploitation framework for developing, testing, and executing exploit code against a remote target machine.
msfconsole
=[ metasploit v6.3.3-dev ]
+ -- --=[ 2289 exploits - 1184 auxiliary - 406 post ]
+ -- --=[ 953 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
msf6 >
#20.
searchsploitA command-line search tool for Exploit-DB that also allows you to take a copy of exploits to your working directory.
searchsploit apache 2.4.7
-------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------- ---------------------------------
Apache 2.4.7 (Ubuntu) - 'mod_cgi' Bash Env | linux/remote/34900.py
Apache mod_authz_svn < 1.8.10 / < 1.7.18 - | multiple/remote/34101.txt
-------------------------------------------------- ---------------------------------
---
#CyberSecurity #Forensics #Utilities
#21.
stringsPrints the sequences of printable characters in files. Useful for finding plaintext credentials or other information in binary files.
strings /bin/bash
/lib64/ld-linux-x86-64.so.2
_ITM_deregisterTMCloneTable
__gmon_start__
...
echo
read
printf
#22.
grepSearches for patterns in each file. An indispensable tool for parsing log files and command output.
grep "Failed password" /var/log/auth.log
Oct 27 10:20:05 server sshd[1234]: Failed password for invalid user admin from 203.0.113.5 port 54321 ssh2
Oct 27 10:20:10 server sshd[1236]: Failed password for root from 203.0.113.5 port 12345 ssh2
#23.
chmodChanges the permissions of files and directories. Critical for hardening a system.
# Before
ls -l script.sh
-rwxrwxr-x 1 user user 50 Oct 27 10:25 script.sh
# Command
chmod 700 script.sh
# After
ls -l script.sh
-rwx------ 1 user user 50 Oct 27 10:25 script.sh
#24.
xxdCreates a hex dump of a given file or standard input. It can also convert a hex dump back to its original binary form.
echo -n "Hi" | xxd
00000000: 4869 Hi
#25.
base64Encodes and decodes data in Base64 format. Commonly used in web applications and email attachments.
echo -n "security" | base64
c2VjdXJpdHk=
---
#CyberSecurity #Crypto #Hashing
#26.
opensslA robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. Also a general-purpose cryptography library.
# Generate a self-signed certificate
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
Generating a RSA private key
...........................................................................+++++
......................................................................+++++
writing new private key to 'key.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
...
(Files key.pem and cert.pem are created)
#27.
sha256sumComputes and checks a SHA256 message digest. Used to verify file integrity.
echo -n "hello world" > file.txt
sha256sum file.txt
b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 file.txt
#28.
gpg(GNU Privacy Guard) A complete and free implementation of the OpenPGP standard, allowing you to encrypt and sign your data and communications.
# Encrypt a file
echo "secret message" > secret.txt
gpg -c secret.txt
(A file named secret.txt.gpg is created after prompting for a passphrase)
#29.
aircrack-ngA complete suite of tools to assess Wi-Fi network security. It focuses on monitoring, attacking, testing, and cracking.
# Put interface in monitor mode
airmon-ng start wlan0
PHY Interface Driver Chipset
phy0 wlan0 ath9k Atheros Communications Inc. AR9271 802.11n
(mac80211 monitor mode vif enabled for [phy0]wlan0 on [phy0]wlan0mon)
(mac80211 station mode vif disabled for [phy0]wlan0)
#30.
theHarvesterA tool for gathering open-source intelligence (OSINT) to help determine a company's external threat landscape.
theharvester -d google.com -l 100 -b google
[*] Target: google.com
[*] Searching Google for 100 results...
[*] Found 2 emails:
- some-email@google.com
- another-email@google.com
[*] Found 15 hosts:
- host1.google.com
- host2.google.com
...
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤2
Please open Telegram to view this post
VIEW IN TELEGRAM
100 Python Examples: A Step-by-Step Guide
#Python #Programming #Tutorial #LearnPython
Part 1: The Basics (Examples 1-15)
#1. Print "Hello, World!"
The classic first program.
#2. Variables and Strings
Store text in a variable and print it.
#3. Integer Variable
Store a whole number.
#4. Float Variable
Store a number with a decimal point.
#5. Boolean Variable
Store a value that is either
#6. Get User Input
Use the
#7. Simple Calculation
Perform a basic arithmetic operation.
#8. Comments
Use
#9. Type Conversion (String to Integer)
Convert a user's input (which is a string) to an integer to perform math.
#10. String Concatenation
Combine multiple strings using the
#11. Multiple Assignment
Assign values to multiple variables in one line.
#12. The
Check the data type of a variable.
#13. Basic Arithmetic Operators
Demonstrates addition, subtraction, multiplication, and division.
#14. Floor Division and Modulus
#15. Exponentiation
Use
---
Part 2: String Manipulation (Examples 16-25)
#16. String Length
Use
#Python #Programming #Tutorial #LearnPython
Part 1: The Basics (Examples 1-15)
#1. Print "Hello, World!"
The classic first program.
print() is a function that outputs text to the console.print("Hello, World!")Hello, World!
#2. Variables and Strings
Store text in a variable and print it.
message = "I am learning Python."
print(message)
I am learning Python.
#3. Integer Variable
Store a whole number.
age = 30
print("My age is:", age)
My age is: 30
#4. Float Variable
Store a number with a decimal point.
price = 19.99
print("The price is:", price)
The price is: 19.99
#5. Boolean Variable
Store a value that is either
True or False.is_learning = True
print("Am I learning?", is_learning)
Am I learning? True
#6. Get User Input
Use the
input() function to get information from the user.name = input("What is your name? ")
print("Hello, " + name)What is your name? Alice
Hello, Alice
#7. Simple Calculation
Perform a basic arithmetic operation.
a = 10
b = 5
print(a + b)
15
#8. Comments
Use
# to add comments that Python will ignore.# This line calculates the area of a rectangle
length = 10
width = 5
area = length * width
print("Area is:", area)
Area is: 50
#9. Type Conversion (String to Integer)
Convert a user's input (which is a string) to an integer to perform math.
age_str = input("Enter your age: ")
age_int = int(age_str)
next_year_age = age_int + 1
print("Next year you will be:", next_year_age)Enter your age: 25
Next year you will be: 26
#10. String Concatenation
Combine multiple strings using the
+ operator.first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
John Doe
#11. Multiple Assignment
Assign values to multiple variables in one line.
x, y, z = 10, 20, 30
print(x, y, z)
10 20 30
#12. The
type() FunctionCheck the data type of a variable.
num = 123
text = "hello"
pi = 3.14
print(type(num))
print(type(text))
print(type(pi))
<class 'int'>
<class 'str'>
<class 'float'>
#13. Basic Arithmetic Operators
Demonstrates addition, subtraction, multiplication, and division.
a = 15
b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
#14. Floor Division and Modulus
// for division that rounds down, and % for the remainder.a = 15
b = 4
print("Floor Division:", a // b)
print("Modulus (Remainder):", a % b)
Floor Division: 3
Modulus (Remainder): 3
#15. Exponentiation
Use
** to raise a number to a power.power = 3 ** 4 # 3 to the power of 4
print(power)
81
---
Part 2: String Manipulation (Examples 16-25)
#16. String Length
Use
len() to get the number of characters in a string.my_string = "Python is fun"
print(len(my_string))
13
❤1