day 10 types of error in python 1.zero division error print (10/0) 2.value error 3.keyword error 4.index error 5.attribute error 6.typerrror 7.ioerror 8.module error 9.import error 🐍 Common Python Errors Every Developer Should Know While learning Python, understanding errors is just as important as writing code. These errors help developers identify and fix issues quickly. Here are some common Python errors with examples. 👇 1️⃣ ZeroDivisionError Occurs when a number is divided by zero. print(10/0) Output: ZeroDivisionError: division by zero 📌 Python does not allow division by zero because it is mathematically undefined. 2️⃣ ValueError Occurs when a function receives a correct data type but an inappropriate value. num = int("hello") Output: ValueError: invalid literal for int() 📌 Here Python expects a numeric string but receives text. 3️⃣ KeyError Occurs when trying to access a key that does not exist in a dictionary. data = {"name": "Prem", "age": 25} print(data["salary"]) Output: KeyError: 'salary' 📌 The dictionary does not contain the key "salary". 4️⃣ IndexError Occurs when trying to access an index that is out of range. numbers = [10, 20, 30] print(numbers[5]) Output: IndexError: list index out of range 📌 The list has only 3 elements but we are trying to access the 6th position. 5️⃣ AttributeError Occurs when an object does not have the attribute or method you are trying to use. text = "python" text.append("3") Output: AttributeError: 'str' object has no attribute 'append' 📌 append() works for lists, not strings. 6️⃣ TypeError Occurs when an operation is applied to an inappropriate data type. print("Age: " + 25) Output: TypeError: can only concatenate str (not "int") to str 📌 Python cannot combine string and integer directly. 7️⃣ IOError / OSError Occurs when file operations fail. file = open("data.txt", "r") Output: FileNotFoundError: [Errno 2] No such file or directory 📌 Happens when the file does not exist. 8️⃣ ModuleNotFoundError Occurs when Python cannot find the module you are trying to import. import tensorflowxyz Output: ModuleNotFoundError: No module named 'tensorflowxyz' 📌 The module is not installed or the name is incorrect. 9️⃣ ImportError Occurs when Python cannot import a specific component from a module. from math import square Output: ImportError: cannot import name 'square' 📌 The math module does not contain square. 💡 Tip: Errors are not failures — they are guides that help developers write better code. more information follow Prem chandar 🔖 Hashtags #Python #PythonProgramming #LearnPython #Coding #Programming #Developers #SoftwareEngineering #TechLearning #AI #MachineLearning #CodingJourney
Common Python Errors Every Developer Should Know
More Relevant Posts
-
🐍 3 Python Built-ins That Look Simple… But Are More Powerful Than They Seem One thing I appreciate about Python is how some of the most useful tools look deceptively simple. At first glance, they seem basic. But once you understand the one feature that really matters, they become incredibly practical in real projects. Here are 3 built-ins that quietly make Python code cleaner and more expressive. 🔢 1. sorted() — More Than Just Sorting Numbers Most people think sorted() is mainly for sorting numbers or strings. But the real power comes from key=. In real applications, you're rarely sorting plain numbers. Instead, you're sorting things like: 👤 Users 📋 Tasks 📁 Files 📦 Dictionaries The key parameter tells Python which part of each item should determine the order. Examples in real projects: ✔️ Sort users by age ✔️ Sort tasks by priority ✔️ Sort files by modification date Instead of restructuring your data or writing extra logic, sorted() lets you clearly express how your data should be ordered. 🔗 2. zip() — Pair Related Data Cleanly A very common pattern looks like this: names[i] ages[i] It works… but it also means manually managing indexes. zip() removes that extra work. It lets you iterate through related values together, without worrying about positions. Example scenarios: 👤 Names + ages 🛒 Products + prices 📅 Dates + sales numbers Another benefit: if the lists have different lengths, zip() automatically stops at the shortest one. The result? ✔️ Less indexing ✔️ Cleaner loops ✔️ Easier-to-read code 🔁 3. enumerate() — When You Need Index + Value You’ve probably seen this pattern before: for i in range(len(items)): It works, but it’s not the cleanest approach. enumerate() already gives you both the index and the value in one step. This makes loops much more natural. Common use cases include: 📋 Printing numbered lists 📊 Tracking item positions 🧭 Working with ordered data A small change—but it often makes loops simpler and clearer. 💡 The Bigger Lesson Many Python built-ins are like this. They look simple at first, so people only use them at a surface level. But once you understand the feature that really matters, your code becomes: ✔️ clearer ✔️ shorter ✔️ easier to reason about And that’s a pretty good trade. 💬 Which Python built-in improved your code the most once you truly understood it? #Python #Programming #SoftwareEngineering #PythonTips #CleanCode #DeveloperProductivity #CodingTips
To view or add a comment, sign in
-
-
💡 Python Exception Handling: Writing More Reliable Code While writing programs in Python, errors can sometimes occur during execution. These are known as runtime errors, such as: • Dividing by zero • Entering an invalid data type • Trying to open a file that does not exist If not handled properly, these errors may stop the program unexpectedly. Exception handling helps manage such situations gracefully. 1️⃣ Basic try/except Code that may cause an error is placed inside the try block. If an error occurs, the except block runs instead of stopping the program. Example: try: number = int(input("Enter a number: ")) print(1000 / number) except: print("An error occurred") ➡️ The program tries to convert the input and divide 1000 by it. If the input is invalid or 0, the except block runs instead of crashing. 2️⃣ Handling specific exceptions We can handle different errors separately. Example: try: number = int(input("Enter a number: ")) result = 1000 / number except ValueError: print("Invalid input") except ZeroDivisionError: print("Cannot divide by zero") This example handles different types of errors separately. ➡️ If the user enters an invalid value, a ValueError occurs. ➡️ If the user enters 0, a ZeroDivisionError occurs. 3️⃣ Using else The else block runs only if no exception occurs. Example: try: number = int(input("Enter number: ")) result = 1000 / number except ZeroDivisionError: print("Cannot divide by zero") else: print("Result is:", result) ➡️ This separates normal logic from error handling. 4️⃣ Using finally The finally block runs whether an exception occurs or not. Example: file = None try: file = open("data.txt", "r") print("File opened successfully") except FileNotFoundError: print("The file does not exist") finally: if file: file.close() print("File closed") ➡️ file is first set to None, meaning the variable exists but is not linked to a file yet. ➡️ The program tries to open data.txt. If the file is opened successfully, a message is printed. ➡️ If the file does not exist, a FileNotFoundError occurs and the except block runs. ➡️ The finally block always runs and ensures the file is closed if it was opened. 🔹 The finally block is commonly used for cleanup tasks such as closing files, database connections, or releasing system resources. 5️⃣ Capturing the error message Example: try: x = 10 / 0 except Exception as e: print("Error:", e) ➡️ The error message is stored in e, which helps in debugging. 🔹 Summary try and except make Python programs more robust by preventing crashes and handling unexpected situations properly. #Python #Programming #AI #DataAnalytics #ExceptionHandling #Coding
To view or add a comment, sign in
-
In Python, what is the difference between mutable and immutable variables? And how does this affect data handling inside functions? 🔹 First: What does Mutable vs Immutable mean? In Python, everything is an object. The key difference is whether the object can be changed after it is created. ✅ Immutable Objects An immutable object cannot be modified after creation. If you try to change it, Python creates a new object instead. Examples: • int • float • str • tuple Example: y = 3.5 y = y * 2 print(y) ➡️ Output: 7.0 Here, Python does not modify 3.5. It creates a new float object 7.0 and reassigns y to it. ✅ Mutable Objects A mutable object can be modified after creation without creating a new object. Examples: • list • dict • set Example: list = [1, 2, 3] list.append(4) print(list) ➡️ Output: [1, 2, 3, 4] Here, Python modifies the same list object in memory. 🔎 How Does This Affect Functions? This difference becomes very important when passing objects to functions. 1️⃣ Case 1: Immutable Inside a Function def change_text(text): text = text + "!" word = "Hi" change_text(word) print(word) ➡️ Output: Hi 🔹Explanation • word = "Hi" creates a string object "Hi" in memory. • When we call change_text(word), the function receives a reference to the same object. • Inside the function, text = text + "!" does NOT modify "Hi" because strings are immutable. • Python creates a new string "Hi!" and makes text refer to it. • The original variable word still refers to "Hi". ➡️ That’s why print(word) outputs "Hi". 2️⃣ Case 2: Mutable Inside a Function def remove_last(numbers): numbers.pop() values = [10, 20, 30] remove_last(values) print(values) ➡️ Output: [10, 20] 🔹Explanation • values = [10, 20, 30] creates a list object in memory. • When we call remove_last(values), the function receives a reference to the same list. • Inside the function, numbers.pop() removes the last element from the same list object in memory. • Since lists are mutable, Python modifies the existing object instead of creating a new list. • Both values and numbers point to that same list, so the change appears outside the function as well. ➡️ That’s why print(values) outputs [10, 20]. 🔎 Core Concept • Immutable objects cannot be changed in place. • Mutable objects can be modified directly. • When passing mutable objects to functions, changes inside the function affect the original data. • When passing immutable objects, changes inside the function do not affect the original variable. 🔹Why This Matters in AI & Analytics When working with datasets and AI pipelines, modifying a mutable object can unintentionally change your original data. Understanding mutability helps you avoid bugs and write more predictable, reliable code. #Python #Programming #AI #DataScience #MachineLearning #AIandAnalytics
To view or add a comment, sign in
-
🚀 I Learned Two Python Concepts Today That Instantly Made My Code Better Today I practiced two important Python concepts: • While Loops • Format Specifiers (Python f-string formatting) Both are heavily used in real programs for input validation and clean output formatting. 🔁 1. While Loop — Repeating Code Until a Condition Changes A while loop repeatedly executes code as long as a condition is true. age = int(input("Enter your age: ")) while age < 0: print("Age cannot be negative") age = int(input("Enter your age: ")) print(f"You are {age} years old") 📌 What Happens 1️⃣ User enters age. 2️⃣ If the value is negative, an error appears. 3️⃣ The program asks again until a valid value is entered. 🌍 Real‑world uses • Input validation • Login retry systems • Game loops • Menu programs For example, an ATM keeps asking for a PIN until it is correct. 🔄 2. Infinite Loop + Break (Common Pattern) while True: principal = float(input("Enter principal amount: ")) if principal < 0: print("Principal cannot be negative") else: break 🧠 Logic • while True creates a continuous loop • Invalid input → error message • Valid input → break stops the loop This pattern is widely used for reliable user input handling. 🎯 3. Format Specifiers — Clean Output Formatting Python f-strings allow precise formatting of numbers. General syntax {value:flags} Example value price = 3000.1459 🔢 Round to specific decimals print(f"{price:.2f}") Output 3000.15 .2f → round to 2 decimal places (very common in finance). 0️⃣ Zero padding / fixed width print(f"{price:010}") Example 0003000.1459 Useful for IDs, invoices, or structured tables. 📊 Number alignment Left {value:<10} Right {value:>10} Center {value:^10} Helpful when printing tables or reports. 💰 Sign and comma formatting print(f"{price:+,.2f}") Output +3,000.15 Meaning: • + show sign • , thousands separator • .2f two decimals Common in financial dashboards and reports. 🧮 Example: Compound Interest total = principal * pow((1 + rate/100), time) print(f"Balance after {time} years: ${total:.2f}") This demonstrates: • while-loop validation • calculation logic • formatted output 📚 What I Practiced Today • While loops • Infinite loop pattern • Input validation • Python format specifiers • Clean numeric output Programming is about controlling logic and handling real data correctly. 🔗 Code Repository GitHub: https://lnkd.in/dFtwyqEw #python #pythonlearning #codingjourney #programming #softwaredeveloper #learnpython #developers #100daysofcode #computerscience
To view or add a comment, sign in
-
-
🚀 Most beginners “learn Python”… But very few actually build logic with it. Today, I focused on changing that. 📚 What I Learned Today I worked on Python fundamentals through real mini-projects instead of just reading concepts. I practiced: Loops & conditionals Lists, tuples & dictionaries User input handling Basic game logic Random module And most importantly… I combined them into working programs. 🧠 Key Concepts I Learned • Control Flow (if/else + loops) Used to control program decisions Example: checking correct/incorrect answers 👉 This is the backbone of any application logic • Data Structures (Tuples, Lists, Dictionaries) Tuples → fixed data (questions, answers) Lists → dynamic storage (user guesses, cart items) Dictionaries → key-value pairs (menu, capitals) 👉 Real-world use: storing structured app data • Dictionary Methods .get() → safe access (avoids errors) .items() → loop through key-value pairs 👉 Used in menus, APIs, and configs everywhere • User Input Handling input() + .upper() / .lower() 👉 Ensures consistent user interaction • Random Module random.choice() → random selection random.shuffle() → shuffle data 👉 Core for games, simulations, AI logic 💻 What I Built Today 1️⃣ Quiz Game Multiple questions with options Tracks user answers Calculates final score 👉 Learned how to structure logic step-by-step 2️⃣ Menu Ordering System Displays menu using dictionary User selects items Calculates total bill 👉 Real-world concept of cart systems (like e-commerce) 3️⃣ Dictionary Practice System Managed and updated key-value data Iterated through keys, values, items 👉 Foundation for backend development 4️⃣ Random Experiments Generated random numbers Simulated card shuffling 👉 Core concept behind games and probability systems ⚠️ Challenge I Faced Problem: → Managing multiple data structures together (lists + dictionaries + tuples) got confusing Solution: → Broke the problem into steps: Store data clearly Process user input Apply logic Print results 👉 This structured thinking made everything manageable 💡 Developer Insight Don’t just memorize syntax. 👉 Build small systems where multiple concepts work together Because: Real development = combining simple concepts into one working system 📈 Progress Reflection Today I moved from: “Learning Python concepts” → “Thinking like a developer” Now I can: Design simple programs Handle user input Build logic-driven applications This is real progress toward becoming a full-stack developer 🎯 Tomorrow’s Focus Start file handling (reading/writing files) Build a persistent version of the quiz (save scores) Improve logic structure 🔥 Final Thought Small projects build big skills. You don’t need 100 tutorials… You need 10 projects you truly understand. #buildinpublic #python #codingjourney #learnincode #developers #programming #100daysofcode #softwareengineering #beginners #webdevelopmen
To view or add a comment, sign in
-
🚀 Most beginners “learn Python”… But very few actually build logic with it. Today, I focused on changing that. 📚 What I Learned Today I worked on Python fundamentals through real mini-projects instead of just reading concepts. I practiced: Loops & conditionals Lists, tuples & dictionaries User input handling Basic game logic Random module And most importantly… I combined them into working programs. 🧠 Key Concepts I Learned • Control Flow (if/else + loops) Used to control program decisions Example: checking correct/incorrect answers 👉 This is the backbone of any application logic • Data Structures (Tuples, Lists, Dictionaries) Tuples → fixed data (questions, answers) Lists → dynamic storage (user guesses, cart items) Dictionaries → key-value pairs (menu, capitals) 👉 Real-world use: storing structured app data • Dictionary Methods .get() → safe access (avoids errors) .items() → loop through key-value pairs 👉 Used in menus, APIs, and configs everywhere • User Input Handling input() + .upper() / .lower() 👉 Ensures consistent user interaction • Random Module random.choice() → random selection random.shuffle() → shuffle data 👉 Core for games, simulations, AI logic 💻 What I Built Today 1️⃣ Quiz Game Multiple questions with options Tracks user answers Calculates final score 👉 Learned how to structure logic step-by-step 2️⃣ Menu Ordering System Displays menu using dictionary User selects items Calculates total bill 👉 Real-world concept of cart systems (like e-commerce) 3️⃣ Dictionary Practice System Managed and updated key-value data Iterated through keys, values, items 👉 Foundation for backend development 4️⃣ Random Experiments Generated random numbers Simulated card shuffling 👉 Core concept behind games and probability systems ⚠️ Challenge I Faced Problem: → Managing multiple data structures together (lists + dictionaries + tuples) got confusing Solution: → Broke the problem into steps: Store data clearly Process user input Apply logic Print results 👉 This structured thinking made everything manageable 💡 Developer Insight Don’t just memorize syntax. 👉 Build small systems where multiple concepts work together Because: Real development = combining simple concepts into one working system 📈 Progress Reflection Today I moved from: “Learning Python concepts” → “Thinking like a developer” Now I can: Design simple programs Handle user input Build logic-driven applications This is real progress toward becoming a full-stack developer 🎯 Tomorrow’s Focus Start file handling (reading/writing files) Build a persistent version of the quiz (save scores) Improve logic structure 🔥 Final Thought Small projects build big skills. You don’t need 100 tutorials… You need 10 projects you truly understand. #buildinpublic #python #codingjourney #learnincode #developers #programming #100daysofcode #softwareengineering #beginners #webdevelopment
To view or add a comment, sign in
-
How Lambda Really Works Inside Python Loops One of the most confusing Python behaviors appears when using lambda inside loops. Let’s look at this example: funcs = [lambda x: x * i for i in range(3)] print(funcs[1](2)) Many developers expect the output to be 2, but the actual output is: 4 Let’s break it down step by step. 1️⃣ Step 1: What does this line create? funcs = [lambda x: x * i for i in range(3)] This is a list comprehension. The loop runs with: • i = 0 • i = 1 • i = 2 On each iteration, we append: lambda x: x * i After the loop finishes, funcs contains three function objects. Important: ❌ It does NOT contain numbers. ✅ It contains function objects. If we print it: print(funcs) ➡️ We get something like: [<function ...>, <function ...>, <function ...>] Because we stored functions, not results. 2️⃣ Step 2: The Critical Concept: Late Binding Here’s the key idea: The lambda does not store the value of i at the time it is created. It stores a reference to the variable i. ➡️ By the time the loop finishes, i equals: 2 So all three functions now effectively behave like: lambda x: x * 2 This behavior is called late binding. Python looks up the value of i when the function is executed, not when it is defined. 3️⃣ Step 3: What does this line do? print(funcs[1](2)) First: funcs[1] Returns the second function in the list. Which is effectively: lambda x: x * 2 Then (2) ➡️ Calls the function with x = 2. So the result becomes: 2 * 2 = 4 That’s why the output is: 4 🔑 Key Points to Remember • lambda creates a function. • The loop creates several functions. • They all use the same variable. • After the loop ends, the variable has its last value. • So all functions use that last value. • If you want each function to remember its own value, you must store it at creation time using: ➡️ lambda x, i=i: x * i Understanding this concept is essential when working with closures, functional programming, or building dynamic logic in Python. Have you ever been surprised by Python’s late binding behavior? 👀 #Python #Programming #Coding #SoftwareDevelopment #AI #MachineLearning #DataScience
To view or add a comment, sign in
-
Whether you're just starting Python or you've been coding for years, there are certain commands and patterns you reach for constantly. Bookmark this: a complete cheat sheet of Python commands you'll use every single day. VARIABLES AND DATA TYPES → Numbers: age = 30, price = 19.99 → Strings: name = "Alice", f"Hello, {name}!" → Booleans: is_active = True → Type checking: type(age), isinstance(age, int) STRING ESSENTIALS → Formatting: f"Total: ${price:.2f}" → Methods: .upper(), .lower(), .strip(), .split() → Searching: .find(), .count(), .startswith() → Slicing: text[0:3], text[::-1] LIST OPERATIONS → Creating: fruits = ["apple", "banana"] → Adding: .append(), .insert(), .extend() → Removing: .remove(), .pop(), del → List comprehensions: [x**2 for x in range(10)] → Filtering: [x for x in range(20) if x % 2 == 0] DICTIONARIES → Access: user["name"], user.get("phone", "N/A") → Modify: user["age"] = 31, user.update({"city": "NYC"}) → Iterate: for key, value in user.items() → Dict comprehensions: {x: x**2 for x in range(6)} LOOPS AND CONTROL → For loops: for i, item in enumerate(list) → While loops with break/continue → Range: range(2, 10, 2) → Zip: for name, age in zip(names, ages) → Ternary: status = "adult" if age >= 18 else "minor" FUNCTIONS → Basic: def greet(name): return f"Hello, {name}!" → Default params: def greet(name, greeting="Hello") → Args/kwargs: def func(*args, **kwargs) → Lambda: lambda x: x**2 CLASSES → Basic class with __init__ and methods → Inheritance: class Dog(Animal) → Dataclasses: @dataclass for simple data containers FILE I/O → Reading: with open("file.txt", "r") as f: content = f.read() → Writing: with open("file.txt", "w") as f: f.write("text") → CSV: csv.reader(), csv.DictReader() → JSON: json.load(), json.dump() ERROR HANDLING → Try/except blocks with specific exceptions → Finally clause for cleanup → Raising custom exceptions COMMON BUILT-INS → Math: abs(), round(), min(), max(), sum() → Type conversion: int(), float(), str(), bool() → Iteration: len(), range(), enumerate(), zip() → Functional: map(), filter(), any(), all() WHY THIS MATTERS Python's strength is in its readability and expressiveness. These patterns aren't just syntax—they're the building blocks of clean, Pythonic code. Mastering these daily-use commands makes you more productive and helps you write code that other developers can easily understand and maintain. Complete Python cheat sheet with examples: https://lnkd.in/dZwv4gNK What Python commands do you find yourself using most often? #Python #Programming #CheatSheet #PythonBasics #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
🧙♂️ Magic Methods in Python (Dunder Methods) Python is known for its powerful and flexible object-oriented features. One of the most interesting concepts in Python is Magic Methods, also called Dunder Methods (Double Underscore Methods). Magic methods allow developers to define how objects behave with built-in operations such as addition, printing, comparison, and more. These methods always start and end with double underscores (__). Example: __init__ __str__ __add__ __len__ They are automatically called by Python when certain operations are performed. --- 🔹 Why Magic Methods are Important? Magic methods help to: ✔ Customize the behavior of objects ✔ Make classes behave like built-in types ✔ Improve code readability ✔ Implement operator overloading They allow developers to write clean, powerful, and Pythonic code. --- 🔹 Commonly Used Magic Methods 1️⃣ __init__ – Constructor This method is automatically called when an object is created. class Student: def __init__(self, name): self.name = name s = Student("Vamshi") --- 2️⃣ __str__ – String Representation Defines what should be displayed when we print the object. class Student: def __init__(self, name): self.name = name def __str__(self): return f"Student name is {self.name}" s = Student("Vamshi") print(s) --- 3️⃣ __len__ – Length of Object Allows objects to work with the len() function. class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) t = Team(["A", "B", "C"]) print(len(t)) 4️⃣ __add__ – Operator Overloading Defines how the + operator works for objects. class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value n1 = Number(10) n2 = Number(20) print(n1 + n2) 🔹 Key Takeaway Magic methods make Python classes more powerful and flexible by allowing objects to interact naturally with Python's built-in operations. Understanding magic methods helps developers write cleaner and more advanced object-oriented programs. #Python #PythonProgramming #MagicMethods #DunderMethods #OOP #Coding #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