PYTHON JOURNEY - Day 42 / 50..!! TOPIC – While Loops Today I explored While Loops — a different way to repeat code. Unlike for loops that run a set number of times, a while loop keeps running as long as a specific condition is True. 1. The Basic While Loop You set a condition, and the loop repeats until that condition becomes False. Python count = 1 while count <= 5: print(f"Count is: {count}") count += 1 # Important: This updates the condition! 2. The Infinite Loop (The Trap!) If you forget to update your variable (like count += 1), the loop will never stop. This is called an Infinite Loop. Tip: Press Ctrl + C in your terminal to stop it! 3. Using While Loops for User Input Perfect for when you don't know how many times the user will need to try something. Python password = "" while password != "1234": password = input("Enter password to unlock: ") print("Access Granted!") Why Use While Loops? Dynamic Repetition: Ideal for situations where the ending point depends on user behavior or a random event. Game Loops: Most games use a while loop to keep the game running until the player clicks "Quit." Monitoring: Useful for checking a sensor or a website status until something changes. Mini Task Write a program that: Starts a variable number = 10. Uses a while loop to countdown from 10 to 1. Prints each number and then prints "Blast off! " when the loop finishes. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
Mastering While Loops in Python
More Relevant Posts
-
PYTHON JOURNEY - Day 41 / 50 ...!! TOPIC – For Loops Today I entered the world of Loops! Specifically, the For Loop, which is used to iterate over a sequence (like a list, tuple, or string) and repeat a block of code. 1. Looping Through a List Instead of printing every item manually, a for loop does it in two lines. Python fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits: print(f"I love eating {fruit}!") 2. Using the range() Function The range() function is perfect when you want to run code a specific number of times. Python # This prints numbers 0 to 4 for i in range(5): print(f"Iteration number: {i}") 3. Looping Through a String Since strings are sequences of characters, you can loop through them too! Python name = "PYTHON" for letter in name: print(letter) Why Use For Loops? Automation: Perform the same action on thousands of items instantly. DRY Principle: "Don't Repeat Yourself" — loops keep your code short and clean. Data Processing: Essential for analyzing lists of numbers or text data. Mini Task Write a program that: Creates a list of numbers: [1, 2, 3, 4, 5]. Uses a for loop to calculate the square of each number (number * number). Prints: "The square of <number> is <result>." #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
Why it took nearly 30 years to have no-GIL Python versions? TL;DR: The Single-Thread Tax In the past, every time someone tried to remove the GIL, the standard Python code got 30-50% slower for making refcounting thread safe. How was this solved in Python 3.13+ versions? The move to No-GIL isn't just about deleting the lock. It’s about Biased Reference Counting and Immortal Objects. -> Immortal Objects: Things like True, False and None now have a special status where their reference counter never changes. This means threads don't have to fight over them. So single thread tax is out of question. -> Biased Counting: Python now assumes that the thread that created an object is the one that will use it most. It handles that thread’s counting differently than other(guest) threads. So this finally reached a point where the "Single-Thread Tax" is down to about 5-10%. This approach has real limitations (especially for cross-thread sharing). Will discuss them in next posts. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
🔤 Master These Python String Methods & Level Up Your Code 🚀 Strings are everywhere in Python from user input to data processing. If you know these core string methods, your code instantly becomes cleaner, safer, and more professional. ✨ Must-know methods: • split() --> Break a sentence into words for text analysis • strip() --> Clean extra spaces from user input • join() --> Combine list items into a single string • replace() --> Update or sanitize text values • upper() --> Convert text to uppercase for consistency • lower() --> Normalize text for case-insensitive comparison • isalpha() --> Validate name fields (letters only) • isdigit() --> Check if input contains only numbers • startswith() --> Verify prefixes like country codes or URLs • endswith() --> Validate file extensions (.pdf, .jpg, etc.) • find() --> Locate a word or character inside a string 💡 Why they matter? ✔ Clean messy user input ✔ Validate data effortlessly ✔ Write readable, efficient logic ✔ Avoid common bugs in real projects If you’re learning Python , bookmark this 📌 Keep up the 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞 👍 𝐂𝐨𝐧𝐬𝐢𝐬𝐭𝐞𝐧𝐜𝐲 is the 𝐊𝐞𝐲 in 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠 💯 👇 Comment “Python” if you want a part-2 with real examples! #Python #PythonProgramming #Coding #LearnToCode #Developer #ProgrammingTips #CleanCode
To view or add a comment, sign in
-
-
🧠 Reverse a list | Python Problem Statement Given a list of n elements, reverse the list in place. 📌 Examples Input: n=5 myList = [20,1,10,5,59] Output: [59,5,10,1,20] 🔍 Approach Brute Force Approach 1. Traverse the list and store elements in a temporary list in reverse order 2. Copy the temporary list back to the original list ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) ⚠️ This approach is easy to understand but uses extra space. Optimized Approach (Two-Pointer Technique) 1. Initialize two pointers: left = 0 and right = n − 1 2. Swap elements at left and right 3. Increment left and decrement right 4. Repeat until left < right ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) 🧪 Python Code def reverse(self, arr: list, n: int) -> None: left = 0 right = n-1 while left < right: arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 🧩 Edge Cases (Interview Tip) Empty list → no change Single-element list → already reversed List with duplicate elements → handled naturally #Python #DSA #CodingInterview #InterviewPreparation #CollegeStudents #CampusPlacements #LearningInPublic
To view or add a comment, sign in
-
PYTHON Versus C - Expressiveness versus raw control I have had this debate...C is too much! Situation: I have a variable that stores the value "spaces" I want to convert this to "s p a c e s" In python: print(" ".join("spaces")) In C: (Warning: Don't use in Production) #include <stdio.h> int main() { char text[] = "spaces"; size_t text_len = sizeof(text) - 1; size_t out_len = 2 * text_len - 1; char spaced_text[out_len + 1]; // +1 for trailing null int i = 0, j = 0; for(i = 0; i < out_len; i++) { if(i%2 == 0) { spaced_text[i] = text[j++]; } else { spaced_text[i] = ' '; } } spaced_text[out_len] = '\0'; printf("%s\n", spaced_text); return 0; } After I learnt C - I realized just what it takes to get to " ".join(<string>). Python is just abstracting away a lot of things to make life easy for the programmer. Naturally for those who like to go a level deeper " ".join(<string>) is not satisfying enough... I am sure some of you will relate with this 😊 Have a restful Sunday!
To view or add a comment, sign in
-
Ever wondered why Python sometimes says two equal-looking numbers are not equal? 🤔 Python Code: a = 0.1 + 0.2 b = 0.3 print(a == b) print(round(a, 1) == b) At first glance, 0.1 + 0.2 should be exactly 0.3. But Python works with binary floating-point values, not human-friendly decimals. So instead of storing 0.3, Python internally gets something extremely close to it — but not exactly the same. That tiny difference is enough to make a == b evaluate to False. Rounding brings both values into the same precision range, which is why the second comparison evaluates to True. This is the reason why, in real-world data science and analytics, direct float comparisons are avoided. A safer approach: Copy code Python import math math.isclose(a, b) Key takeaway: Numbers in Python can look equal, behave equal, and still be unequal in memory. #Python #DataScience #ProgrammingInsights #FloatingPoint #TechLearning #CodingConcepts
To view or add a comment, sign in
-
🐍 Python in 60 Seconds — Day 12 Comparisons & Logic Programs make decisions by comparing values. ⚖️ Comparison operators 5 == 5 → True 5 != 3 → True 5 > 3 → True 5 < 3 → False 5 >= 5 → True 5 <= 4 → False Comparisons always return: True or False ⚠️ Beginner trap 5 = 5 → ❌ Error 5 == 5 → ✅ Comparison One = assigns. Two == compare. 🔗 Logical operators True and False → False True or False → True not True → False Used to combine conditions. 🧠 Real example age = 20 age > 18 and age < 30 → True Python reads this almost like English. 📌 Comparison chaining (Python magic ✨) 18 <= age <= 30 → True Yes — this is valid Python 😄 Clean and readable. ⚠️ Another beginner trap True == 1 → True False == 0 → True They’re different types, but behave similarly in comparisons. 🧠 Key idea Comparisons create facts. Logic combines them. 💡 Insight Programs don’t “think” — they evaluate conditions you define. Clear logic = correct behavior. 🔮 Tomorrow if / elif / else — turning logic into decisions 🚦🐍 #Python #LearnPython #Programming #Coding #TechCareers #DataScience #100DaysOfCode
To view or add a comment, sign in
-
-
Dataclasses in Python: ClassVar, InitVar, slots, cached_property power tools with sharp edges ⚠️ I recently walked through this User dataclass and it’s a perfect example of how modern Python (2024/2025) gives us huge power but also demands clear intent. @dataclass(frozen=False, slots=True) class User: ... This single line already tells a story: slots=True → memory-efficient, faster attribute access frozen=False → this is an entity, not a value object (it can change) 🧠 Key lessons hidden in this code 1️⃣ ClassVar is NOT instance state MAX_LOGIN_ATTEMPTS: ClassVar[int] = 5 This: Does NOT appear in __init__ Does NOT affect equality Is shared across all users 👉 Perfect for constants, limits, and rules not object identity. 2️⃣ InitVar is for construction only password_raw: InitVar[str | None] = None This value: Exists only during initialization Is passed to __post_init__ Is never stored on the object 👉 Ideal for passwords, secrets, or temporary setup data. 3️⃣ slots=True means no dynamic attributes Because of this line: _hashed_password: int | None = field(init=False, repr=False) We explicitly declare internal state. Without it, setting _hashed_password would crash at runtime. 👉 With slots, every attribute must be intentional. 4️⃣ cached_property + mutability = responsibility @cached_property def display_name(self): ... This caches the value after first access. But since frozen=False, this is now possible: user.username = "new_name" 👉 Which means your cache can lie if you mutate fields carelessly. Caching + mutable objects = your responsibility. 5️⃣ Why frozen=False matters here If this were frozen=True: __post_init__ mutation would fail cached_property would break You’d need object.__setattr__ #Python #PythonDataclasses #SoftwareEngineering #BackendDevelopment #CleanCode #Architecture #DesignPatterns #PythonTips #SeniorEngineers
To view or add a comment, sign in
-
-
🔍 𝗣𝘆𝘁𝗵𝗼𝗻 𝗧𝗶𝗽: 𝗪𝗵𝘆 𝗬𝗼𝘂 𝗦𝗵𝗼𝘂𝗹𝗱𝗻’𝘁 𝗧𝗲𝘀𝘁 𝗙𝗹𝗼𝗮𝘁𝗶𝗻𝗴 𝗣𝗼𝗶𝗻𝘁 𝗡𝘂𝗺𝗯𝗲𝗿𝘀 𝗳𝗼𝗿 𝗘𝗾𝘂𝗮𝗹𝗶𝘁𝘆 I recently revisited an important lesson every Python developer should know: 𝗙𝗹𝗼𝗮𝘁𝗶𝗻𝗴 𝗽𝗼𝗶𝗻𝘁 𝗻𝘂𝗺𝗯𝗲𝗿𝘀 𝘀𝗵𝗼𝘂𝗹𝗱 𝗻𝗼𝘁 𝗯𝗲 𝘁𝗲𝘀𝘁𝗲𝗱 𝗳𝗼𝗿 𝗲𝗾𝘂𝗮𝗹𝗶𝘁𝘆 𝘂𝘀𝗶𝗻𝗴 ==. Due to the way numbers are represented in binary, certain decimal numbers can’t be stored with perfect accuracy. This means direct equality checks can lead to unexpected results. #python print(0.1 + 0.2 == 0.3) # Output: False Even though mathematically 0.1 + 0.2 equals 0.3, Python returns False due to floating point precision errors. #python print(0.1 * 3 == 0.3) # Output: False Multiplying 0.1 by 3 should give 0.3, but due to floating point representation, Python returns False. This issue can occur with division and more complex calculations as well. ✅ 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗨𝘀𝗲 𝗮 𝗧𝗼𝗹𝗲𝗿𝗮𝗻𝗰𝗲-𝗕𝗮𝘀𝗲𝗱 𝗖𝗼𝗺𝗽𝗮𝗿𝗶𝘀𝗼𝗻 The best practice is to check if numbers are “close enough,” not exactly equal. Python’s math.isclose() is perfect for this: #python import math print(math.isclose(0.1 + 0.2, 0.3)) # Output: True By using this approach, you can avoid subtle bugs and ensure your comparisons are robust. #Python #CodingTips #SoftwareEngineering #CleanCode #Programming #DeveloperTips
To view or add a comment, sign in
-
𝗣𝘆𝘁𝗵𝗼𝗻 𝗶𝘀 𝗹𝗮𝘇𝘆. 𝗔𝗻𝗱 𝘁𝗵𝗮𝘁'𝘀 𝗮 𝗳𝗲𝗮𝘁𝘂𝗿𝗲, 𝗻𝗼𝘁 𝗮 𝗯𝘂𝗴. When Python evaluates `False and something_else`, it doesn't bother checking `something_else`. Why would it? The result is already determined. This is called short-circuit evaluation, and you can use it intentionally: → username = input("Name: ") or "Guest" If the user enters nothing, the empty string is falsy. Python short-circuits and uses "Guest" instead. No if/else. No extra variables. Just clean, readable code. 𝗕𝘂𝘁 𝗵𝗲𝗿𝗲'𝘀 𝘄𝗵𝗲𝗿𝗲 𝗶𝘁 𝗴𝗲𝘁𝘀 𝗽𝗼𝘄𝗲𝗿𝗳𝘂𝗹: → x != 0 and (10 / x) > 5 If x is zero, Python sees `False` and skips the division entirely. No ZeroDivisionError. This pattern lets you write guard clauses that are both elegant and safe. Understanding short-circuit evaluation isn't just about writing clever code. It's about understanding how Python thinks—and making that work for you. I'm writing "Zero to AI Engineer: Python Foundations" in public. Follow along on Substack for behind-the-scenes updates and excerpts (link in comments). #Python #Programming #AIEngineering #TechCareers #LearnToCode
To view or add a comment, sign in
More from this author
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