Day 11 🚀 Python Series – Exception Handling (Simple & Clear) When we write programs, errors can happen during execution. If we don’t handle them, the program will crash ❌ 👉 Exception Handling helps us manage errors smoothly without stopping the entire program. 🔹 Why We Use It? To handle runtime errors and keep the program running safely. 🔑 Main Keywords in Exception Handling ✅ try Write the risky code inside this block. ✅ except Handles the error if it occurs. ✅ else Runs if there is NO error. ✅ finally Runs always (whether error happens or not). 💻 Simple Example try: num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) result = num1 / num2 except ZeroDivisionError: print("You cannot divide by zero!") except ValueError: print("Please enter valid numbers!") else: print("Result is:", result) finally: print("Program execution completed.") 🔍 What Happens Here? • If user enters 0 → ZeroDivisionError handled • If user enters text → ValueError handled • If no error → result will print • Finally → always executes 💡 Exception handling makes your program professional, safe, and user-friendly. Follow for more information Prem chandar #Python #PythonProgramming #ExceptionHandling #CodingLife #LearnToCode #DeveloperJourney #social media #network #brand #ai #ml
Python Exception Handling Basics with try except else finally
More Relevant Posts
-
How asyncio event loop actually works under the hood Async in Python often feels like magic. You write: await some_io() …and suddenly your app handles thousands of requests. But what’s really happening? At the core: event loop At the core of asyncio is the event loop. Think of it as a scheduler that constantly: • checks for ready tasks • runs them • pauses on await • switches to another task Key idea Async functions don’t run in parallel. They run cooperatively. Example: async def task(): await something() When Python hits await: • pauses the coroutine • returns control to the loop • runs another task Threads vs asyncio Threads: Thread A → running Thread B → waiting Asyncio: Task A → waiting for I/O Task B → running Task C → ready What happens under the hood Very simplified loop: while True: run ready tasks wait for I/O The real magic — I/O When you do: await socket.recv() Python: • registers the socket in OS (epoll / kqueue) • pauses the coroutine • resumes it when data is ready No blocking. No busy waiting. Why it’s powerful • thousands of connections in one thread • low memory usage • no thread switching overhead Important limitation CPU-bound code blocks everything. for i in range(10_000_000): pass → event loop freezes Rule of thumb I/O-bound → asyncio CPU-bound → multiprocessing Mental model Tasks → Event Loop → OS → Event Loop → Tasks Question Do you use asyncio in production or still prefer threads? #Python #AsyncIO #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
My Data Science Journey — While Loop, Break, Continue, Functions & Modules Today marked an important shift — moving from basic scripts to building a real multi-file Python project executed from the terminal. 𝐖𝐡𝐚𝐭 𝐈 𝐋𝐞𝐚𝐫𝐧𝐞𝐝: While Loop – Executes as long as a condition remains true – Requires initialization, condition, and update – Understood how missing updates can lead to infinite loops – Built practical examples like multiplication tables Break & Continue – break exits the loop immediately – continue skips the current iteration and moves to the next – Applied both in real scenarios like searching values within a list Functions – Created reusable functions using def – Improved code readability and reusability – Learned how to define once and use multiple times Modularization – Organized code into multiple files for better structure – Improved maintainability, scalability, and reusability Multi-File Project – Built a structured Python project with separate modules – Imported functions across files and executed them from a main entry point – Successfully ran the project using the terminal environment 𝐊𝐞𝐲 𝐈𝐧𝐬𝐢𝐠𝐡𝐭: This was the day everything connected — environment setup, operators, conditionals, loops, and now functions with modular project structure. Consistent learning is starting to compound into real development skills. This felt like a shift from writing code to building actual programs. Read the full breakdown with code examples on Medium 👇 https://lnkd.in/g9mDKQxQ #DataScienceJourney #Python #WhileLoop #Functions #Modules #Programming #Learning #Developers
To view or add a comment, sign in
-
𝐏𝐲𝐭𝐡𝐨𝐧 𝐈𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝐄𝐱𝐩𝐥𝐚𝐢𝐧𝐞𝐝 (List → Iterator → Generator → yield) If you understand these 4 concepts, you understand how Python loops actually work. Most developers use them every day… but rarely think about how they are connected. Let’s break it down simply. 1️⃣ 𝐋𝐢𝐬𝐭 — 𝐬𝐭𝐨𝐫𝐞𝐬 𝐞𝐯𝐞𝐫𝐲𝐭𝐡𝐢𝐧𝐠 𝐟𝐢𝐫𝐬𝐭 A list prepares all values in memory before you start using them. Example numbers = [1, 2, 3, 4] This is simple and fast for small datasets. But if the dataset is very large (logs, API data, millions of records), memory usage grows quickly. 2️⃣ 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫 — 𝐫𝐞𝐭𝐫𝐢𝐞𝐯𝐞𝐬 𝐯𝐚𝐥𝐮𝐞𝐬 𝐨𝐧𝐞 𝐛𝐲 𝐨𝐧𝐞 An iterator returns the next element when asked. When you write a loop like: for n in numbers: print(n) Python internally uses something similar to: next(iterator) Each call retrieves the next value. Think of it like pressing a Next button. 3️⃣ 𝐆𝐞𝐧𝐞𝐫𝐚𝐭𝐨𝐫 — 𝐜𝐫𝐞𝐚𝐭𝐞𝐬 𝐯𝐚𝐥𝐮𝐞𝐬 𝐨𝐧 𝐝𝐞𝐦𝐚𝐧𝐝 A generator is simply an easy way to create an iterator. Instead of storing values, it produces them only when needed. Example def count(n): for i in range(n): yield i Now Python generates numbers one by one. This is perfect for: • large files • streaming APIs • big datasets • data pipelines 4️⃣ 𝐓𝐡𝐞 𝐤𝐞𝐲 𝐝𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞: 𝐫𝐞𝐭𝐮𝐫𝐧 𝐯𝐬 𝐲𝐢𝐞𝐥𝐝 Normal functions use 𝙧𝙚𝙩𝙪𝙧𝙣 𝙧𝙚𝙩𝙪𝙧𝙣 → function finishes immediately. Generators use 𝙮𝙞𝙚𝙡𝙙 𝙮𝙞𝙚𝙡𝙙 → pause the function produce a value resume later from the same place. This is why generators are memory efficient. 🧠 Mental model List → store everything Iterator → get next item Generator → create items on demand yield → pause & continue later Once this clicks, many Python features suddenly make sense. Curious to hear from other developers. When did generators finally “click” for you? #Python #AutomationTesting #TestAutomation #QAEngineering #SDET #LearnPython
To view or add a comment, sign in
-
-
No LangChain, no Python, no fancy framework. Just C, curl, and a local LLaMA model running with llama.cpp on my Machine. Why? I wanted to really feel what “agentic” AI looks like at the lowest level: 1) I spin up llama.cpp locally with a quantized Meta LLaMA model, exposing an OpenAI‑style /v1/chat/completions endpoint on localhost. 2) My C program opens a simple terminal loop, reads user input, and sends it as JSON over HTTP using libcurl. 3) The response is parsed directly from the raw JSON and printed back to the console – no SDKs, no helpers. 4) Every turn (User: / Bot:) is appended to a memory.txt log, so the agent has a persistent, readable conversation history I can inspect right inside my editor. 5) On top of that, I keep a sliding window of recent messages in memory and send them on every request, so the model can actually “remember” context during the session, not just answer one‑off prompts. It’s a tiny project, but it was a fun reminder of what’s actually happening under all the layers of modern tooling: you’re just sending structured text to a model, getting structured text back, and deciding how to manage state and side‑effects around it. Code: https://lnkd.in/ggdYXaZH
To view or add a comment, sign in
-
🚨 Most people got this Python question WRONG! Let’s fix it 👇 Yesterday, I posted a poll on LinkedIn asking: 👉 What is the output of these two codes? x = [10, 20, 30] x.append([40, 50]) print(len(x)) x = [10, 20, 30] x.extend([40, 50]) print(len(x)) 📊 The majority answered: 5 for both ❌ ✅ Correct Answers: 👉 append() → 4 👉 extend() → 5 💡 Why? 🔹 append() adds the entire list as ONE element Result: [10, 20, 30, [40, 50]] → length = 4 🔹 extend() adds elements individually Result:[10, 20, 30, 40, 50] → length = 5 🎯 Key Insight: append = “add as one” extend = “spread and add” 🔥 Why this matters: This small difference can create hidden bugs in: Data preprocessing Feature engineering ML pipelines 💬 Did you get it right? Comment your answer! #Python #DataAnalytics #DataScience #Learning #Coding #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 14/60 – Dictionary Comprehension (Level Up Your Python 🚀) Yesterday you learned list comprehension. Today, let’s level up 👇 🧠 What is Dictionary Comprehension? A quick way to create dictionaries in one clean line. ❌ Traditional Way numbers = [1, 2, 3, 4] squares = {} for num in numbers: squares[num] = num * num print(squares) ✅ Dictionary Comprehension Way numbers = [1, 2, 3, 4] squares = {num: num * num for num in numbers} print(squares) 👉 Cleaner. Faster. More Pythonic. 🔍 With Condition numbers = [1, 2, 3, 4, 5, 6] even_squares = {num: num * num for num in numbers if num % 2 == 0} print(even_squares) ⚡ Real Example names = ["adeel", "ali", "ahmed"] name_length = {name: len(name) for name in names} print(name_length) ❌ Common Mistake {num * num for num in numbers} # ❌ This creates a set Correct: {num: num * num for num in numbers} # ✅ Dictionary 🔥 Pro Tip Use dictionary comprehension when: ✅ You want clean transformation of data ❌ Avoid if logic becomes too complex 🔥 Challenge for today 👉 Create numbers from 1 to 5 👉 Create dictionary where: Key = number Value = cube of number Comment “DONE” when finished ✅ Follow Adeel Sajjad to stay consistent for 60 days 🚀 #Python #PythonProgramming #LearnPython #Coding #Programming #Developer #SoftwareEngineering
To view or add a comment, sign in
-
-
Ever feel like your AI/ML experiment configurations are just sprawling, error-prone dictionaries? 🤦♀️ You're not alone! While dictionaries are flexible, they can make your code harder to read, debug, and maintain, especially when dealing with many hyperparameters or dataset settings. Here's a trick to make your configuration management cleaner, safer, and much more readable: Python `dataclasses`! ✨ `dataclasses` let you define clear, type-hinted structures for your data. This means you get: 1. Readability: Know exactly what parameters are available. 2. Safety: Catch typos early with type checking. 3. Defaults: Easily set default values for optional parameters. 4. Immutability: (Optional) Make sure your config doesn't change unexpectedly. Imagine defining your model's hyperparameters or data processing settings with a clear structure instead of a nested dictionary. It makes passing configurations around your project a breeze and drastically reduces silent bugs. Plus, it integrates beautifully with modern Python tooling! How do you currently manage configurations in your AI/ML projects? Share your approach or other Python tricks below! 👇 #Python #AIML #MachineLearning #DataScience #PythonTips
To view or add a comment, sign in
-
-
If you're learning Python, strings are the first thing you must master. 🧵 I made this cheat sheet covering everything a beginner needs — all in one place. 👇 🔤 What's inside: 📌 Creating Strings — single, double, and triple quotes 📌 Indexing & Slicing — s[0], s[-1], s[0:4], s[::-1] 📌 Case Methods — upper(), lower(), title(), swapcase() 📌 Search Methods — find(), count(), startswith(), endswith() 📌 Check Methods — isalpha(), isdigit(), isalnum(), isspace() 📌 Replace & Strip — replace(), strip(), lstrip(), rstrip() 📌 Split & Join — split(), join() with real examples 📌 String Formatting — f-strings and .format() 📌 Operators — +, *, in keyword 🎁 Bonus Tip: Reverse any string in one line → s[::-1] Strings are everywhere — in web scraping, data cleaning, APIs, and automation. Getting comfortable with them early will save you hours of debugging later. ⏱️ 💾 Save this post and share it with someone learning Python today! --- 📌 Follow for daily Python tips, cheat sheets, and developer resources. #Python #LearnPython #PythonTips #CodingForBeginners #Programming #SoftwareDevelopment #PythonDeveloper #CodeNewbie #LearnPython #DataScience #AIBeginners #100DaysOfCode #TechEducation #DataScience #WebDevelopment #GenerativeAI
To view or add a comment, sign in
-
-
This week I built a Python-based automation system that uses AI vision parsing to eliminate manual trade logging. Here’s how it works: 1️⃣ I save a screenshot of my trade chart. 2️⃣ A Python script scans my “Trade Screenshots” folder for new images. 3️⃣ The image is sent to an AI model that parses the chart annotations (entries, exits, stop level, timeframe, planned R, etc.). 4️⃣ Python calculates the rest of the metrics such as weighted entry, exit size, P&L, and realized R. 5️⃣ The completed trade record is automatically appended to my Google Sheets journal. This was a fun project because it showed me how I can implement python automations, APIs, and structured data pipelines to eliminate repetitive, manual work. Excited to keep building tools like this that turn messy workflows into automated ones.
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