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
Python For Loops: Automate Code with Loops
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
I Built A Movie Recommendation System Using Python. 🎬 A application that suggests movies a user might enjoy based on their past preferences, using real-world rating data from the Movie Lens dataset. 💻 What it does : ✦ Uses historical user–movie ratings (no real-time users) ✦Identifies movies a user liked (ratings ≥ 3.5) ✦Finds similar movies based on other users’ rating patterns ✦Recommends unseen movies ranked by relevance How it works: ▪️Movie Lens data is loaded into Pandas DataFrames ▪️A user is selected directly from the dataset ▪️Highly rated movies are treated as user preferences ▪️Similarity is computed using collaborative filtering logic ▪️Recommendations are generated and ranked (not random) ▪️Results are displayed through a simple app interface What I learned: Working with real-world data gave me a deeper understanding of how recommendation systems work behind the scenes. From data preprocessing to implementing collaborative filtering logic, this project strengthened my skills in Python, data analysis, and machine learning concepts. Check it out here: https://lnkd.in/gWHs7fMZ ✨ #DataScience #MachineLearning #Python #Projects #CollaborativeFiltering #DataAnalysis
To view or add a comment, sign in
-
-
💥Day 15 of the Python Journey 💥 Today more deep down into while loop and match function: exploring how real-world systems handle constant input and simple logics in services we use daily. By combining a while loop with Python's modern match-case statement, get a system that is both persistent and incredibly clean: Example: Restaurant Ordering System ✅While loop: keeps the menu running until 'exit' ✅Match: handles known choices without messy if-elifs order = "" while order != "exit": order = input("Add to cart (pizza/burger/exit): ").lower() match order: case "pizza": print("🍕 Pizza added to cart!") case "burger": print("🍔 Burger added to cart!") case "exit": print("✅ Order completed. Enjoy your meal!") case _: print("⚠️ Item not available. Try again.") ⚡Ker Learnings: 📍The while loop represents the "session"—it waits until the condition fails. 📍The match statement provides a declarative way to handle fixed options. 📍Match is more readable and efficient than traditional if-elif chains for structured data. Coding is so much more intuitive when you map it to everyday experiences. For those learning Python: Do you prefer using match-case or the classic if-elif-else blocks? Let’s discuss! 👇 #Python #CodingJourney #CleanCode #ProgrammingTips #DataAnalyst #Analyst #AnalyticsJourney #LearnToCode2025
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
-
-
Power of Generators in Python:- When dealing with large datasets, logs, or streams, loading everything into memory is expensive and slow. Generators solve this by producing values on demand, one at a time, as you iterate. 🔹 Real definition (Generators in Python):- A generator in Python is a function or expression that returns an iterator and yields values one-by-one using the yield keyword instead of return. The code inside a generator pauses at each yield, remembers its state, and resumes from there when the next value is requested (for example, in a for loop or with next()). >>Image explanation (for your graphic):- Design a simple, clear image that explains generators visually: >>Visual idea: >Show a water tap connected to a big water tank labeled “data”. >Water drops coming out one-by-one from the tap are labeled yield value, and the whole tap is labeled “generator function”. >>Concept on the image: >Tank = all possible data >Tap = generator (controls flow) >Drops = values produced lazily, only when needed >>Caption text on image: “Generators in Python: produce one value at a time using yield, saving memory and improving performance.” You can add a small code snippet on the side of the image: def gen(): for i in range(5): yield i >>Key advantages of generators:- >Memory efficient: No need to store the entire sequence in memory; values are generated on-the-fly, which is ideal for large files, logs, or big ranges. >Lazy evaluation: Values are computed only when requested, reducing unnecessary work and improving performance. >Easy to write iterators: Generators create iterators without writing __iter__() and __next__() manually, making code cleaner and more Pythonic. >Great for pipelines: Multiple generators can be chained to build efficient data-processing pipelines step by step (filtering, transforming, mapping, etc.). #Python #Generators #PythonTips #PythonDeveloper #Programming #Coding #SoftwareDevelopment #LearnPython #DataProcessing #CleanCode
To view or add a comment, sign in
-
-
List in Python: Lists are collection of ordered and mutable data. Here are some of the list programs. 1) Program to swap first and fourth element of the List a= ["Ram","Mohan","Krish","Rita"] print(a) a[0],a[3]=a[3],a[0] print(a) 2) Program to add a value a second position in the list a=["Ram","Mohan","Krish","Rita"] print(a) a.insert(1,"Ganesh") == (Here the first value of the list is indexed as 0 hence to add the value a the second place 1 is used) ====================================== a= [13,7,12,10] 1) Program to get the largest and smallest value from the list a.sort() print(a) print("The Largest value in the list is:", a[-1]) print("The Smallest value in the list is:", a[0]) Note: Here once the list is sorted the first value which is at 0 index will always be the smallest and last value at -1 index will always be the highest value.
To view or add a comment, sign in
-
🐍 𝐏𝐲𝐭𝐡𝐨𝐧 𝐌𝐚𝐳𝐞 Recently, I shared a Python poll question that looks simple at first glance… But once you step inside, finding the exit isn’t that easy. Let’s take a look at the question: L1 = [1, 2, 3, 4, 5, 6] L2 = [a for a in L1 if a % 2] print(*L2, sep=", ") What do you think the output will be? a) 1,2,3,4,5,6 b) 2,4,6 c) 1,3,5 d) It raises an error This poll question points to a small but critical detail in Python that we often overlook without realizing it. 📖 I shared the background of the poll, why this question is so confusing, and a detailed evaluation in my Medium article. 👉 To find your way out of the Python Maze: https://shorten.ly/jD9j 👉 Our Poll Link : https://lnkd.in/dJ_TgXe8 💬 Answer it first, then read the article. Did you find the right path right away? 👇 Shared by İzzet ÖZDEMİR #PythonMaze #Python #DataScience #MachineLearning #Programming #Learning #CodeThinking
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
-
🚀 From String Splits to Structured Data: A Quick Python Evolution Ever watched a simple Python script evolve? 😄 Started with extracting first names from a list: names = ["Charles Oladimeji", "Ken Collins"] fname = [] for i in names: fname.append(i.split()[0]) # Result: ['Charles', 'Ken'] Then flipped to last names: fname.append(i.split()[1]) # Result: ['Oladimeji', 'Collins'] Finally transformed it into clean, structured dictionaries: names = ["Charles Oladimeji", "Ken Collins", "John Smith"] fname = [] for i in names: parts = i.split() fname.append({"first": parts[0], "last": parts[1]}) # Result: [{'first': 'Charles', 'last': 'Oladimeji'}, ...] Why I love this progression: 1. Shows how small tweaks solve different problems 2. Demonstrates data structure thinking (list → list of dicts) 3. Real-world applicable for data cleaning/API responses 4. Sometimes the most satisfying code journeys start with a simple .split()! #DataEngineer #Python #Coding #DataTransformation #Programming
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