Python | Algorithms | Data Structures | Cyber Security | Networks
Photo
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout,
QLabel, QLineEdit, QPushButton)
class ConverterApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Temperature Converter")
self.setup_ui()
def setup_ui(self):
# Create widgets
self.celsius_input = QLineEdit()
self.fahrenheit_input = QLineEdit()
self.convert_btn = QPushButton("Convert")
self.result_label = QLabel("Enter temperature to convert")
# Set up layout
layout = QVBoxLayout()
layout.addWidget(QLabel("Celsius:"))
layout.addWidget(self.celsius_input)
layout.addWidget(QLabel("Fahrenheit:"))
layout.addWidget(self.fahrenheit_input)
layout.addWidget(self.convert_btn)
layout.addWidget(self.result_label)
# Connect button click
self.convert_btn.clicked.connect(self.convert)
self.setLayout(layout)
def convert(self):
try:
if self.celsius_input.text():
# Celsius to Fahrenheit
celsius = float(self.celsius_input.text())
fahrenheit = (celsius * 9/5) + 32
self.fahrenheit_input.setText(f"{fahrenheit:.2f}")
self.result_label.setText("Conversion complete!")
elif self.fahrenheit_input.text():
# Fahrenheit to Celsius
fahrenheit = float(self.fahrenheit_input.text())
celsius = (fahrenheit - 32) * 5/9
self.celsius_input.setText(f"{celsius:.2f}")
self.result_label.setText("Conversion complete!")
except ValueError:
self.result_label.setText("Please enter a valid number!")
if __name__ == "__main__":
app = QApplication([])
window = ConverterApp()
window.show()
app.exec_()
---
## 🔹 PyQt5 Designer Tool
Qt Designer lets you create UIs visually:
1. Launch Designer:
pyqt5-tools designer
2. Design your interface (saves as
.ui file)3. Convert to Python code:
pyuic5 input.ui -o output.py
Example Usage:
from PyQt5 import uic
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('design.ui', self) # Load UI file
---
## 🔹 Event Handling Basics
PyQt5 uses signals and slots for interactivity:
# Connecting signals to slots
button.clicked.connect(self.on_button_click)
checkbox.stateChanged.connect(self.on_checkbox_change)
line_edit.textChanged.connect(self.on_text_change)
# Example slot methods
def on_button_click(self):
print("Button clicked!")
def on_checkbox_change(self, state):
print("Checkbox state:", state)
def on_text_change(self, text):
print("Text changed to:", text)
---
## 🔹 Best Practices for Beginners
1. Organize code in classes/methods
2. Use layouts instead of absolute positioning
3. Name widgets clearly (e.g.,
self.login_btn)4. Separate UI code from business logic
5. Handle errors gracefully in event handlers
---
### 📌 What's Next?
In Part 2, we'll cover:
➡️ Advanced Widgets (Tables, Trees, Tabs)
➡️ Custom Signals
➡️ Styling with QSS
➡️ Multiple Windows
#PyQt5Tutorial #GUIPython #LearnToCode 🚀
Practice Exercise:
1. Create a simple calculator app
2. Build a text editor with save/load buttons
3. Make a color picker that changes window background
Learning Common Algorithms with Python
• This lesson covers fundamental algorithms implemented in Python. Understanding these concepts is crucial for building efficient software. We will explore searching, sorting, and recursion.
• Linear Search: This is the simplest search algorithm. It sequentially checks each element of the list until a match is found or the whole list has been searched. Its time complexity is O(n).
• Binary Search: A much more efficient search algorithm, but it requires the list to be sorted first. It works by repeatedly dividing the search interval in half. Its time complexity is O(log n).
• Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Its time complexity is O(n^2).
• Recursion (Factorial): Recursion is a method where a function calls itself to solve a problem. A classic example is calculating the factorial of a number (
#Python #Algorithms #DataStructures #Coding #Programming #LearnToCode
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
• This lesson covers fundamental algorithms implemented in Python. Understanding these concepts is crucial for building efficient software. We will explore searching, sorting, and recursion.
• Linear Search: This is the simplest search algorithm. It sequentially checks each element of the list until a match is found or the whole list has been searched. Its time complexity is O(n).
def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if the element is not found
# Example
my_list = [4, 2, 7, 1, 9, 5]
print(f"Linear Search: Element 7 found at index {linear_search(my_list, 7)}")
• Binary Search: A much more efficient search algorithm, but it requires the list to be sorted first. It works by repeatedly dividing the search interval in half. Its time complexity is O(log n).
def binary_search(sorted_data, target):
low = 0
high = len(sorted_data) - 1
while low <= high:
mid = (low + high) // 2
if sorted_data[mid] < target:
low = mid + 1
elif sorted_data[mid] > target:
high = mid - 1
else:
return mid # Element found
return -1 # Element not found
# Example
my_sorted_list = [1, 2, 4, 5, 7, 9]
print(f"Binary Search: Element 7 found at index {binary_search(my_sorted_list, 7)}")
• Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Its time complexity is O(n^2).
def bubble_sort(data):
n = len(data)
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if data[j] > data[j+1]:
# Swap the elements
data[j], data[j+1] = data[j+1], data[j]
return data
# Example
my_list_to_sort = [4, 2, 7, 1, 9, 5]
print(f"Bubble Sort: Sorted list is {bubble_sort(my_list_to_sort)}")
• Recursion (Factorial): Recursion is a method where a function calls itself to solve a problem. A classic example is calculating the factorial of a number (
n!). It must have a base case to stop the recursion.def factorial(n):
# Base case: if n is 1 or 0, factorial is 1
if n == 0 or n == 1:
return 1
# Recursive step: n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example
num = 5
print(f"Recursion: Factorial of {num} is {factorial(num)}")
#Python #Algorithms #DataStructures #Coding #Programming #LearnToCode
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1