🚀 Day 22 /30 📝Hollow Patterns #30DaysOfPython Today I practiced Hollow Pattern Programming using Python. I learned how to print hollow shapes by using conditions inside nested loops. This helped me understand how logical conditions ("if" statements) control pattern boundaries. ⭐ 1️⃣ Hollow Square Pattern Example Output: * * * * * * * * * * * * * * * * 💻 Python Code: n = 5 for i in range(1, n+1): for j in range(1, n+1): if i == 1 or i == n or j == 1 or j == n: print("*", end=" ") else: print(" ", end=" ") print() ---------------------------------------------------------------------- ⭐ 2️⃣ Hollow Right Triangle Example Output: * * * * * * * * * * * * 💻 Python Code: n = 5 for i in range(1, n+1): for j in range(1, i+1): if j == 1 or j == i or i == n: print("*", end=" ") else: print(" ", end=" ") print() ---------------------------------------------------------------------- ⭐ 3️⃣ Hollow Pyramid Pattern Example Output: * * * * * * * * * * * * 💻 Python Code: n = 5 for i in range(1, n+1): print(" "*(n-i), end="") for j in range(1, i+1): if j == 1 or j == i or i == n: print("* ", end="") else: print(" ", end="") print() ---------------------------------------------------------------------- 📚 What I Learned Today ✔ Creating hollow patterns using conditions ✔ Using "i" and "j" positions to control pattern edges ✔ Understanding boundary logic in pattern programming ✔ Improving problem-solving skills with nested loops ✔ Combining loops and conditions effectively ---------------------------------------------------------------------- 💡 Key Takeaway Hollow patterns are a great way to practice conditional logic and nested loops, which are very important for improving programming skills. #Day22✅ Step by step, my Python logic building is getting stronger 🚀 #Python #30DaysOfPython #CodingJourney #PatternProgramming #LearningDaily
30 Days of Python: Hollow Patterns with Python Programming
More Relevant Posts
-
🐍 Python Practice Progress ( 21 out of 50 question solved) Here are the problems I recently solved: ✅ Count even and odd numbers in a list ✅ Reverse a list without using reverse() ✅ Insert the third largest number at the second last position in a list. ✅ Find the sum of all elements in a list ✅ Merge two lists ✅ Find common elements between two lists ✅ Sort a list without using sort() Working through these exercises helped reinforce concepts like: • loops and indexing • list operations • conditional logic • problem-solving without relying on built-in shortcuts Sometimes going back to the basics is the best way to build stronger foundations. Day 3 ------------------- Count even and odd numbers in a list. try: Num1=[1,2,3,4,5,6,7,8,9,9,88] even=0 odd=0 for i in Num1: if i%2==0: even=even+1 elif i%2!=0: odd=odd+1 print("even are ",even) print("odd are ", odd) except ValueError: print("Some error occured.") Reverse a list without using reverse(). list1=[1,2,3,4,5,6,7] rev_list=[] rev_list=list1[::-1] print(rev_list) # or try: list1=[1,2,3,4,5,6,7] rev_list=[] for i in list1: rev_list.insert(0,i) print(rev_list) except ValueError: print("error occured.") or try: list1=[1,2,3,4,5,6,7] rev_list=[] for i in range(len(list1)-1,-1,-1): rev_list.append(list1[i]) print(rev_list) except ValueError: print("error occured.") Insert third largest number in a list and add it at second last position. try: list1=[1,2,76,84,989,23,4,5,666,7,788,8,9897] third_largest=sorted(list1)[-3] list1.insert(len(list1)-1,third_largest) print(list1) Find the sum of all elements in a list. try: list1=[2,4,5,4,44,33,65,898,90] s=0 for i in list1: s=s+i print(s) except ValueError: print("error occured") Merge two lists. try: list1=[2,3,4,4,5,6,7] list2=[99,8,0,4,2,1] c=list1+list2 print(c) except ValueError: print("error occured") using extend method try: list1=[2,3,4,4,5,6,7] list2=[99,8,0,4,2,1] list1.extend(list2) print(list1) except ValueError: print("error occured") # Find common elements between two lists. try: list1=[2,3,4,4,5,6,7] list2=[99,8,0,4,2,1] list3=set(list1).intersection(set(list2)) print(list(list3)) except ValueError: print("error occured") Sort a list without using sort(). try: list2=[99,8,0,4,2,1] for i in range(len(list2)): for j in range(len(list2)-1): if list2[j]>list2[j+1]: list2[j],list2[j+1]=list2[j+1],list2[j] ---i am using bubble sort logic print(list2) except ValueError: print("error occured") #Python #CodingPractice #PythonProgramming #ProblemSolving #DataScienceJourney
To view or add a comment, sign in
-
🐍 Did you know? In Python, there’s a layer that sits above your classes, one that controls how classes themselves are created and behave. It’s called a metaclass. What exactly is a metaclass? - Objects are instances of classes - Classes are instances of metaclasses By default, Python uses type as the metaclass for all classes. But you can create your own metaclasses to customize how classes are defined and constructed. Example 1: Auto-injecting methods The metaclass automatically adds a greet method to the class. class Meta(type): def __new__(cls, name, bases, dct): def greet(self): return f"Hello from {name}!" dct["greet"] = greet return super().__new__(cls, name, bases, dct) class Person(metaclass=Meta): def __init__(self, name): self.name = name p = Person("Olivia") print(p.greet()) # Hello from Person! Example 2: Enforcing class rules Metaclasses can enforce constraints when a class is created. class MainClass(type): def __new__(cls, name, bases, attrs): if "foo" in attrs and "bar" in attrs: raise TypeError(f"Class {name} cannot define both foo and bar") return super().__new__(cls, name, bases, attrs) class SubClass(metaclass=MainClass): foo = 42 # bar = 34 # This would raise an error Example 3: Dynamic class generation class AnimalType: def __init__(self, ftype, items): self.ftype = ftype self.items = items def sub_animal(ftype): class_name = ftype.capitalize() def __init__(self, items): super(self.__class__, self).__init__(ftype, items) globals()[class_name] = type(class_name, (AnimalType,), {"__init__": __init__}) # create classes dynamically [sub_animal(a) for a in ["mammal", "bird"]] Metaclasses are a powerful (and sometimes mysterious) part of Python. Most developers rarely need them, but they are used in frameworks like Django. #Python #Metaclasses #SoftwareEngineering #BackendDevelopment #CleanCode #PythonTips
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
-
-
🔹 Understanding Python Memory One important concept is how Python stores data in memory. When we write: a = 10 Most people think variable a stores the value 10. But in reality, Python variables store references to objects. Here 10 is the object, and a simply points to that object in memory. Multiple variables can reference the same object: a = 10 b = a Both a and b point to the same object in memory. 🔹 Mutable vs Immutable Objects Understanding this difference is very important in backend development. Immutable objects (cannot change after creation) ✴️ int ✴️ float ✴️ bool ✴️ str ✴️ tuple Example: a = 10 a = 20 Python creates a new object instead of modifying the old one. Mutable objects (can change after creation) ✴️ list ✴️ dictionary ✴️ set ✴️ custom classes Example: a = [1, 2] b = a b.append(3) Now a becomes: [1, 2, 3] Because both variables point to the same mutable object. This is a very common source of bugs in backend systems when shared state is not handled properly. 🔹 Generators in Python Generators are extremely useful for handling large data efficiently. A generator produces values one at a time instead of loading everything into memory. Example: def numbers(): for i in range(5): yield i for n in numbers(): print(n) Here, values are generated only when needed. 💡 Why generators are important in backend systems Generators are widely used for: ✴️ Streaming large API responses ✴️ Processing logs ✴️ Reading millions of database rows ✴️ Background workers ✴️ Data pipelines ✴️ Async streaming They help save memory and improve performance, especially when working with large datasets. #Python #BackendEngineering #SoftwareDevelopment
To view or add a comment, sign in
-
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 Concept: sorted() with key Sort smarter, not harder 😎 ❌ Traditional Way students = [ {"name": "Alice", "marks": 85}, {"name": "Bob", "marks": 92}, {"name": "Charlie", "marks": 78} ] # Sorting manually (messy & long) students.sort(key=lambda x: x["marks"]) print(students) ✅ Pythonic Way students = [ {"name": "Alice", "marks": 85}, {"name": "Bob", "marks": 92}, {"name": "Charlie", "marks": 78} ] sorted_students = sorted(students, key=lambda x: x["marks"]) print(sorted_students) 🧒 Simple Explanation Think of key like a rule for sorting 📏 ➡️ “Sort based on THIS value” ➡️ Python handles the rest 💡 Why This Matters ✔ Clean & readable ✔ No custom loops needed ✔ Works with complex data ✔ Very common in real-world apps ⚡ Bonus Tip (Reverse Order) sorted_students = sorted(students, key=lambda x: x["marks"], reverse=True) 🐍 Don’t just sort — sort smart 🐍 Let Python do the heavy lifting #Python #PythonTips #CleanCode #LearnPython #Sort #SortingWithKeys #Programming #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 **DSA with Python – Recursion Practice** Continuing my **Data Structures & Algorithms with Python** journey, today I practiced more **recursion-based problems** to strengthen my understanding of how recursive calls break problems into smaller subproblems. 📚 **Problems I Practiced** 🔹 **Count Number of Digits (Recursion)** Logic: Repeatedly divide the number by 10 until it reaches 0. Each recursive call counts one digit. 🔹 **Sum of Digits of a Number** Example: 5251 → 5 + 2 + 5 + 1 = 13 Using recursion: `sum(n) = (n % 10) + sum(n // 10)` 🔹 **Reverse a String using Recursion** Example: `"abcd"` → `"dcba"` Recursively reduce the string and build the reversed result step by step. 🔹 Palindrome Check using Recursion Compared characters from the start and end of the string recursively until the middle is reached. Works for both odd and even length strings. 🔹 Reverse a String using Recursion Example: "abcd" → "dcba" Recursively append characters from the end to build the reversed string. 🔹 Sum of All Elements in an Array using Recursion Logic: sum(arr, i) = arr[i] + sum(arr, i+1) Continue until the index reaches the length of the array. 💡 **Key Learnings** ✔ Importance of **base conditions** in recursion ✔ How recursive calls create a **call stack** ✔ Breaking complex problems into **smaller subproblems** ✔ Strengthening **algorithmic thinking** Step by step building stronger foundations in **DSA and problem solving**. #DSA #Python #Recursion #Algorithms #DataStructures #CodingPractice #ProblemSolving #CodingInterview #PythonDeveloper #SoftwareEngineering #BackendDevelopment #LearnInPublic #DeveloperJourney #ContinuousLearning #Programming #TechLearning #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
I’ve just published my first blog post on Medium, diving into a Python concept I recently explored: 👉 Mutable vs Immutable Objects Before this, I used to think variables simply “store values.” But in Python, they actually reference objects in memory. Having learned C previously really helped me grasp this concept more quickly, especially when it comes to understanding how memory and references work. In this post, I break down: • The difference between == and is • Mutable vs immutable objects (with clear examples) • Why l1 = l1 + [4] and l1 += [4] behave differently • How Python passes arguments to functions Writing about what I learn pushes me to go deeper and truly understand the concepts. If you’re learning Python or preparing for technical interviews, this is definitely a topic worth mastering. 📖 Read here: https://lnkd.in/guVnYN3Q #Python #SoftwareEngineering #Programming #LearningJourney #Tech
To view or add a comment, sign in
-
😊❤️ Todays topic: Topic: *args and **kwargs in Python: ============== Sometimes you don’t know how many arguments a function will receive. Python gives a flexible way to handle this. *args (Non-keyword arguments): Used to pass multiple values as a tuple. def add(*args): print(args) add(1, 2, 3) Output: (1, 2, 3) Explanation: *args collects all positional arguments Inside the function, it behaves like a tuple Example with logic: def add(*args): total = 0 for i in args: total += i return total print(add(1, 2, 3, 4)) Output: 10 **kwargs (Keyword arguments): Used to pass multiple key-value pairs as a dictionary. def info(**kwargs): print(kwargs) info(name="Gemini", role="Developer") Output: {'name': 'Gemini', 'role': 'Developer'} Explanation: **kwargs collects named arguments Inside the function, it behaves like a dictionary Example with logic: def info(**kwargs): for key, value in kwargs.items(): print(key, ":", value) info(name="Gemini", role="Developer") Key Difference: *args → tuple of values **kwargs → dictionary of key-value pairs Order Rule (Important): def func(a, *args, **kwargs): pass Order must be: Normal parameters *args **kwargs 😎Interview Insight: You can use any name instead of args/kwargs, but * and ** are mandatory Very useful in writing flexible and reusable functions Quick Question: What will happen if you pass both *args and **kwargs together in a function call? #Python #Programming #Coding #InterviewPreparation #Developers
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