Day 10: While Loops — The Power of Repetition 🔄 In programming, we rarely want to do something just once. We want to do it until a specific goal is reached. This is where Loops come in. Today, we are focusing on the While Loop—the simplest way to tell Python: "Keep going until I tell you to stop." 1. The Concept: "Repeat Until..." A while loop checks a condition. If it's True, it runs the code inside. Then it goes back to the top and checks again. It repeats this cycle until the condition finally becomes False. The Syntax: count = 1 while count <= 5: print(f"Attempt number {count}") count += 1 # Crucial: changing the condition 2. The Big Debate: "if" vs. "while" Wait, there is no such thing as an "if loop," though many beginners call it that! Here is the difference: The if statement: Checks the condition once. If it's true, it runs the code once and moves on. The while loop: Checks the condition, runs the code, and loops back to check again. It stays there as long as the condition is met. 💡 The Engineering Lens: Think of an if statement as a Gate and a while loop as a Treadmill. You pass the gate once; you stay on the treadmill until the timer runs out. 3. The Danger Zone: The Infinite Loop ♾️ This is the most common bug with while loops. If your condition never becomes False, the loop runs forever. ❌ The Bug: while True: print("Help!") (This will eventually crash your program or freeze your computer). 🛡️ The Fix: Always ensure that something inside the loop changes the variable being checked in the condition (like count += 1 in our first example). 4. Interactive Loops: Using input() while loops are perfect for creating menus or waiting for a specific user action. Example: password = "" while password != "secret123": password = input("Enter the password to continue: ") print("Access Granted!") 💡 The Engineering Lens: In professional software, we often use while loops to listen for data from a server or to keep a game running until the player hits "Quit." #Python #SoftwareEngineering #CodingBasics #Automation #LearnToCode #ProgrammingTips #TechCommunity #PythonDeveloper
Python While Loops: Repetition and Conditionals
More Relevant Posts
-
From print() to GUI - here's what building a Calculator taught me about Python When I started learning Python, I was writing simple functions in the terminal: add(a, b) subtract(a, b) multiply(a, b) divide(a, b) Basic? Yes. But that logic became the foundation of something I'm genuinely proud of. I took those same 4 functions and built a fully functional Calculator GUI using Python and CustomTkinter — no web, no JavaScript, just pure Python. As a Computer Science student at KNUST, this project showed me that classroom concepts become real the moment you build something with them. 𝗪𝗵𝗮𝘁 𝗜 𝗯𝘂𝗶𝗹𝘁: 1. A responsive dark-themed UI with color-coded operator buttons 2. A live display that auto-scales font size for long numbers 3. A calculation history panel (last 10 results) 4. Full keyboard support - type expressions just like a real calculator 5. Edge case handling - division by zero, chained operators, decimal validation 6. Modular architecture separating UI logic from core computation 𝗪𝗵𝗮𝘁 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱: 1. The importance of separating business logic from the presentation layer 2. Event-driven programming — how GUIs respond to user actions in real time 3. Why clean, reusable functions matter even in small projects 4. How to handle edge cases gracefully before they become bugs The jump from terminal scripts to GUI applications felt huge at first. But it showed me that the fundamentals never change - good code is good code, whether it runs in a terminal or a window. Every big project starts with a small function. Keep building. 🚀 #Python #Programming #SoftwareDevelopment #GUI #LearningToCode #TechSkills #ComputerScience #KNUST
To view or add a comment, sign in
-
🚀 Day 61 of #100DaysOfCode 🧩 Problem: Word Break (LeetCode 139) Today’s problem was all about Dynamic Programming + String Matching. 💡 Problem Statement: Given a string "s" and a dictionary of words "wordDict", determine if "s" can be segmented into a space-separated sequence of one or more dictionary words. --- 🔍 Approach: Instead of checking all possible combinations (which is expensive), I used Dynamic Programming: ✔️ Create a DP array where "dp[i]" means: 👉 Can the substring "s[0:i]" be formed using the dictionary? ✔️ Initialize: "dp[0] = True" (empty string is always valid) ✔️ For every index "i", check all "j < i": If "dp[j]" is True AND "s[j:i]" exists in dictionary → mark "dp[i] = True" --- ⚡ Time Complexity: O(n²) ⚡ Space Complexity: O(n) --- 📌 Key Learning: Dynamic Programming helps avoid recomputation by storing results of subproblems. --- 🔥 Consistency is the real game. #DSA #LeetCode #Python #CodingJourney #PlacementPreparation
To view or add a comment, sign in
-
-
Clean code isn’t just about working software. It’s about respect. 🐍✨ If you write Python, you’ve probably heard of PEP 8. But do you follow it religiously? Following the Python Enhancement Proposal (PEP 8) style guide is the difference between writing code that only you can read, and writing code that the entire community can maintain. Here are 3 quick PEP 8 rules that instantly make you look like a pro: 🧹 Indentation: Use 4 spaces per indentation level. No tabs. (Yes, spaces!) 📏 Line Length: Limit all lines to a maximum of 79 characters. 📦 Imports: Always put imports at the top of the file, separated into standard library, third-party, and local imports. Why bother? Because in the real world, code is read far more often than it is written. Make it easy for your teammates (and future you) to understand. Do you use a linter to auto-format your code, or do you prefer to write it manually? Let me know in the comments! 👇 #Python #PEP8 #CodingBestPractices #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
I didn’t just “learn Python” — I forced myself to prove it by working tougher over the past few weeks Instead of jumping from one tutorial to another, I sat down and actually built things. No shortcuts, no skipping — just writing code, breaking it, fixing it, and repeating. So I turned everything into a structured repository: notes + concepts + working programs + mini projects. 📚 What this included: • Core fundamentals (variables, strings, numbers) • Control flow (if-else, operators, logic building) • Loops and iteration (including nested logic) • Functions and arguments • How Python actually runs (interpreter → bytecode → execution) 💻 What I ended up building: • 🔢 A menu-driven calculator • 💰 An interest + tax calculation system • 🔐 A password strength checker • 🎯 A number guessing game • 🎓 A full CLI-based student management system (CRUD) The interesting part? At the start, even small logic felt confusing. By the end, I was comfortably structuring full programs. Not because I “finished a course” — but because I kept writing code until things started making sense. 🔗 Here’s everything I built: [ https://lnkd.in/grknB8p6 ] This is just the beginning. Next step: build something bigger and less comfortable. #Python #Programming #BuildInPublic #CodingJourney #StudentDeveloper #GitHub #LearnToCode #SoftwareDevelopment
To view or add a comment, sign in
-
-
This was my favorite chapter to write. The agent went from helpless to surgical with three plain tools. No RAG, no embeddings — just the Unix philosophy applied to AI.
"Fix the bug in authentication." My agent had no idea which file to open. It can read files. It can edit code. But a 500-file project? It's lost without a map. So I gave it three tools: list_files - shows the project skeleton (just file names and structure) search_codebase - runs git grep to find where "authenticate" lives read_file - opens the exact file, with line numbers The workflow: zoom out (map the project) -> zoom in (search for the keyword) -> read (open the specific file). Three passes. No vector database. No embeddings. Just the same approach you'd use with find and grep. That workflow took the agent from "I don't know where to look" to "the bug is on line 47 of auth.py." https://lnkd.in/gWdFWM4g #Python #AIAgents #DevTools #PurePython
To view or add a comment, sign in
-
Day 29: The Anatomy of a Bug — Three Types of Errors 🐞 In programming, not all "crashes" are created equal. We categorize errors into three levels of severity, ranging from "The computer doesn't understand you" to "The computer does exactly what you said, but you said the wrong thing." 1. Syntax Errors (The "Grammar" Mistake) These happen before the code even starts running. Python’s "Parser" looks at your script and realizes it violates the rules of the language. The Cause: Missing colons :, unclosed parentheses (, or incorrect indentation. The Result: The program won't start at all. 💡 The Engineering Lens: These are the "cheapest" errors to fix. Your code editor (IDE) will usually highlight these with a red squiggly line as you type. 2. Runtime Errors (The "Panic" Mistake) The syntax is perfect, and the program starts running—but then it hits a situation it can't handle. The Cause: Dividing by zero, trying to open a file that doesn't exist, or calling a variable that hasn't been defined yet (NameError). The Result: The program "crashes" in the middle of execution. 💡 The Engineering Lens: We handle these using Exception Handling (try/except). Professional code assumes things will go wrong (like the internet cutting out) and builds "safety nets" to keep the program alive. 3. Semantic Errors (The "Logic" Mistake) These are the most dangerous and difficult to find. The program runs perfectly from start to finish. There are no crashes and no red text. But the output is wrong. The Cause: You used + when you meant -, or your loop stops one item too early. The Result: The program gives you the wrong answer (e.g., a calculator saying $2 + 2 = 22$). 💡 The Engineering Lens: The computer is doing exactly what you told it to do; the "error" is in your logic. We find these using Unit Testing and Debugging tools. If you don't test your code, you might not even know a semantic error exists until a customer reports it. #Python #SoftwareEngineering #Debugging #ProgrammingTips #LearnToCode #TechCommunity #PythonDev #CleanCode #BugHunting
To view or add a comment, sign in
-
I’ve just published my first Python project on GitHub. This is a command-line Contact List application developed to practice core programming concepts such as data structures, input validation, and basic CRUD operations. Key features: • Add, edit, and delete contacts • Search functionality • Automatic ID generation • Duplicate prevention (email/phone) This project is part of my transition into software engineering, and I’ll continue building more applications to strengthen my skills. Repository: https://lnkd.in/g7kFu8PD #Python #GitHub #SoftwareEngineering #Programming #CareerTransition
To view or add a comment, sign in
-
Writing code that works is one thing but designing something that’s easy to extend and doesn’t break as it grows is a different challenge. Lately, I’ve been thinking more about what actually makes object-oriented design effective not just functional. Especially when building systems in Python that need to handle complexity. I built a turn based card game system in Python to focus on that using object oriented programming to managing state, interactions, and edge cases through clean class design. What stood out to me was how much the structure of code impacts its ability to handle complexity. Designing components that interact cleanly and behave correctly across different scenarios made me realise how important good OOP design really is. Through this Python based project, I was able to: - Design a modular class structure to manage system state and interactions - Implement clear separation of responsibilities across components - Handle edge cases and ensure robustness - Build logic that consistently passes all test scenarios This has pushed me to explore object-oriented programming in Python more intentionally, focusing on building systems that are maintainable and scalable. I’ve shared the project on GitHub for anyone interested in trying out themselves: https://lnkd.in/gV2bmvMS #SoftwareEngineering #Python #ObjectOrientedProgramming #StudentProject #Tech
To view or add a comment, sign in
-
🚀 Python Journey — Day 15 | Advanced List Logic with Functions Today I continued practicing functions by solving more advanced list-based logical problems. Problems I solved : • Find second largest number in a list • Find second smallest number in a list • Copy elements from one list to another • Print all prime numbers from a list • Replace all zero values with a given number • Check whether all elements in a list are same • Find frequency of all elements in a list • Flatten a nested list into a single list • Split a list into even and odd lists • Find pairs of elements with a given sum • Remove all odd numbers from a list • Remove all even numbers from a list • Multiply all list elements by a fixed number • Find difference between maximum and minimum values • Check whether a list is empty I implemented these problems using functions, loops, and conditional logic to strengthen my understanding of advanced list manipulation and structured problem solving. Thanks to Rudra Sravan kumar sir for the guidance and continuous support. Learning daily and getting more confident On to Day 16 #Python #PythonDeveloper #LogicBuilding #10000Coders #Coding #LearningJourney #ProblemSolving #CodeEveryDay #KeepLearning
To view or add a comment, sign in
-
Most developers keep learning new frameworks. I focus on eliminating manual work. That mindset changed how I build software. I wrote a new Medium article about 6 Python libraries that became part of my default toolkit tools I genuinely use in every project. Visit my Medium profile to read the full breakdown.
To view or add a comment, sign in
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