🐍 Python For Loops (Iteration) 🔄 For loops are used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. They let you execute a block of code repeatedly for each item. 👉 They are essential for automating tasks and processing collections of data efficiently. 🔹 1. What is a For Loop? A for loop executes a set of statements, once for each item in a collection. Example: for character in "Python": print(character) Output: P y t h o n 🔹 2. Looping Through a List This is one of the most common uses: going through each item in a list. Syntax: for item in list_name: # code to execute for each item Example: fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}.") Output: I like apple. I like banana. I like cherry. 🔹 3. The range() Function The range() function generates a sequence of numbers, often used to loop a specific number of times. • range(stop): Numbers from 0 up to (but not including) stop. • range(start, stop): Numbers from start up to (not including) stop. • range(start, stop, step): Numbers from start up to stop, increasing by step. Example: for i in range(3): # Loop 3 times (0, 1, 2) print(f"Iteration {i}") Output: Iteration 0 Iteration 1 Iteration 2 🔹 4. break and continue Statements • break: Stops the loop completely, even if the iterable hasn't finished. • continue: Skips the rest of the current iteration and moves to the next. Example (break): for number in range(1, 6): if number == 4: break # Stop when number is 4 print(number) Output: 1 2 3 Example (continue): for item in ["A", "B", "C", "D"]: if item == "C": continue # Skip 'C' print(item) Output: A B D 🎯 Today's Goal(What you should do) ✔️ Understand what for loops are ✔️ Iterate over lists, strings, and ranges (using your Python editor) ✔️ Use break and continue to control loop flow (using your Python editor)
Python For Loops: Iteration and Control Flow
More Relevant Posts
-
You might want to take a look at this, Everybody says NumPy is faster than Python List. But, How fast ?? Well I looked into it !! So, here is the overhead of every value you use in Python. Let's say you use a value 42. Here is the detailed overhead. ob_refcnt - 8 bytes (For garbage collection, if reference count is zero, then python just deletes it from RAM) ob_type - 8 bytes (For storing what datatype that value belongs to, here that's integer) ob_digit - 8 bytes (For the actual value - 42). Therefore, 24 bytes for each value. Let's take it a step further. Say you have a 4 values to store just [1, 2, 3, 4] and Let's compare Python list vs NumPy array. Python List : Stores Pointers not the actual values and Hence, you need a list of pointers first, each pointer in the "pointer list" points to the actual value that is scattered across different locations of RAM. So, in-order to store 4 elements. 4 x 8 = 32 (pointer list) 4 x 24 = 96 (actual values) Therefore, 32 + 96 = 128 Bytes. NumPy arrays : It's contiguous and also homogeneous. Also, we don't have pointers model. Here we store actual values next to each other. Thus, giving us a easy traversal using strides. 4 x 8 = 32 Bytes. NumPy can store raw values directly because it enforces a single dtype. Since every element is the same size, it can locate any element using simple math (base + index × itemsize) instead of pointers. Python lists allow mixed types and that's exactly what forces the pointer model. Note: I am only comparing the storage models here. Both Python lists and NumPy arrays have their own object overhead which I've intentionally left out to keep the comparison clean. Apart from storage models. There is another reason why NumPy is so powerful in numerical computations and that is vectorization Vectorization in NumPy : When you do np.sum(a), NumPy runs optimized C code across the entire array in one shot no Python interpreter involved. A Python loop hits interpreter overhead on every single element. That's the real reason NumPy can be 10-100x faster for numerical operations. There is reason why this guy is named as "Numerical Python" !!
To view or add a comment, sign in
-
🚀Today I explored another important concept in Python — Strings 💻 🔹 What is a String? A string is a sequence of characters used to store text data. Anything written inside quotes (' ' or " ") is considered a string in Python. 🔹 How Strings Work: 1️⃣ Each character has a position (index) 2️⃣ We can access characters using indexing 3️⃣ We can extract parts of a string using slicing 4️⃣ We can modify output using built-in methods 👉 Flow: Text → Access/Manipulate → Output 🔹 Operations I explored: ✔️ Indexing Accessing individual characters using position ✔️ Slicing Extracting a part of the string ✔️ String Methods Using built-in functions like upper(), lower(), replace() 🔹 Example 1: Indexing & Slicing text = "Python" print(text[0]) # P print(text[-1]) # n print(text[0:4]) # Pyth 🔹 Example 2: String Methods msg = "hello world" print(msg.upper()) print(msg.replace("world", "Python")) 🔹 Key Concepts I Learned: ✔️ Indexing (positive & negative) ✔️ Slicing ✔️ Built-in string methods ✔️ Immutability (strings cannot be changed directly) 🔹 Why Strings are Important: 💡 Used in user input 💡 Data processing 💡 Text manipulation in real-world applications 🔹 Real-life understanding: Strings are everywhere — from usernames and passwords to messages and data handling in applications Learning step by step and gaining deeper understanding every day 🚀 #Python #CodingJourney #Strings #Programming
To view or add a comment, sign in
-
-
✅ *Python Basics: Part-4* *Functions in Python* 🧩⚙️ 🎯 *What is a Function?* A function is a reusable block of code that performs a specific task. 🔹 *1. Defining a Function* Use the `def` keyword: ```python def greet(name): print(f"Hello, {name}!") ``` 🔹 *2. Calling a Function* ```python greet("Alice") ``` 🔹 *3. Return Statement* Functions can return a value using `return`: ```python def add(a, b): return a + b result = add(3, 5) print(result) # Output: 8 ``` 🔹 *4. Default Parameters* You can set default values for parameters: ```python def greet(name="Guest"): print(f"Hello, {name}") ``` 🔹 *5. Keyword Arguments* Arguments can be passed by name: ```python def info(name, age): print(f"{name} is {age} years old") info(age=25, name="Bob") ``` 🔹 *6. Variable-Length Arguments* - `*args`: Multiple positional args - `**kwargs`: Multiple keyword args ```python def show_args(*args): print(args) def show_kwargs(**kwargs): print(kwargs) ``` 💬 *Double Tap ❤️ for Part-5!*
To view or add a comment, sign in
-
Python: 05 🐍 Python Iterables: Diving Deeper 🚀 We'll work on different complex types (range, list etc.) and strings iteration. We've already known the for loops, now let's dive into deeper and know what is range function returns. 🔍 We will use a built in 'type' function to get the type of an object. 🛠️ For example: type(5) .. it will return <class 'int'>; that means number 5 is an integer value 🔢 type(range(5)) .. it will return <class 'range'>; that means we get the value from a range function that means its an object of type range! 🧊 Primitive vs. Complex Types 💡 In python we have primitive types like numbers, strings, Booleans. We also have so many complex types, 'range' is one of those complex types. So interesting concept of range is, it is iterable which means we can iterate over it or use it in a for loop. That is why we can write code like this: for x in range(3): Here x can hold number in the range in each iteration. 🔄 Result: 1 2 3 Strings are also iterable! 🧵 For example: for x in "python": print(x) It will return: ✨ p ✨ y ✨ t ✨ h ✨ o ✨ n Which means x will hold one character from the string in each iteration. 🔡 List Iteration 📋: for x in [1, 2, 3, 4,..,n]: print(x) It will return: 1 2 3 4 ... ... ... nth X will hold one object from the list in each iteration. 🎯 #PythonProgramming #PythonDeveloper #Coding #python #iterator #DataScience #pythondeveloper #programmer
To view or add a comment, sign in
-
-
🐍 What is Polymorphism in Python? Most people hear this term and think it’s complex… But it’s actually one of the most powerful and practical concepts in OOP. 💡 Simple Meaning 👉 Polymorphism = “Many Forms” . It means: ➡️ The same method or function can behave differently depending on the object ⚙️ How It Works in Python In Python, polymorphism is mainly achieved using: ✔ Method Overriding (Runtime Polymorphism) ✔ Duck Typing (Python’s flexible behavior) ✔ Operator Overloading (like + working with different types) . 🧠 Real Example Imagine this: Dog 🐶 → “Woof” Cat 🐱 → “Meow” Both use the same method: speak() 👉 But output is different based on the object . 💻 Code Example 𝒄𝒍𝒂𝒔𝒔 𝑨𝒏𝒊𝒎𝒂𝒍: 𝒅𝒆𝒇 𝒔𝒑𝒆𝒂𝒌(𝒔𝒆𝒍𝒇): 𝒑𝒂𝒔𝒔 𝒄𝒍𝒂𝒔𝒔 𝑫𝒐𝒈(𝑨𝒏𝒊𝒎𝒂𝒍): 𝒅𝒆𝒇 𝒔𝒑𝒆𝒂𝒌(𝒔𝒆𝒍𝒇): 𝒓𝒆𝒕𝒖𝒓𝒏 "𝑾𝒐𝒐𝒇" 𝒄𝒍𝒂𝒔𝒔 𝑪𝒂𝒕(𝑨𝒏𝒊𝒎𝒂𝒍): 𝒅𝒆𝒇 𝒔𝒑𝒆𝒂𝒌(𝒔𝒆𝒍𝒇): 𝒓𝒆𝒕𝒖𝒓𝒏 "𝑴𝒆𝒐𝒘" 𝒂𝒏𝒊𝒎𝒂𝒍𝒔 = [𝑫𝒐𝒈(), 𝑪𝒂𝒕()] 𝒇𝒐𝒓 𝒂𝒏𝒊𝒎𝒂𝒍 𝒊𝒏 𝒂𝒏𝒊𝒎𝒂𝒍𝒔: 𝒑𝒓𝒊𝒏𝒕(𝒂𝒏𝒊𝒎𝒂𝒍.𝒔𝒑𝒆𝒂𝒌()) . 👉 Same method → different behavior 🔥 Why It’s Important ✔ Improves code reusability ✔ Makes code flexible & scalable ✔ Reduces complexity ✔ Helps write clean OOP design . ⚠️ Important Note 👉 Python focuses more on method overriding, not traditional overloading like Java . 🎯 Interview Gold Answer “Polymorphism in Python refers to the ability of a method or function to take multiple forms. It allows the same method name to behave differently based on the object, commonly achieved through method overriding and duck typing.” . 💬 Engagement 👉 Can you think of a real-world example of polymorphism? Comment below 👇 . 👉 Comment “PYTHON” if you want more interview questions like this 🚀 . . #Python #PythonProgramming #OOP #Polymorphism #CodingInterview #LearnPython #Developers #SoftwareEngineering #Programming #TechCareers #InterviewPreparation #100DaysOfCode #CodeNewbie
To view or add a comment, sign in
-
-
Day 16 / 30 - while Loops in Python What is a while Loop? A while loop keeps running its block of code as long as a condition is True. Unlike a for loop which runs a fixed number of times, a while loop runs an unknown number of times, it stops only when the condition becomes False. Perfect for situations where you don't know in advance how many repetitions you'll need. Syntax Breakdown while condition: # runs as long as condition is True # must update something to eventually make condition False while --> checks the condition before every single run condition --> any expression that evaluates to True or False How It Works, step by step Python checks the condition at the top of the loop If True --> it runs the indented block of code Goes back to the top and checks the condition again Keeps repeating until the condition becomes False When False --> exits the loop and continues the program for Loop vs while Loop for loop 1. Use when you know how many times to repeat 2. Looping over a list, range, sequence while loop 1. Use when you don't know how many times 2. Keep going until a condition changes The Infinite Loop -Most Common Mistake If your condition never becomes False, the loop runs forever, freezing your program. Always make sure something inside your loop changes the condition like incrementing a counter or taking user input so the loop can eventually stop. break and continue break - stops the loop immediately, exits even if the condition is still True continue → skips the current iteration and jumps back to the condition check Both break and continue work in for and while loops. Code Example # Count from 1 to 5 count = 1 while count <= 5: print("Count: " + str(count)) count = count + 1 # break — stop early number = 0 while number < 10: if number == 5: break # stops loop at 5 print(number) number += 1 Key Learnings ☑ A while loop runs as long as its condition is True , checks before every iteration ☑ Always update something inside the loop, counter, input, or flag or you'll get an infinite loop ☑ break exits the loop immediately when a condition is met ☑ continue skips the current iteration and jumps back to the condition check ☑ Use for when you know the count — use while when you don't Why It Matters While loops power real systems — PIN verification, login retry limits, game loops, servers waiting for requests. Anywhere your program needs to wait or keep trying until something changes, a while loop is the answer. My Takeaway A for loop is like a to-do list — you know how many items there are. A while loop is like waiting for a bus — you keep waiting until it arrives. Different tools, different situations. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
Episode 13 of What I Can Do with Python. Have you ever tried sorting a dataset that contains a mix of numbers and letters, only to realize Excel treats the values as text? Here is a relatable example: "12.4kg, 9kg, 45.4kg, 102kg" If you sort that column in ascending order in Excel, "9kg" will not come first. In fact, "102kg" may appear before smaller values because Excel is sorting the entries as text, not as numbers. That is not a bug. It is just how text-based sorting works internally. In this episode, I worked on solving that limitation. I built a Python-powered user-defined function for Excel that performs natural sorting. Instead of limiting it to a single column like Excel’s "SORT" function, I designed it more like a "SORTEDBY" function that supports multiple columns and custom sort directions. I named the function "natural_sort_by". It takes: one required positional argument: the data to be sorted additional arbitrary positional arguments that define the column index and sort direction The column index starts from 1 to make it more intuitive for Excel users. For sort direction, I used: "1" for ascending "-1" for descending By default, null values are pushed to the end. I also included proper error handling to help users quickly spot and correct mistakes. Behind the scenes, this project involved a lot of data manipulation with pandas, the "natsort" module for natural sorting logic, error handling, and xlwings as the bridge back to Excel. This is another example of how Python can help extend Excel beyond its default capabilities. Does this sound like a problem you have encountered when sorting data? A demo video showing how it works is attached to this post. See you in Episode 14
To view or add a comment, sign in
-
FastAPI + No-GIL Python might be one of the most important backend shifts this year Most of the conversation in AI has been about models getting faster. But something equally important is happening at the runtime level. With FastAPI 0.136.0, support for Python’s free-threaded (No-GIL) builds is now becoming practical to experiment with. I wanted to understand what this actually means in a real API scenario. So I ran a simple benchmark: - Python 3.12 (with GIL) - Python 3.13 free-threaded build (No-GIL) Same FastAPI app Same endpoints No code changes For CPU-bound workloads, I saw up to ~8x improvement. This isn’t surprising when you think about it. For years, the Global Interpreter Lock has limited Python’s ability to fully use multiple cores in a single process. Threads never really meant parallel execution for CPU-heavy tasks. Most of us worked around it using multiprocessing, task queues, or by adding more infrastructure. No-GIL changes that model. Now threads can actually run in parallel across cores, which means CPU-heavy APIs can scale more naturally without increasing system complexity. Where this becomes especially relevant: - ML inference APIs - Data processing pipelines - Feature engineering workloads - Real-time analytics backends That said, there are some important caveats: - Python 3.13’s free-threaded mode is still experimental - Not all libraries are thread-safe yet - The ecosystem will take time to stabilize So this is not a “move everything to No-GIL today” moment. But it is a strong signal of where Python is heading. For a long time, the trade-off was clear: Python was easy to use, but not ideal for CPU-bound parallelism. That trade-off may not hold for much longer. Curious to hear how others are thinking about this. Are you planning to experiment with No-GIL Python, or waiting for the ecosystem to mature?
To view or add a comment, sign in
-
-
How My Python Brain Almost Broke My Rust Code🐍🦀 "I typed return, added a semicolon, and Rust looked at me like I’d just tried to put ketchup on a five-star steak." Coming from Python, we’re treated to a world where functions are like polite requests: "Please do this, and return this value when you're done." It’s explicit. It’s comfortable. It’s what we know. But then I met Rust. I tried to write a simple area function and my Python instincts screamed: “Declare the variables! Use the keyword! End the line!” The result? A syntax error that felt like a personal intervention. ## Under the Hood: The "Semicolon" Secret 🤐 In Python, almost everything is a statement. A statement is a command—it does something. In Rust, the magic lies in Expressions. With a semicolon (;): You’ve created a Statement. It performs an action, returns "unit" (), and effectively "kills" the value's journey. Without a semicolon: You’ve created an Expression. The value is "live," and because it’s the last thing in the block, Rust "yields" it upward to the function caller. You may ask? Why does Rust hate my return 🤷? It doesn't! You can use return, but idiomatic Rust treats the last expression as the "final result" of the block. Think of a Python function as a vending machine (you have to press a button to get the result out). Think of a Rust function as a waterfall (the value naturally flows out the bottom unless you put a dam—a semicolon—in its way). I wanna spoil your evening dear python Devs who are transitioning 🤣: 1. Stop declaring "Return variables": You don't need result = x * y. Just let x * y be the last line. 2. The Semicolon is a Wall: If you want a value to leave a function, don't block it with a ;. 3. Types are Friends: While Python guesses what you’re returning, Rust demands you sign a contract by declaring the return type before you even type the type the logic 🫣 eg.(-> i32) . It feels strict and very manual, but it’s actually Rust’s way of promising your code won't crash at 3 AM 😂. Conclusion: Transitioning from Python to Rust isn't just about learning new syntax; it’s about moving from a "Command" mindset to a "Flow" mindset. Python tells the computer what to do; Rust describes how data should transform brick by brick. Ditch the semicolon, ditch the indentation,embrace the expression, and let your code flow! 🦀✨ #RustLang #Python #CodingHumor #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
Python: 06 🐍 Python Tip: Master the input() Function! Ever wondered how to make your Python programs interactive? It all starts with taking input from the user! ⌨️ 1) How to capture input? -To get data from a user, we have to use the input() function. To see it in action, you need to write in the terminal using: '$ python3 app.py' 2) The "Type" Trap 🔍 -By default, Python is a bit picky. If you want to know the type of our functions, You can verify this using the type() function: Python code: x = input("x: ") print(type(x)) Output: <class 'str'> — This means 'x' is a string! 3) Converting Types (Type Casting) 🛠️ If you want to do math, you have to convert that string into an integer. Let's take a look at this example- Python code: x = input("x: ") y = int(x) + 4 # Converting x to an integer so we can add 4! [Why do this? Without int(), here we called int() function to detect the input from the user, otherwise Python tries to do "x" + 4. Since you can't add text to a number, your code would crash! 💥] print(f"x is: {x}, y is {y}") The Result 🚀: If you input 4, the output will be: ✅ x is: 4, y is: 8 Happy coding! 💻✨ #Python #CodingTips #Programming101 #LearnPython #SoftwareDevelopment
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