🚀 Day 12 of Python Learning: File Handling in Python Today I learned how Python can create, read, write, and update files. File handling is very useful for storing data permanently. 🔹 What is File Handling? File handling allows us to work with text files and save information outside the program. 🔸 Opening a File file = open("data.txt", "r") 🔸 Reading a File print(file.read()) 🔸 Writing to a File file = open("data.txt", "w") file.write("Hello Python") 🔸 Appending Data file = open("data.txt", "a") file.write("\nNew Line Added") 🔸 Best Practice: Close File file.close() 🔸 Better Way Using with Statement with open("data.txt", "r") as file: print(file.read()) 💡 Key Learning: Using "with open()" is safer because Python automatically closes the file after use. 🧪 Practice Task: ✔ Create a file and write your name ✔ Append your city name ✔ Read the file content ✔ Count total lines in the file 🎯 Interview Question: What is the difference between "w" and "a" mode in Python file handling? Answer: "w" mode overwrites existing content, while "a" mode adds new content at the end of the file. 📌 Day 12 completed — learning practical Python skills daily! #Python #Learning #CodingJourney #Day12 #Programming #SDET #100DaysOfCode Masai #masaiverse #Dailylearning
Python File Handling Basics and Best Practices
More Relevant Posts
-
🚀 Day 9 of Python Learning: Dictionary in Python Today I learned about Dictionaries — one of the most powerful data structures in Python for storing data in key-value pairs. 🔹 What is a Dictionary? A dictionary stores data in pairs: key and value. It is useful when you want to store structured information like user details, product data, etc. 🔸 Creating a Dictionary student = { "name": "Rohit", "age": 22, "city": "Meerut" } 🔸 Accessing Values print(student["name"]) print(student["age"]) 🔸 Adding New Data student["course"] = "Python" 🔸 Updating Data student["age"] = 23 🔸 Removing Data student.pop("city") 💡 Key Learning: Dictionaries are mutable and allow fast access to data using keys. 🧪 Practice Task: ✔ Create a dictionary with your name, age, and city ✔ Add one new key-value pair ✔ Update one value ✔ Print all keys and values using a loop 🎯 Interview Question: What is the difference between list and dictionary in Python? Answer: A list stores ordered values using indexes, while a dictionary stores data using key-value pairs. 📌 Day 9 completed — growing every single day! #Python #Learning #CodingJourney #Day9 #Programming #SDET #100DaysOfCode Masai #masaiverse #dailyleaning
To view or add a comment, sign in
-
🐍 Learning Python is not about memorizing syntax. It’s about learning how to think logically, step by step. I reviewed a Python Tutorial (Codes) guide, and one thing stood out clearly: Strong Python learning starts with the fundamentals not shortcuts. What I like about this tutorial is that it builds from the core topics that actually matter: * strings * lists * tuples * sets * dictionaries * conditions * loops * functions * exception handling * classes and objects * file reading/writing * lambda functions * list comprehensions * decorators * generators That matters. Because real progress in Python does not come from copying advanced code from the internet. It comes from understanding: * how data is structured, * how logic flows, * how errors happen, * and how code becomes reusable and readable. One thing I especially liked: The tutorial uses practical code examples to move from very basic outputs and data types into more structured concepts like functions, classes, file handling, decorators, and generators. That makes it feel like a real learning path instead of disconnected theory. The uncomfortable truth? A lot of people say they want to learn Python… but get bored at the basics and jump too early into “advanced” topics. That usually slows them down. Because the basics are not the boring part. They are the foundation. 👇 Comment: What do you think is the most important Python skill to master first? A) Data types B) Loops and conditions C) Functions D) Error handling E) Problem-solving mindset #Python #Programming #Coding #PythonTutorial #LearnPython #SoftwareDevelopment #Automation #DataStructures #Functions #ExceptionHandling #OOP #FileHandling #Lambda #Decorators #Generators #CodingJourney #TechSkills #ComputerScience #Developer #PythonLearning
To view or add a comment, sign in
-
🚀 Day 8 of Python Learning: Tuples and Sets in Python Today I learned about Tuples and Sets — two important data structures in Python used for storing collections of data efficiently. 🔹 What is a Tuple? A tuple is an ordered collection of items that cannot be changed after creation (immutable). 🔸 Creating a Tuple my_tuple = (1, 2, 3, 4, 5) 🔸 Accessing Elements print(my_tuple[0]) # First element print(my_tuple[-1]) # Last element 🔹 What is a Set? A set is an unordered collection of unique items. Duplicate values are automatically removed. 🔸 Creating a Set my_set = {1, 2, 3, 4, 4, 5} print(my_set) Output: {1, 2, 3, 4, 5} 🔸 Adding Elements my_set.add(6) 🔸 Removing Elements my_set.remove(3) 💡 Key Learning: Use tuples when data should not change, and sets when you need unique values only. 🧪 Practice Task: ✔ Create a tuple of 5 numbers ✔ Create a set with duplicate values ✔ Add and remove elements from a set ✔ Print all tuple values using a loop 🎯 Interview Question: What is the difference between list, tuple, and set in Python? Answer: List is ordered and mutable, tuple is ordered and immutable, while set is unordered and stores only unique values. 📌 Day 8 completed — learning one step at a time! #Python #Learning #CodingJourney #Day8 #Programming #SDET #100DaysOfCode Masai #masaiverse #dailylearning
To view or add a comment, sign in
-
"ChatGPT just taught me Python in 5 steps. Here's exactly what it said 👇 Teaching mode is ON 🎓 Topic: Python (Basics) 1. Simple Explanation (Beginner Friendly) Python is a programming language used to give instructions to a computer. Just like you follow instructions in real life (e.g., “wake up → brush → go to school”), Python lets you give step-by-step instructions to a computer so it can do tasks for you. 2. Step-by-Step Breakdown Step 1: Your First Python Code Python print("Hello, World!") 👉 This tells the computer: “Display Hello, World!” Step 2: Output (Showing Results) print() is used to show something on the screen. Python print("I am learning Python") Step 3: Variables (Storing Information) Variables store data so you can use it later. Python name = "Soubhagya" age = 17 👉 Now Python remembers these values. Use them like this: Python print(name) print(age) Step 4: Taking Input from User Python name = input("Enter your name: ") print("Hello", name) 👉 The user types something, and Python uses it. Step 5: Basic Math in Python Python a = 10 b = 5 print(a + b) # addition print(a - b) # subtraction print(a * b) # multiplication print(a / b) # division 3. Real-Life Example 🏪 Imagine you're calculating your monthly pocket money. You get ₹100 every week. Python weekly_money = 100 total = weekly_money * 4 print(total) 👉 Python calculates your monthly money automatically instead of you doing it manually. 4. Quick Summary Python = language to talk to computers print() = display output Variables = store values input() = take user input Can do calculations and automate tasks 5. Your Turn (Test Question) 🧠 What will this code output? Python x = 8 y = 2 print(x * y)
To view or add a comment, sign in
-
🚀 Day 10 of Python Learning: Strings in Python Today I learned about Strings — one of the most commonly used data types in Python for working with text data. 🔹 What is a String? A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. 🔸 Creating Strings name = "Rohit" city = 'Meerut' 🔸 Accessing Characters print(name[0]) # First character print(name[-1]) # Last character 🔸 String Slicing print(name[0:3]) # Roh print(name[2:]) # hit 🔸 Common String Methods text = "python learning" print(text.upper()) # PYTHON LEARNING print(text.lower()) # python learning print(text.title()) # Python Learning print(text.replace("python", "Java")) 🔸 String Length print(len(name)) 💡 Key Learning: Strings are immutable, which means individual characters cannot be changed directly. 🧪 Practice Task: ✔ Create a string with your name ✔ Print first and last character ✔ Convert text to uppercase ✔ Replace one word in a sentence 🎯 Interview Question: What is the difference between list and string in Python? Answer: A string stores text characters and is immutable, while a list stores multiple values and is mutable. 📌 Day 10 completed — consistency creates success! #Python #Learning #CodingJourney #Day10 #Programming #SDET #100DaysOfCode Masai #dailyleaning #masaiverse
To view or add a comment, sign in
-
Python Learning Journey – Dictionaries Deep Dive Dictionaries are one of the most powerful and flexible data structures in Python. Today, I explored some important functions that every developer should know 👇 📌 Core Dictionary Functions: ✔️ len() – Returns number of key-value pairs ✔️ clear() – Removes all elements ✔️ get() – Access values safely without errors ✔️ pop() – Removes specific key and returns its value ✔️ popitem() – Removes last inserted key-value pair ✔️ keys() – Returns all keys ✔️ items() – Returns key-value pairs ✔️ copy() – Creates a shallow copy ✔️ setdefault() – Returns value of key (adds if not present) ✔️ update() – Updates dictionary with new key-value pairs 💡 Advanced Concept: ✨ Dictionary Comprehension – A concise way to create dictionaries in a single line Example: {x: x*x for x in range(5)} 🎯 Mastering dictionaries helps in writing efficient and clean code, especially when working with real-world data. #Globalquesttechnologies #GR Narendra Reddy #Python #CodingJourney #100DaysOfCode #Programming #SoftwareDevelopment #PythonBasics #Learning
To view or add a comment, sign in
-
-
🚀 Day 27 of My Python Learning Journey 🚀 Today I explored one of the most powerful concepts in Python: Polymorphism. 📌 Topics I Learned: 🔹 Advantages of Polymorphism • Improves code reusability • Makes programs more flexible • Reduces complexity • Helps in writing cleaner and scalable code 🔹 Important Terminologies in Python Polymorphism • Method Overriding • Operator Overloading • Duck Typing • Magic Methods 🔹 Duck Typing Philosophy in Python “If it walks like a duck and talks like a duck, then it is a duck.” 🦆 Python does not care about the object type, it only cares whether the required method or behavior is present. 🔹 Operator Overloading Python allows us to redefine the behavior of operators for user-defined objects. Example: + operator can perform different tasks: • Addition for numbers • Concatenation for strings and lists 🔹 Method Overriding A child class can redefine the method of the parent class with its own implementation. 🔹 Magic Methods Used for Operator Overloading • add() → + • sub() → - • mul() → * • truediv() → / • lt() → < • gt() → > • eq() → == 🔹 Error Associated with + Operator Trying to add incompatible data types gives an error. Example: 5 + "Python" Output: TypeError: unsupported operand type(s) for +: 'int' and 'str' Learning polymorphism made me realize how Python gives flexibility to write smart and dynamic code. Excited to learn more every day! 💻✨ Thanks for your support G.R NARENDRA REDDY sir #Day27 #Python #Polymorphism #DuckTyping #OperatorOverloading #MethodOverriding #MagicMethods #PythonProgramming #CodingJourney #LearningPython #FutureDeveloper
To view or add a comment, sign in
-
-
🚀 Day 8 of Learning Python: Error Handling 💻 ✅ Back with a learning update 👉 Today I explored how Python handles errors gracefully using exception handling. This helps prevent programs from crashing and improves user experience. 🔹 Common Python Errors: ZeroDivisionError → Dividing by zeroValueError → Invalid input (e.g., text instead of number)TypeError → Wrong data type usedFileNotFoundError → File does not exist 💡 1. Simple Error Handling try: num = int(input("Enter number: ")) print(10 / num) except: print("Error occurred!")👉 Prevents the program from crashing on invalid input 💡 2. Handling 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!") 💡 3. Using else try: num = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("You entered:", num)👉 else runs only when no exception occurs 💡 4. Using finally try: file = open("data.txt") except FileNotFoundError: print("File not found!") finally: print("Execution completed")👉 finally always executes (useful for cleanup) 💡 5. Handling Multiple Errors Together try: a = int(input()) b = int(input()) print(a / b) except (ValueError, ZeroDivisionError): print("Invalid input or division by zero") ⚡ Raising Your Own Error age = int(input("Enter age: ")) if age < 18: raise Exception("You must be 18+") 🔥 Custom Exception (Advanced) class MyError(Exception): pass try: raise MyError("Something went wrong") except MyError as e: print(e) ✅ Key Takeaway: Error handling makes your programs more robust, user-friendly, and professional. #Python #CodingJourney #LearnPython #30DaysOfCode #Programming
To view or add a comment, sign in
-
🚀 Day 13 of Python Learning: Exception Handling in Python Today I learned how to handle errors in Python using exception handling. This helps programs run smoothly even when unexpected issues occur. 🔹 What is Exception Handling? Exception handling is used to catch errors and prevent the program from crashing. 🔸 Basic Example try: num = 10 / 0 except: print("Error occurred") 🔸 Handling Specific Error try: number = int("abc") except ValueError: print("Invalid input") 🔸 Using Finally Block try: print("Start") except: print("Error") finally: print("This always runs") 🔸 Using Else Block try: print(10 / 2) except: print("Error") else: print("No error found") 💡 Key Learning: Using try-except makes programs more reliable and user-friendly. 🧪 Practice Task: ✔ Handle divide by zero error ✔ Handle invalid number input ✔ Use finally block in one program ✔ Create a safe calculator using try-except 🎯 Interview Question: What is the purpose of finally block in Python? Answer: The finally block always executes whether an error occurs or not. It is commonly used for cleanup tasks like closing files or database connections. 📌 Day 13 completed — learning how professionals handle errors! #Python #Learning #CodingJourney #Day13 #Programming #SDET #100DaysOfCode Masai #masaiverse #dailylearning
To view or add a comment, sign in
-
Assalam o Alaikum 👋 💡 Python Tip: Stop Writing Extra Code — Use "enumerate()"! If you’re learning Python, this small function can make your code cleaner and smarter 🚀 What is "enumerate()"? "enumerate()" is a built-in Python function that helps you loop through a list while keeping track of the index (position) of each item. 👉 Normally, you do this: You create a counter variable, update it manually, and then access elements. But with "enumerate()"… Python does it for you automatically Example: my_list = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(my_list): print(index, fruit) Output: 0 apple 1 banana 2 cherry Why use "enumerate()"? No need to create a separate counter Cleaner & more readable code Less chance of mistakes Perfect for loops where position matters Pro Tip: You can even change the starting index! for index, fruit in enumerate(my_list, start=1): print(index, fruit) 👉 Now counting starts from 1 instead of 0 🚀 Real Use Cases: • Numbering items in a list • Working with indexed data • Tracking positions in loops • Displaying ordered results If you're learning Python, mastering small functions like this will level up your coding fast! 👉 Follow for more simple Python & AI tips #Python #PythonTips #CodingForBeginners #LearnPython #AIAutomation #TechLearning
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