🤸 Week 2 of 180 — Python finally has a BRAIN now! 🧠 Last session I learned Lists — how to store data. Today? I learned how to control what Python DOES with that data. 💥 Loops & Control Statements — and this is where programming starts feeling like actual logic. 👇 🤔 Why do we even need this? Without control flow, Python just runs every line top to bottom. Boring. 😴 With control flow, Python can: → Make decisions using if-elif-else → Repeat tasks using for or while → Exit early, skip steps, or do nothing using break, continue, pass These are the backbone of logic in every Python program. 🦴 🧭 Part 1 — if-elif-else (Making Decisions) age = 18 if age >= 18: print("You can vote.") # ✅ this runs elif age >= 16: print("Almost there!") # skipped else: print("You cannot vote.") # skipped if checks the first condition. elif checks the next one if if was False. else is the fallback — runs only when everything above fails. 🛡️ 🔁 Part 2 — for Loop (Iterate over sequences) Use for when you know exactly how many times to loop. names = ["Alice", "Bob", "Charlie"] for name in names: print(name) # Alice # Bob # Charlie Works on lists, strings, dictionaries — anything iterable! 🔄 ⏳ Part 3 — while Loop (Run until condition is False) Use while when you DON'T know how many times to loop. i = 1 while i <= 5: print(i) i += 1 # prints 1 2 3 4 5 ⚠️ Always update your variable inside while — or you'll be stuck in an infinite loop forever. 😂 🎮 Part 4 — break, continue, pass # break → EXIT the loop completely for i in range(10): if i == 5: break # stops at 5, never reaches 6,7,8... # continue → SKIP this step, go to next for i in range(5): if i == 2: continue # skips 2, prints 0,1,3,4 # pass → DO NOTHING (placeholder) for i in range(3): pass # valid empty loop, no error! 🎯 Part 5 — range() + else with Loops # range() — generate number sequences for i in range(1, 6): print(i) # 1 2 3 4 5 # else with loop — runs when loop completes WITHOUT break for i in range(3): print(i) else: print("Loop finished successfully!") # 🎉 That else with loops was a surprise — I didn't know Python could do that! 😲 💡 The Big Mental Model I have now: if-elif-else = Python DECIDING 🤔 for = Python REPEATING a known number of times 🔁 while = Python WAITING until something changes ⏳ break/continue/pass = Python CONTROLLING the flow 🎮 📅 Week 2 / 180 — Loops & Control: DONE! ✅ Grinding through my 6-Month GenAI & Agentic AI Certificate Program 🏛️ IIT Patna Certified while still_learning: keep_going() # this is me right now 😂 💬 Which one confused you more when you started — break or continue? 👇 ♻️ Repost if this made control flow click for you! #Python 🐍 #Loops #ControlFlow #IfElse #ForLoop #WhileLoop #Week2 #GenAI 🤖 #IITPatna 🏛️ #LearningInPublic #100DaysOfCode #PythonBasics #CodingJourney #AgenticAI #NeverStopLearning 🚀 #BuildInPublic
Python Loops & Control Flow: if-elif-else, for, while, break, continue, pass
More Relevant Posts
-
There are multiple data types in Python, and it's pivotal to understand them so that you can build Python skills from the ground up. Here is a cheat sheet that lists the most commonly used types, what they are, and an example of what their output would look like: - String: Text data that is wrapped in quotes (e.g. "Hello World" or 'Hello World') - Integer: Positive or negative whole numbers (e.g. 15, -15) - Float: Positive or negative decimal numbers (e.g. 3.14, -1.5) - Boolean: Used for true or false evaluation (e.g. True or False) - List: Ordered, mutable collection of values held within []. Allows duplicates (e.g. [1,2,2,3]) - Tuple: Ordered, immutable collection of values held within () that cannot be changed after creation. Allows duplicates (e.g. (1,2,2,3)) - Set: Unordered, mutable collection of values held within {}. Values are unique and immutable within the set itself (e.g. {1,2,3}) - Dictionary: Key-value pairs where the key is a unique identifier for the value, held within {} (e.g. {"name":"John","age":25}) The application for the different data types is endless, such as converting a list to a set in order to remove duplicates and store a unique set of values from the original list. For example: og_list = [1,2,2,3,4,4,5] new_set = set(og_list) print(new_set) # Output: {1, 2, 3, 4, 5} Once you are familiar with the different data types, you have a foundation that helps you move on to creating more advanced scripts! #Python #PythonTips #LearnPython #Programming #DataEngineering #DataScience #AnalyticsEngineering
To view or add a comment, sign in
-
Python Variables Explained Simply (With Real Examples) In Python, everything you work with is data. When you create a variable, Python: Creates the data in memory Assigns a reference (variable name) to it Think of a variable as a label stuck on a box. Simple code = age = 25 Here , Age is a variable and 25 is the value assigned to it. Python does not require any type declaration. Because it's type is already determined. age = 25 # integer price = 19.99 # float name = "Alex" # string is_active = True # boolean A simple coding example which defines about user profile by using different datatypes : name = "Rahul" age = 24 height = 5.9 is_student = True print("Name:", name) print("Age:", age) print("Height:", height) print("Student Status:", is_student) Dynamic Typing : As informed earlier ,Python allows changing type dynamically. x = 10 print(type(x)) x = "hello" print(type(x)) Output : <class 'int'> <class 'str'> Because of this flexibility, python is fast for development. Important Concept: Checking Data Type Python provides type().Useful in debugging and validation. age = 22 print(type(age)) output : <class 'int'> #Python #Programming #Coding #LearnToCode #Beginners #TechCareer #SelfLearning
To view or add a comment, sign in
-
🚀 Day 3 of My Data Science Journey — Python Fundamentals: I/O, Formatting & Variables After setting up my complete development environment on Day 2, today’s focus was on diving deeper into Python fundamentals and understanding how things work behind the scenes. 𝐓𝐨𝐩𝐢𝐜𝐬 𝐂𝐨𝐯𝐞𝐫𝐞𝐝: – Input & Output — working with input() and print() functions – Output Formatting — using sep= and end= for better control – String Formatting — f-strings and .format() for clean, readable output – Type Conversion — converting data types using int(), str(), etc. – Number Base Systems — working with binary, octal, and hexadecimal values – Error Handling — understanding common issues like TypeError – Variable Naming — writing clean, readable, and professional code Today’s key learning: Python’s simplicity and powerful built-in functions make coding more efficient and readable. Small concepts like formatting and proper variable naming can significantly improve code quality. Excited to keep building and strengthening my fundamentals step by step. 📊 Read the full breakdown with examples on Medium 👇 https://lnkd.in/dHveMPTz #DataScienceJourney #Python #Learning #Programming #Developers #CareerGrowth
To view or add a comment, sign in
-
I think dictionaries might be the first Python topic that actually feels like organizing real life. 🐍 Day 08 of my #30DaysOfPython journey was all about dictionaries, and this one felt especially useful because it is basically how Python stores meaningful information. A dictionary is an unordered, mutable key-value data type. You use a key to reach a value — simple, but powerful. Today I explored: 1. Creating dictionaries with dict() built-in function and {} 2. Storing different kinds of values like strings, numbers, lists, tuples, sets, and even another dictionary 3. Checking length with len() 4. Accessing values using key name in [] or get() method 5. Adding and modifying key-value pairs 6. Checking whether a key exists using in operator 7. Removing items with pop(key), popitem() (removes the last item), and del 8. Converting dictionary items with items() which returns a dict_item object that contains key-value pairs as tuples 9. Clearing a dictionary with clear() 10. Copying with copy() and avoids mutation 11. Getting all keys with keys() and values with values(). These will return views - dict_keys() and dict_values() What stood out to me today was how dictionaries make data feel searchable instead of just stored. That key-value structure makes them one of the most practical tools in Python when working with real information. One more day, one more topic, one more step toward thinking in Python instead of just reading Python. When did dictionaries finally stop feeling confusing for you — or are they still one of those topics that need a second look? Github Link - https://lnkd.in/ewzDyNyw #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
Day 44 : Python Data Types Today I used the different data types in Python and understood it's usage. Hands-on : - Today I explored the core data types in Python, which are essential for storing and working with different kinds of data. - I started with numeric types like integers and floats, which are used for mathematical operations. -Next, I learned about boolean values (True/False), which are mainly used in conditions and decision-making. - I then worked with strings, which store text data and support various operations like slicing and formatting. - Moving forward, I explored collection data types such as lists, which are ordered and mutable, and tuples, which are ordered but immutable. - I also learned about sets, which store unique values without any specific order. - Finally, I studied dictionaries, which store data in key-value pairs and are extremely useful for structured data representation. Result : - Successfully understood different Python data types and how they are used to store and manage various forms of data. Key Takeaways : - Numeric types (int, float) are used for calculations. - Boolean values help in decision-making and conditional logic. - Strings are used to handle textual data. - Lists are ordered and mutable collections. - Tuples are ordered but immutable. - Sets store unique, unordered values. - Dictionaries use key-value pairs for structured data storage. #Python #Programming #DataAnalytics #LearningJourney #DataTypes #CodingBasics #DataScience #BeginnerPython #AnalyticsSkills
To view or add a comment, sign in
-
-
Any serious performance-critical work involving custom algorithms shouldn't be done in python, and in fact people use alternatives such as C++. But who likes coding in C++, especially for scientific research and prototyping? I've been working on a genomics project in python, and a component requires computing stats for a large number of lists. Simple?—well incredibly slow, even with numpy (written in C, but lots of overheads) and JIT numba (somewhat usable). So I quickly wrote a benchmark in both Python (default, numpy, numba) and Julia (default, SIMD, and even more aggressive SIMD). While the goal here is not providing comprehensive comparison between python and julia, it's a simple case study demonstrating Julia's edge on performance and flexibility. https://lnkd.in/e9sR_KbN
To view or add a comment, sign in
-
📢 Day 2 of my Python series is LIVE on MrCloudBook! 🐍 𝗣𝘆𝘁𝗵𝗼𝗻 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 & 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 — the building blocks that make your variables actually DO something! In Day 1, we covered variables and data types — the nouns of Python. Day 2 is all about the verbs. ✅ Here's what's inside: 🔢 Arithmetic operators — including the 3 that surprise every beginner: //, %, ** 🔍 Comparison operators — and the classic = vs == trap 🧠 Logical operators — and, or, not (with short-circuit evaluation!) ✅ Truthiness — what Python considers True or False 📝 Assignment operators — +=, -=, *= and more 🔤 String operators — +, *, and in 🎯 Operator precedence — so your expressions mean what you think they mean 💼 A complete Invoice Calculator project using every concept from the article If you're starting your Python journey or know someone who is — this one's for you. 🙌 👇 Read it here: https://lnkd.in/gSqznx_T #Python #LearnPython #PythonForBeginners #MrCloudBook #DevOps #100DaysOfCode #Programming #TechCommunity
To view or add a comment, sign in
-
Day 6 of My Data Science Journey — Python Conditionals: if, else, elif & Nested if Today’s focus was on one of the most practical and essential concepts in Python — Conditional Statements. This is where programs start making decisions based on different conditions, bringing logic into real-world applications. After building a strong foundation over the past few days, I applied multiple concepts together to understand how conditionals work in real scenarios. 𝐖𝐡𝐚𝐭 𝐈 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞𝐝: if / else – Handling two outcomes based on conditions (e.g., age check, even/odd, positive/negative) if / elif / else – Managing multiple conditions where Python evaluates the first true case – Practical examples like grade calculation, BMI categories, number system checks . Nested if – Applying multiple layers of conditions for complex logic – Worked on real-world scenarios like driving eligibility, login validation 𝐊𝐞𝐲 𝐈𝐧𝐬𝐢𝐠𝐡𝐭: The real strength of conditionals comes from combining them with previously learned concepts like string methods, type conversion, arithmetic operations, boolean logic. This is where coding starts to feel more practical and powerful. Each day is building on the previous one, making learning more structured and meaningful. Read the full article with detailed examples on Medium 👇 https://lnkd.in/d2TU6vXf #DataScienceJourney #Python #Programming #Learning #Developers
To view or add a comment, sign in
-
📘 **Day 11 – File Handling in Python** Today I learned about **File Handling in Python** 📂 👉 File handling allows us to **create, read, write, and update files**. It helps store data permanently instead of keeping it only in memory. 🔹 **Types of Modes:** * `r` → Read file * `w` → Write (overwrites file) * `a` → Append (adds data) * `x` → Create new file 🔹 **Basic Example:** ```python # Writing to a file file = open("example.txt", "w") file.write("Hello, Python!") file.close() # Reading from a file file = open("example.txt", "r") print(file.read()) file.close() ``` 💡 **Best Practice:** Use `with` statement (auto closes file) ```python with open("example.txt", "r") as file: data = file.read() print(data) ``` ✨ **Key Learning:** File handling is important for saving data like logs, user input, and reports. 🚀 Step by step becoming better in Python! #Day11 #Python #CodingJourney #FileHandling #SkillCourse #DataAnalyst
To view or add a comment, sign in
-
Python has easy ways to make your text, numbers, and dates look clear and professional. Here are 4 tricks you should try: 1. f-Strings :The easiest way to put variables straight into your text. Fast, readable, perfect for quick outputs. name = "Mayar" age = 22 print(f"My name is {name} and I am {age} years old.") 2. Alignment & Width :Keep tables, reports, or lists neat by aligning text and numbers. Left, center, or right—your choice! print("{:<10} | {:^10} | {:>10}".format("Name", "Age", "Score")) print("{:<10} | {:^10} | {:>10}".format("Mayar", 22, 95)) 3. Template Strings :Create reusable text templates and fill in values later. Makes your code cleaner and easier to manage. from string import Template t = Template("Hello $name, your score is $score.") print(t.substitute(name="Mayar", score=95)) 4. Date & Time Formatting :Show dates and times in a clear, readable way. Useful for reports, logs, or messages. from datetime import datetime now = datetime.now() print(f"Date: {now:%d-%m-%Y} Time: {now:%H:%M:%S}") CodeAcademy_om Kulsoom Shoukat Ali Sultan AL-Yahyai #Python #Coding #PythonTips #Developer #LearnPython #TechSkills #CodeBetter #DateTime
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