day 15 Generator 🔹 Generator in Python A Generator is a special type of function that allows you to generate values one at a time instead of returning all values at once. Normally, when we use return, a function ends after returning one value. But using the yield keyword, a generator can pause its execution and continue later, producing multiple values over time. Why use Generators? ✔ Saves memory ✔ Handles large datasets efficiently ✔ Generates values only when needed (lazy evaluation) Example def number_generator(): yield 1 yield 2 yield 3 for num in number_generator(): print(num) How it works 1️⃣ Function starts execution 2️⃣ yield returns a value 3️⃣ Function pauses its state 4️⃣ When called again, it continues from where it stopped Decorator in Python A Decorator is used to modify or extend the behavior of a function without changing its original code. In simple terms, a decorator wraps another function and adds extra functionality. Why use Decorators? ✔ Code reusability ✔ Clean and maintainable code ✔ Add logging, authentication, timing, etc. Example def my_decorator(func): def wrapper(): print("Before function execution") func() print("After function execution") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() Decorators are widely used in frameworks like Flask, Django, and FastAPI 15 challenge completed i have covered all topics in python more information follow Prem chandar #Python #PythonProgramming #MachineLearning #DataScience #SoftwareDevelopment #Coding #DeveloperLife #AI #TechLearning #social media #network #share #support
Python Generators & Decorators Explained
More Relevant Posts
-
Minimal Python RAG Agent Example Using LlamaIndex Here's a bare-bones RAG agent implementation ready to run after installing dependencies: ```python # Install dependencies # pip install llama-index-core llama-index-readers-file llama-index-embeddings-openai import os from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings # 2. Specify document path cwd = os.getcwd() + "\\\\data" documents = SimpleDirectoryReader(cwd).load_data() # 3. Global settings (override as needed) Settings.embed_model = "openai/text-embedding-3-small" Settings.llm = None # Use OpenAI GPT-4 by default # 4. Build index index = VectorStoreIndex.from_documents(documents) # 5. Create query engine query_engine = index.as_query_engine() # 5. Run query response = query_engine.query("What are data security requirements in the policy?") print(response) ``` What this does: - Automatically cites source documents - Supports streaming & citations for UX - Requires only 5 lines of custom code For production: Add rerankers, metadata filters, and caching. #CodeSnippet #Python #RAG #LlamaIndex #AIDevelopment #OpenSource
To view or add a comment, sign in
-
Logic in Python – Understanding and, or, and not! 🔗🐍 Programs aren’t just about calculations—they need to make decisions. That’s where logical operators come in. They let us combine multiple conditions and control the flow of our code. This session was all about mastering the three core logical operators in Python: and, or, and not. Here’s what I learned: --- 🔹 The and Operator · Returns True only if both operands are True. · Otherwise, it returns False. A and B True + True = True True + False = False False + True = False False + False = False ```python print((2 < 3) and (1 < 2)) # True and True → True print((5 > 3) and (2 > 5)) # True and False → False ``` --- 🔹 The or Operator · Returns True if at least one operand is True. · Only False if both are False. A B A or B True + True = True True + False = True False + True = True False + False = False ```python print(True or False) # True print(False or False) # False ``` --- 🔹 The not Operator · Reverses the boolean value. · not True → False · not False → True ```python print(not True) # False print(not False) # True ``` --- ✅ Key Takeaways: · Logical operators work with boolean values and return booleans. · and → all must be true · or → at least one true · not → flips the truth value · You can combine them with relational operators to build complex conditions. --- 💬 Let’s Discuss: Have you ever used and/or in a real project? What’s the most creative condition you’ve built with them? Drop your examples below! 👇 --- 🔖 #Python #LogicalOperators #CodingBasics #LearnToCode #ProgrammingLogic #NXTWave #TechJourney
To view or add a comment, sign in
-
🔎 What if you could know the moment a website changes? From pricing updates to competitor pages and documentation edits, tracking changes manually is not practical. A simple Python script can handle it automatically. This guide shows how to build a website change tracker with Python and Crawlbase that fetches pages, generates SHA-256 content fingerprints, and detects updates reliably. What you will learn: 🔹 Fetch page content using the Crawlbase Crawling API 🔹 Extract clean text and generate content fingerprints 🔹 Detect changes by comparing snapshots 🔹 Run the tracker automatically on a schedule A practical tool for developers working on monitoring, research, or automation. 📖 Read the full article: https://lnkd.in/gXQuPZcS #Crawlbase #Python #WebScraping #Developers #Automation #WebsiteMonitoring #DataEngineering
To view or add a comment, sign in
-
You’re probably writing more Python code than you need to. Small tricks can make your code cleaner, faster, and easier to read which AI might also miss if not prompted well. I came across a collection of 100 Python tips that covers both basics and practical patterns 1] Cleaner syntax • List, set, and dictionary comprehensions for concise code • Swapping variables and unpacking in a single line Less code, same logic. 2] Built-in power • Modules like collections, itertools, datetime • Functions like enumerate, zip, sorted Python already gives you most of what you need. 3] Writing efficient code • Generators vs list comprehensions (memory vs speed tradeoff) • Using built-ins instead of manual loops Efficiency often comes from using the right abstraction. 4] Working with real tasks • File handling, PDFs, screenshots, web automation • Data handling with pandas 5] Debugging and readability • Assertions for early error detection • Zen of Python principles Good code is easy to understand. Python is simple. But writing clean Python is a skill. #python #programming #developer #coding #softwareengineering
To view or add a comment, sign in
-
😊❤️ Todays topic: Topic: Lambda Functions in Python ================ A lambda function is a small anonymous function defined in a single line. It is used when you need a simple function for a short period of time. Basic Syntax: lambda arguments: expression Example (Normal Function): def add(a, b): return a + b print(add(2, 3)) Same using lambda: add = lambda a, b: a + b print(add(2, 3)) Output: 5 Using lambda with built-in functions: map() numbers = [1, 2, 3, 4] result = list(map(lambda x: x * 2, numbers)) print(result) Output: [2, 4, 6, 8] filter() numbers = [1, 2, 3, 4, 5] result = list(filter(lambda x: x % 2 == 0, numbers)) print(result) Output: [2, 4] Key Points: No function name Single expression only (no multiple statements) Automatically returns result When to use: Small, simple operations Temporary functions (especially with map, filter, sorted) 😍Interview Insight: Lambda functions improve code readability when used correctly, but overusing them can make code harder to understand. Quick Question: What will be the output? result = list(map(lambda x: x + 1, [1, 2, 3])) print(result) #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
Day 8 of my Python journey — while loops. This is where Python stops being a calculator and starts being an automated process. Every server that keeps running. Every chatbot that waits for your message. Every retry mechanism that keeps attempting a failed network request. Every interactive menu that loops until you choose to exit. All of it is a while loop at its core. The while-else clause — the pattern most tutorials skip attempts = 0 while attempts < 3: pin = input("Enter PIN: ") if pin == "1234": print("Access granted") break attempts += 1 else: print("Account locked — 3 failed attempts") The else clause on a while loop runs only if the loop completed naturally — meaning it reached the condition and found it False — without ever hitting a break. This exact pattern is how every PIN system, every OTP validator, and every rate-limited login system works. Three attempts. Break on success. Lock on failure. The input validation pattern — used in every interactive program while True: try: age = int(input("Enter your age: ")) if 0 < age < 120: break print("Please enter a valid age between 1 and 119") except ValueError: print("Please enter a number, not text") This while True + break + validation pattern is the professional standard for any program that accepts user input. It loops indefinitely until valid input is received, handles both wrong type and wrong range, and exits cleanly. Every CLI tool, every form processor, every interactive script uses this. What I built today: a number guessing game (random 1–100, max 10 attempts, attempt counter, win/lose message), a 3-attempt PIN system that locks on failure, and an input validator that accepts only integers in a valid range. The game took 34 lines. It handles every case: correct guess, wrong guess, too many attempts, invalid input. Zero crashes under any input. Automation starts with a loop. #Python#Day8#ConditionalLogic#SelfLearning#CodewithHarry#PythonBasics#w3schools.com#W3Schools
To view or add a comment, sign in
-
Your build server is running out of space. You run df -h. 94% full. Great. So you du -sh your way through directories like it's 2005, mentally adding up numbers, until you finally find the 6 .venv folders nobody cleaned up. There's a better way — and building it yourself is half the point. In my latest article, I walk through building pydusk: a terminal disk usage analyzer in Python, inspired by ncdu. Keyboard-driven, non-blocking, with a delete confirmation flow and a clean TUI — all in a single file with two dependencies. Stack: Textual · Typer · os.scandir Things worth stealing from this project even if you never run it: → Why os.scandir beats os.walk for disk traversal → Textual's @work(thread=True) pattern for background tasks → ModalScreen[T] + dismiss() for confirmation dialogs https://lnkd.in/dmKvDSgH #Python #Textual #CLI #OpenSource #Developer
To view or add a comment, sign in
-
😊❤️ Todays topic: List Comprehension in Python ============== List comprehension is a shorter and cleaner way to create lists. Instead of writing multiple lines using loops, you can do it in one line. Basic Example: numbers = [1, 2, 3, 4] squares = [] for i in numbers: squares.append(i * i) print(squares) Now the same using list comprehension: numbers = [1, 2, 3, 4] squares = [i * i for i in numbers] print(squares) Output: [1, 4, 9, 16] Structure: new_list = [expression for item in iterable] expression → what you want to do item → each element iterable → list, tuple, etc. With Condition: numbers = [1, 2, 3, 4, 5, 6] even_numbers = [i for i in numbers if i % 2 == 0] print(even_numbers) Output: [2, 4, 6] With if-else: numbers = [1, 2, 3, 4] result = ["even" if i % 2 == 0 else "odd" for i in numbers] print(result) Output: ['odd', 'even', 'odd', 'even'] Key Points: Makes code shorter and readable Faster than traditional loops in many cases Best used for simple transformations 😎Interview Insight: Avoid very complex list comprehensions with multiple nested conditions, as they reduce readability. Use normal loops when logic becomes complex. Quick Question: Convert this loop into list comprehension?? result = [] for i in range(5): result.append(i + 10) #Python #Programming #Coding #InterviewPreparation #Developers
To view or add a comment, sign in
-
The SFrame project from GraphLab/Dato/Turi I still consider to be one of my best pieces of work. It being C++ though, means it did not age particularly well. The C++ <-> Python bindings in particular, are very fragile. I have always wanted to reimplement it in Rust, and now with the assistance of Claude ... I now have SFrameRust https://lnkd.in/gpd_TgSp :-) Python bindings included. The entire repo is AI coded with a lot of human direction for design. - It appears binary compatible with the original SFrame; it can load the original SFrame format. (I gave it an original SFrame to validate against) - The completely insane parallel CSV parser (which can read JSONL) has been ported and seems to all work. - Performance is *pretty darn good*. (I have not validated every method yet). For methods which I have guided Claude to optimize, it is on par or faster. One of the key features of SFrame is that all its algorithms are designed to keep pretty tight within a memory budget, regardless of size of input. So with care over a few days, I directed Claude (Opus[1m]) to do a most excellent port of the original SFrame sorting algorithm. The current implementation sorts TPC-DS catalog_sales (sc-100 144M rows) in 1:42 min on my laptop (Mac M2 Max). DuckDB took 5 min. (memory limit 8GB) (Note: All benchmarks are unfair and this is no different :-) This is not intended to be a competition. The SFrame sort is *very specialized* for reading/writing SFrame formats and I don't think will work with Parquet though I have not thought too hard about it) Code quality is all considered pretty decent, but I had to continuously provide careful architectural direction. The initial port (done by a Ralph loop) took much too many shortcuts. The issue is that the plans Claude generates are not detailed enough, are non-hierarchical, and are immutable. If it can plan at different levels of abstraction, and can modify plans, I think it can be a lot better. Also implementation sub-agents have much too narrow objectives and tend to lose the big picture. For instance, it will constantly forget that the SFrame design goals is to maximize parallelism, minimize memory utilization, and will keep writing code that reads everything into memory. It will also forget that the query executor has parallel streaming capabilities. It makes sense to minimize the amount of context the implementation agent needs to do its job, but on the other hand that also means that in a large project it does not see enough code patterns to understand the broad design intentions. Anyway, as an experiment, I consider this to be quite a success. I have learnt a lot about working with AI, got a better sense of its capabilities and its limits, and most importantly... scratched an itch (That's basically all my personal AI projects right now). I have no idea what to do with the outcome though :-)
To view or add a comment, sign in
-
Day 30 of #60DaysOfMiniProjects Today I stepped into the world of Web Scraping using Python I built a Webpage Analyzer that extracts and summarizes key details from any website using Python. At first glance, it looks simple—but this project helped me understand how real-world data extraction works behind the scenes. What this project does: • Takes a website URL as input • Fetches webpage content using requests • Parses HTML using BeautifulSoup • Extracts important insights from the page What it analyzes: • Webpage title • Total number of links • Total number of images • Total number of paragraphs Concepts I worked with: • Web scraping fundamentals • HTTP requests handling • HTML parsing • DOM structure understanding • Exception handling in Python This project gave me a clear idea of how websites are structured and how data can be programmatically extracted and analyzed. Next step: Building a more advanced scraper with filtering + data storage Learning step by step. Building consistently. Improving every day. #Python #WebScraping #BeautifulSoup #Requests #MiniProjects #BuildInPublic #CodingJourney #DeveloperGrowth #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development