🐍 30 Python Challenges to Test Your Skills! 💻 1️⃣ Reverse a string without using loops 🔄 2️⃣ Count duplicates in a list 📝 3️⃣ Flatten a nested list 📂 4️⃣ Find all prime numbers up to N 🔢 5️⃣ Check if a string is a palindrome 🔁 6️⃣ Swap two variables in Python ⚡ 7️⃣ Merge two dictionaries efficiently 🗂️ 8️⃣ Remove all vowels from a string ✂️ 9️⃣ Sort a list of dictionaries by a key 🔑 🔟 Generate Fibonacci numbers in one line 🔢 1️⃣1️⃣ Find the most common element in a list 📊 1️⃣2️⃣ Remove duplicates while preserving order ✅ 1️⃣3️⃣ Find largest & smallest number without min()/max() 🔝🔽 1️⃣4️⃣ Count character occurrences in a string 🔡 1️⃣5️⃣ Reverse words in a sentence 🔁 1️⃣6️⃣ Check if two strings are anagrams 🔤 1️⃣7️⃣ Check if a number is a perfect square ◼️ 1️⃣8️⃣ Transpose a 2D list (matrix) 🔄 1️⃣9️⃣ Convert a list of strings to integers, ignoring invalid inputs 🔢 2️⃣0️⃣ Filter even numbers from a list ✨ 2️⃣1️⃣ Calculate factorial using recursion or loops 🔁 2️⃣2️⃣ Check if a number is prime efficiently 🔢 2️⃣3️⃣ Generate all subsets of a list 📂 2️⃣4️⃣ Capitalize the first letter of each word ✍️ 2️⃣5️⃣ Merge two sorted lists into one sorted list 🗂️ 2️⃣6️⃣ Find second largest number in a list 🔝 2️⃣7️⃣ Count vowels in a string 🔡 2️⃣8️⃣ Check if a list is sorted ✅ 2️⃣9️⃣ Find indices of all occurrences of an element 📌 3️⃣0️⃣ Check if a string is a pangram 🔠 💡 Pro Tip: The most Pythonic solutions often use list comprehensions, sets, dictionaries, and built-in functions. ⚡ Try them out and comment your favorite solution! Don’t forget to share tips & tricks you use daily in Python. 🔁 Repost to help others learn faster ❤️ Like if you found it useful 📥 Save it for future reference 👥 Tag someone who needs this! #Python 🐍 #Programming 💻 #CodingChallenge 🚀 #Developers 👨💻 #TechInnovation 💡 #AI 🤖 #MachineLearning 🧠 #DataScience 📊 #Automation ⚡#SoftwareEngineering 💻 #ProgrammingLife 📝 #TechTrends 📈 #PythonTips 🐍 #LearnToCode 📚 #ProblemSolving 🧩 #DeveloperCommunity #TechSkills ⚡ #PythonProgramming 🐍
Python Coding Challenges: 30 Exercises to Test Your Skills
More Relevant Posts
-
Day 15/30 - for Loops in Python What is a for Loop? A for loop is used to iterate — to go through every item in a sequence one by one and execute a block of code for each item. Instead of writing the same code 10 times, you write it once and let the loop repeat it automatically. The loop stops when it has gone through every item. The Golden Rule: A for loop works on any iterable — any object Python can step through one item at a time. This includes lists, tuples, strings, dictionaries, sets, and ranges. Syntax Breakdown for item in iterable: item -> This is a temporary variable holding the current item on each loop , you name it anything in -> It's the keyword that connects the variable to the iterable , always required iterable → the collection being looped - list, tuple, string, range, dict, set 1. How It Works, Step by Step 2. Python looks at the iterable and picks the first item 3. It assigns that item to your loop variable 4. It runs the indented block of code using that item 5. It moves to the next item and repeats steps 2–3 6. When there are no more items, the loop ends automatically The range() Function The range() generates a sequence of numbers for looping. The stop value is always excluded: range(5) -> 0, 1, 2, 3, 4 range(2, 6) -> 2, 3, 4, 5 range(0, 10, 2) -> 0, 2, 4, 6, 8 range(10, 0, -1) -> 10, 9, 8 ... 1 What You Can Loop Over List → loops through each item String → loops through each character one by one Tuple → same as list — goes item by item Dictionary → loops through keys by default; use .items() for key and value Range → loops through a sequence of generated numbers Set → loops through unique items (order not guaranteed) Tip: Use a name that makes the code readable — for fruit in fruits, for name in names, for i in range(10). i is the convention for index-style loops. Key Learnings ☑ A for loop iterates through every item in a sequence — running the same block for each one ☑ range(start, stop, step) generates numbers .Stop is always excluded ☑ You can loop over lists, strings, tuples, dicts, sets, and ranges ☑ The loop variable is temporary , holds the current item on each pass ☑ Indentation matters , only the indented block runs inside the loop Why It Matters: Loops are what turn Python from a calculator into an automation tool. Processing 10,000 sales records, sending emails to every customer, checking every row in a database - all of it uses loops. Writing code once and letting it repeat is one of the most powerful ideas in programming. My Takeaway Before loops, I was writing the same thing over and over. Now I write it once and Python handles the rest. That's what automation actually means - not robots, just smart repetition. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
🔎 Mastering f-Strings in Python #Day32 If you're learning Python, f-strings are something you’ll use almost every day. They make string formatting cleaner, faster, and much more readable. 🔹 What Are f-Strings? f-strings (formatted string literals) were introduced in Python 3.6 and provide a simple way to embed variables and expressions directly inside strings. You create them by placing f before the opening quotation marks. Syntax: f"Your text {variable_or_expression}" Example: name = "Ishu" age = 20 print(f"My name is {name} and I am {age} years old.") ✅ Output: My name is Ishu and I am 20 years old. 🔹 Why Use f-Strings? Before f-strings, we used: 1. % Formatting (Old Style) name = "Ishu" print("Hello %s" % name) 2. .format() Method print("Hello {}".format(name)) 3. f-Strings (Modern Way) ✅ print(f"Hello {name}") 💡Cleaner 💡Easier to read 💡Faster than older methods 💡Supports expressions directly 🔹 Inserting Variables product = "Laptop" price = 55000 print(f"The {product} costs ₹{price}") Output: The Laptop costs ₹55000 🔹 Using Expressions Inside f-Strings You can perform calculations directly inside {} a = 10 b = 5 print(f"Sum = {a+b}") print(f"Product = {a*b}") Output: Sum = 15 Product = 50 🔹 Calling Functions Inside f-Strings name = "ishu" print(f"Uppercase: {name.upper()}") Output: Uppercase: ISHU 🔹 Formatting Numbers Decimal Places pi = 3.14159265 print(f"{pi:.2f}") Output: 3.14 .2f → 2 decimal places. 🔹 Adding Commas to Large Numbers num = 1000000 print(f"{num:,}") Output: 1,000,000 🔹 Formatting Percentages score = 0.89 print(f"{score:.2%}") Output: 89.00% 🔹 Padding and Alignment Left Align print(f"{'Python':<10}") Right Align print(f"{'Python':>10}") Center Align print(f"{'Python':^10}") Useful for reports and tables. 🔹 Using Expressions with Conditions marks = 85 print(f"Result: {'Pass' if marks>=40 else 'Fail'}") Output: Result: Pass Yes — even conditional logic works 😎 🔹 Date Formatting with f-Strings from datetime import datetime today = datetime.now() print(f"{today:%d-%m-%Y}") Example output: 26-04-2026 🔹 Debugging with f-Strings (Awesome Feature) Python allows this: x = 10 y = 20 print(f"{x=}, {y=}") Output: x=10, y=20 Great for debugging 🛠️ 🔹 Escaping Curly Braces Need literal braces? print(f"{{Python}}") Output: {Python} Use double braces {{ }} 🔹 f-Strings with Dictionaries student = {"name":"Ishu","marks":95} print(f"{student['name']} scored {student['marks']}") Output: Ishu scored 95 🔹 f-Strings with Loops for i in range(1,4): print(f"Square of {i} is {i*i}") Output: Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 🔹 Final Thoughts f-Strings are one of Python’s most elegant features. They make your code: ✔More readable ✔More powerful ✔More Pythonic ✔More professional #Python #DataAnalytics #PythonProgramming #DataAnalysis #DataAnalysts #PowerBI #Excel #CodeWithHarry #Tableau #SQL #Consistency #DataVisualization #DataCleaning #DataCollection #MicrosoftPowerBI #MicrosoftExcel #F_Strings
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ```
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ``` 💬 *Double Tap ❤️ for Part 4!*
To view or add a comment, sign in
-
🧠 Python Tricky Outputs — Test Your Knowledge! Can you guess the output of these three Python snippets? Let's find out! 👇 🔍 OUTPUTS: Snippet 1 → '['a', 'b', 'c', 'd', 'e', 'f,g,h']' Snippet 2 → '{2, 3}' Snippet 3 → '2' 🔍HOW IT WORKS: "Snippet 1 — split() with maxsplit=5" Step 1 → String: "a,b,c,d,e,f,g,h" Step 2 → Split by comma ',' Step 3 → maxsplit=5 means only split the first 5 times. Step 4 → Result has 6 items (5 splits + remainder) Split 1 → "a" Split 2 → "b" Split 3 → "c" Split 4 → "d" Split 5 → "e" Remainder → "f,g,h" (no more splitting) "Snippet 2 — Set Intersection (&)" Step 1 → {1, 2, 3} Step 2 → {2, 3, 4} Step 3 → & (ampersand) finds common elements. Step 4 → Common elements: 2 and 3 Step 5 → Result: {2, 3} "Snippet 3 — dict.get() with default" Step 1 → Dictionary d = {"a": 1} Step 2 → d.get("b", 2) Step 3 → "b" is NOT a key in the dictionary Step 4 → get() returns default value → 2 Step 5 → If the key existed, it would return the actual value ⚠️ EDGE CASES: "split() maxsplit" maxsplit=0 → No splitting → Entire string as one item maxsplit > number of commas → Splits all, extra maxsplit ignored Empty string → [''] "Set intersection" Empty set → {} No common elements → set() Same sets → Returns the set itself "dict.get()" Key exists → Returns actual value Key missing → Returns default No default provided → Returns None 📌 REAL-WORLD APPLICATIONS: "split() with maxsplit" → Parsing logs, CSV headers, first N fields only "Set intersection" → Finding common users, shared interests, mutual friends "dict.get()" → Safe dictionary access, avoiding KeyError, from defaults 💡 KEY CONCEPTS: • 'split(',', maxsplit)' → Maximum number of splits to perform • '&' operator → Set intersection (common elements) • 'dict.get(key, default)' → Returns default if key missing • No KeyError → Safer than dict[key] 📌 QUICK QUIZ — Test Yourself: # Q1: What's the output? print("one,two,three,four".split(',', 2)) # Q2: What's the output? print({5, 6, 7} & {6, 7, 8}) # Q3: What's the output? d = {"name": "Alice"} print(d.get("age", 25)) #Python #Coding #Programming #LearnPython #Developer #Tech #PythonTips #Dictionary #Sets #Strings #CodeQuiz #SplitMethod #SetOperations #GetMethod #Day76
To view or add a comment, sign in
-
-
🎭 DRAMA SERIES: “PETER vs PYTHON” (Episode 1) 🐍😂 Scene 1: The Beginning Peter: Python… I heard you’re simple. Python: Yes, I am simple… until you meet my relatives. Peter: Relatives?? Python: NumPy, Pandas, Matplotlib… They don’t play. Scene 2: The First Attempt Peter: Let me impress you… if x = 10: Python (shouting): 🚨 INVALID!!! Peter: But… it looks right 😭 Python: Looking right is not being right. Use == or go home. 📌 Lesson 1: Precision matters. One small mistake can break everything. Scene 3: Indentation Wahala Peter: Okay I fixed it! Python: Hmm… your indentation is off. Peter: It’s just space 😩 Python: There is no “just space” here. Order is everything. 📌 Lesson 2: Structure brings clarity. Discipline in little things = big results. Scene 4: The Loop Madness Peter: Repeat this 3 times. Python: Say no more… (Code runs… runs… keeps running…) Peter: WHY IS IT NOT STOPPING?? 😭 Python: You forgot the condition… enjoy infinity. 📌 Lesson 3: Always define your limits in life and in code. Scene 5: Debugging Therapy Session Peter: Why are you not working?? Python: Check line 72. Peter: But the error is on line 10! Python: Yes… but the problem started from your life choices. 📌 Lesson 4: Errors are teachers. They don’t punish you—they reveal your gaps. Scene 6: Breakthrough Moment (After hours of struggle…) Peter: It… it worked??? 😳🔥 Python: Of course. I was building you, not stressing you. Final Scene: Wisdom Drop Peter: So all this pain was necessary? Python: Yes. You wanted growth, not comfort. 🎯 FINAL LESSON: Python is not your enemy… It’s a mirror of your thinking. If your logic is messy → errors If your thinking is clear → results 😂 Conclusion: Peter is no longer crying… Now he debugs with confidence. 💡 Keep learning. Keep failing. Keep improving. — Fatolu Peter Data Analyst | Python Instructor | Turning confusion into clarity 🚀
To view or add a comment, sign in
-
-
Finding Duplicates in a List using python ? solution 1 : def find_duplicates(nums): seen = set() duplicates = set() for num in nums: if num in seen: duplicates.add(num) else: seen.add(num) return list(duplicates) # Example nums = [1, 2, 3, 2, 4, 5, 1, 6, 3] print(find_duplicates(nums)) solution 2 : def find_duplicates(nums): counts = Counter(nums) return [num for num, count in counts.items() if count > 1] # Example nums = [1, 2, 3, 2, 4, 5, 1, 6, 3] print(find_duplicates(nums)) solution 3: import pandas as pd def find_duplicates(nums): s = pd.Series(nums) return s[s.duplicated()].unique().tolist() # Example nums = [1, 2, 3, 2, 4, 5, 1, 6, 3] print(find_duplicates(nums))
To view or add a comment, sign in
-
🔸 🔸 🔸 Classic example to address late-binding and closures in python This 4 line of code talks about multiple important concepts ↘️ Code: funcs = [] for i in range(3): funcs.append(lambda : i) print([f() for f in funcs]) 🤔 What do you think ❓ Will it give any result, will it error out of random ❓ 🟰 Well, this prints [2,2,2] over console The idea is to demystify why this code does what it does under the hood. Concepts ↘️ ➡️ Is lambda : i a valid syntax ? If yes, what does it denote It denotes a shorthand notation to define a function that does not accept any input parameters and returns a single value as output. What will lambda : i resolve to ❓ ↘️ def f(): return i ❓ What is the iterative statement doing 🟰 It simply creates a container in memory, denoted by i. Initializes i to 0 and keeps incrementing the value that the container referenced by i contains ➡️ i : 0 -> 1 -> 2 ❓What will the list funcs hold ➡️ It's important to note here, funcs is a list that appends lambda into it. ➡️ Since, lambda is nothing more than a function in python, the list holds function ✅ ❓ But, how can a list hold function and what does it mean ➡️ Python treats function as objects, and in programming objects are nothing more than a memory address. 🟰 So, the funcs list holds memory addresses that individually resolve to functions denoted by lambda ✅ ➡️ Another important pointer to note here , the list holds the memory reference to these functions, not the actual value returned by the function. ✅ ❓ Demistify [f() for f in funcs] 🟰 This is a list comprehension in python. ➡️ We are iterating over all thats contained in the list, referencing each element via local variable f Since, f refers to an in-memory function, f() will simply invoke the function call. ✅ ➡️ When i = 0: Invoke f(), the first function pointed to by the first element of the list funcs ❓ The interesting part Function call always creates a new individual scope in python. You can say it as a standalone local environment specific to that function call. So, for the first element in funcs f() -> invokes a function that returns i ❓ Where is i now ➡️ Well, i comes from the loop scope created earlier and is used in the enclosed scope lambda : i denoted by function. ❓ So , are we talking about a closure concept in python here ? ➡️ Yes, this is a closure as lambda is closing over the variable i which is defined in the outer scope, the outer scope is the loop scope. ❓ Another interesting thing to note here is : ➡️ i is defined over a single outer scope, so it is shared amongst all the functions contained in the list funcs. 🤔 Think of it as : We are evaluating each function in the list funcs, where each function simply returns i. 🟰 The value of i = 2, post loop iteration finished in range(3), and hence each of these function calls will return the value 2 i.e. value of the variable closed over by lambda. #python #closure #lambda #softwareengineering #dataengineering
To view or add a comment, sign in
-
🚀 Day 8 to10 — Python Full Stack Training | Conditional statements 🐍 Condition statements in Python are fundamental constructs used to control the flow of execution in a program. They enable decision-making by executing specific blocks of code based on whether given conditions evaluate to True. 1️⃣ if Statement The simplest form, used to execute a block of code only when a condition is satisfied. Example: x = 10 if x > 5: print("x is greater than 5") 2️⃣ if-else Statement Provides an alternative path of execution when the condition is not satisfied. Example: x = 2 if x > 5: print("Condition is True") else: print("Condition is False") 3️⃣ if-elif-else Structure Used when multiple conditions need to be evaluated in sequence. Python executes the first block where the condition is True. Example: score = 78 if score >= 90: print("Excellent") elif score >= 75: print("Good") elif score >= 50: print("Average") else: print("Needs Improvement") 4️⃣ Multiple if Statements In some scenarios, conditions need to be evaluated independently rather than exclusively. Using multiple if statements ensures each condition is checked regardless of others. Example: x = 15 if x > 10: print("Greater than 10") if x % 5 == 0: print("Divisible by 5") 5️⃣ Nested if Statements A nested structure allows you to place one condition inside another, enabling more granular decision-making. Example: x = 18 if x > 10: if x < 20: print("x is between 10 and 20") else: print("x is 20 or more") else: print("x is 10 or less")
To view or add a comment, sign in
-
🚀 Python Series – Day 15: Exception Handling (Handle Errors Like a Pro!) Yesterday, we learned how to work with files in Python 📂 Today, let’s learn how to handle errors smartly without crashing your program ⚠️ 🧠 What is Exception Handling? Exception handling is a way to manage runtime errors so your program continues running smoothly. 👉 Without it → program crashes ❌ 👉 With it → program handles error gracefully ✅ 💻 Understanding try and except try: # risky code (may cause error) except: # runs if error occurs 🔍 How it Works: ✔️ Python first executes code inside try ✔️ If NO error → except is skipped ✔️ If error occurs → Python jumps to except ⚡ Example 1 (Basic) try: num = int(input("Enter number: ")) print(10 / num) except: print("Something went wrong!") 👉 If user enters 0 or text, error is handled. 🔥 Why Avoid Only except? Using only except is not a good practice ❌ 👉 It hides the real error. ✅ Best Practice: Handle Specific Errors try: num = int(input("Enter number: ")) print(10 / num) except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Please enter a valid number!") ⚡ Multiple Exceptions in One Line except (ZeroDivisionError, ValueError): print("Error occurred!") 🧩 else Block (Less Known 🔥) try: num = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("No error, result:", num) 👉 else runs only if no error occurs 🔒 finally Block (Very Important) try: print("Trying...") except: print("Error") finally: print("This always runs ✅") 👉 Used for cleanup (closing files, database, etc.) 🎯 Why This is Important? ✔️ Prevents crashes ✔️ Makes programs professional ✔️ Used in real-world apps, APIs, ML projects ⚠️ Pro Tips: 👉 Always use specific exceptions 👉 Use finally for cleanup 👉 Don’t hide errors blindly 📌 Tomorrow: Modules & Packages (Organize Your Code Like a Pro) Follow me to master Python step-by-step 🚀 #Python #Coding #Programming #DataScience #LearnPython #100DaysOfCode #Tech #MustaqeemSiddiqui
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