🚀 **Day 34 of #100DaysOfPython – Date and Time in Python** 🕒 Python provides the **`datetime`** module to handle dates and times efficiently. Let’s explore the most useful features with simple examples 👇 --- ### 🧭 1️⃣ Importing the datetime Module ```python import datetime ``` This gives access to classes like `date`, `time`, `datetime`, and `timedelta`. --- ### 📅 2️⃣ Working with Dates ```python from datetime import date today = date.today() print("Today's date:", today) specific_date = date(2024, 2, 16) print("Specific date:", specific_date) ``` ✅ You can extract parts of a date: ```python print("Year:", today.year) print("Month:", today.month) print("Day:", today.day) ``` ✅ To find the weekday: ```python print("Weekday (0=Mon):", today.weekday()) print("ISO Weekday (1=Mon):", today.isoweekday()) ``` --- ### ⏰ 3️⃣ Working with Time ```python from datetime import time specific_time = time(14, 30, 15) print("Specific time:", specific_time) print("Hour:", specific_time.hour) print("Minute:", specific_time.minute) print("Second:", specific_time.second) ``` --- ### 📆 4️⃣ Date and Time Together ```python from datetime import datetime now = datetime.now() print("Current date and time:", now) specific_datetime = datetime(2024, 2, 16, 14, 30, 15) print("Specific date and time:", specific_datetime) ``` ✅ Extract individual parts: ```python print("Year:", now.year) print("Month:", now.month) print("Day:", now.day) print("Hour:", now.hour) print("Minute:", now.minute) print("Second:", now.second) ``` --- ### 🕓 5️⃣ Formatting Dates & Times ```python formatted_date = now.strftime("%Y-%m-%d") formatted_time = now.strftime("%H:%M:%S") formatted_datetime = now.strftime("%d-%b-%Y %I:%M %p") print("Formatted Date:", formatted_date) print("Formatted Time:", formatted_time) print("Formatted Date and Time:", formatted_datetime) ``` 📘 Example: `%Y` = Year, `%m` = Month, `%d` = Day, `%H` = Hour, `%M` = Minute, `%S` = Second, `%p` = AM/PM --- ### 🔁 6️⃣ Parsing Strings into Dates ```python from datetime import datetime date_string = "16-02-2024 14:30" parsed_date = datetime.strptime(date_string, "%d-%m-%Y %H:%M") print("Parsed Date and Time:", parsed_date) ``` --- ### ⏳ 7️⃣ Date and Time Arithmetic ```python from datetime import timedelta from datetime import date, datetime today = date.today() now = datetime.now() future_date = today + timedelta(days=7) past_date = today - timedelta(days=3) future_time = now + timedelta(hours=2) print("Date after 7 days:", future_date) print("Date 3 days ago:", past_date) print("Time after 2 hours:", future_time) ``` --- ✨ **In short:** - `date` → handles calendar dates - `time` → handles time only - `datetime` → combines both - `timedelta` → does date/time math 💬 What’s the most common date format you use in your projects? #Python #100DaysOfCode #PythonProgramming #LearningPython #DateTime
"Mastering Date and Time in Python with datetime Module"
More Relevant Posts
-
🚀 Day 35 of #100DaysOfPython – Working with Date, Time & Calendar 🕒📅 Today’s topic helps us retrieve and manipulate the current date, time, and calendar using Python’s built-in modules — time and calendar. 🕐 1️⃣ Retrieving the Current Time Python provides the time() and localtime() functions to get system time. import time lt = time.localtime(time.time()) print(lt) 🧩 Output example: time.struct_time(tm_year=2022, tm_mon=4, tm_mday=14, tm_hour=10, tm_min=30, ...) 🔹 Attributes of time.struct_time: tm_year → Current year tm_mon → Current month tm_mday → Day of month tm_hour → Hour tm_min → Minute tm_sec → Second tm_wday → Weekday tm_yday → Day of year tm_isdst → Daylight saving flag 🕓 2️⃣ Formatted Time with asctime() The asctime() method returns the current time as a formatted string. import time lt = time.asctime(time.localtime(time.time())) print(lt) ✅ Example Output: Thu Apr 14 10:33:59 2022 🧮 3️⃣ Converting String to Time – strptime() Used to parse strings into time structures. import time tr = time.strptime("26 jun 14", "%d %b %y") print(tr) 📖 Example Output: time.struct_time(tm_year=2014, tm_mon=6, tm_mday=26, ...) 🧭 4️⃣ Formatting Time – strftime() Converts time into a specific string format. import time t = (2014, 6, 26, 17, 3, 38, 1, 48, -1) t = time.mktime(t) print(time.strftime("%d %m %y %H:%M:%S", time.gmtime(t))) ✅ Output: 26 06 14 11:33:38 📆 5️⃣ Python Calendar Module The calendar module allows working with dates, months, and years. import calendar print(calendar.prcal(2023)) 🧠 Common Calendar Functions: Method Description prcal(year) Prints full calendar for a year firstweekday() Returns first weekday (default Monday = 0) isleap(year) Checks if year is leap monthcalendar(year, month) Returns matrix of weeks in month leapdays(y1, y2) Counts leap years between y1 and y2 prmonth(year, month) Prints specific month 🗓️ Example: import calendar print(calendar.isleap(2020)) # True print(calendar.monthcalendar(2022, 6)) calendar.prmonth(2022, 5) ✨ In Short: time → retrieves and formats time strptime / strftime → convert between strings & time calendar → helps print and analyze calendars 💬 Which one do you use most often — datetime, time, or calendar? #Python #100DaysOfCode #LearningPython #PythonProgramming #DateTime #Calendar
To view or add a comment, sign in
-
# Paste this into a Python environment (Python 3.8+). No external internet needed. # Replace CIPHER with the exact ciphertext string (digits or letters). import math from collections import Counter, defaultdict import itertools import random # ------------------------- CIPHER = "PASTE_CIPHERTEXT_HERE" # <-- replace this with the D'Agapeyeff ciphertext # ------------------------- # Basic normalization text_raw = "".join(CIPHER.strip().split()) # If digits, keep digits and maybe split into pairs/triples; if letters, uppercase letters only. is_digit = all(ch.isdigit() for ch in text_raw) is_alpha = all(ch.isalpha() for ch in text_raw) def split_digits(text, group=2): return [text[i:i+group] for i in range(0,len(text),group)] def freq_stats(s): c = Counter(s) total = len(s) freqs = [(ch, count, count/total) for ch,count in c.most_common()] return freqs print("Raw length:", len(text_raw)) print("All digits?", is_digit, "All letters?", is_alpha) if is_digit: for g in (1,2,3): groups = split_digits(text_raw, g) print(f"\nGrouping by {g} -> {len(groups)} tokens. Sample:", groups[:20]) print("Frequencies:", freq_stats(groups)[:10]) else: letters = [c.upper() for c in text_raw if c.isalpha()] print("\nLetter sample:", "".join(letters[:80])) print("Letter frequencies:", freq_stats(letters)[:20]) # compute Index of Coincidence N = len(letters) ic = sum(v*(v-1) for v in Counter(letters).values()) / (N*(N-1)) if N>1 else 0 print("Index of Coincidence:", ic) # ------------------------- # Quick Vigenere bruteforce using english quadgram scoring # ------------------------- # Quadgram statistics small sample (for speed). For best results replace with a full quadgram table. quadgrams = { 'TION': 1.0, 'THER':0.9, 'HERE':0.8, 'MENT':0.7, 'ENTH':0.6, # not exhaustive } def score_text_quads(s): s = "".join(ch for ch in s.upper() if ch.isalpha()) score = 0.0 for i in range(len(s)-3): w = s[i:i+4] score += math.log10(quadgrams.get(w, 0.01)) return score def vigenere_decrypt(ct, key): res = [] ki = 0 for ch in ct: if ch.isalpha(): offset = ord('A') k = ord(key[ki%len(key)].upper())-offset p = chr((ord(ch.upper())-offset - k) % 26 + offset) res.append(p) ki += 1 else: res.append(ch) return "".join(res) def try_vigenere(ct, max_keylen=10): ct_letters = "".join(ch for ch in ct.upper() if ch.isalpha()) best = [] for klen in range(1, max_keylen+1): for key_candidate in itertools.product("ABCDEFGHIJKLMNOPQRSTUVWXYZ", repeat=klen): key = "".join(key_candidate) pt = vigenere_decrypt(ct_letters, Had to remove some of the code due to 3000 word limit 🥺🤔🤐🥴 having a nerd 🤓 moment. Things are different 🤫
To view or add a comment, sign in
-
Dictionaries in Python: The Pantry Labels of Your Code 🏷️ Your pantry has so many items — but how do you find things easily? You don’t just dump everything in boxes — you label them! “Sugar → 1kg” “Milk → 2 packets” “Coffee → 500g” That’s what Dictionaries in Python do - they store data as key–value pairs, just like labeled jars in your kitchen! 💡 What is a Dictionary? A dictionary helps you store and access data using names (keys) instead of positions. Think of it like this: Instead of saying “Give me the 3rd item”, you can say “Give me the sugar!” 📘 Example: pantry = { "Sugar": "1kg", "Milk": "2 packets", "Coffee": "500g" } Now, if you want to check what’s in your pantry: print(pantry) Output: {'Sugar': '1kg', 'Milk': '2 packets', 'Coffee': '500g'} 💬 Accessing Items You can get values by using their key names: print(pantry["Sugar"]) Output: 1kg Easy, right? No need to remember the position - just ask for the label! 🧠 Updating or Adding Items Refill something or add new stock: pantry["Sugar"] = "2kg" # update existing pantry["Tea"] = "1 box" # add new print(pantry) Output: {'Sugar': '2kg', 'Milk': '2 packets', 'Coffee': '500g', 'Tea': '1 box'} 💥 Removing Items You can remove an item once it’s finished: del pantry["Coffee"] print(pantry) Output: {'Sugar': '2kg', 'Milk': '2 packets', 'Tea': '1 box'} 💡 Why Dictionaries Are Powerful ✅ Easy to find data using names ✅ Data stays organized and readable ✅ Perfect for real-world applications - like storing user info, product details, etc. 🧠 Today’s takeaway: “Dictionaries are like labeled jars — they help you find exactly what you need without confusion!” 💬 Try this today: Create a dictionary with your favorite fruits and their colors 🍎 Then print each fruit with its color using: for fruit, color in fruits.items(): print(fruit, "is", color) #PythonWithKeshav #LearnPython #PythonBasics #CodingJourney #PythonDictionaries #ProgrammingForBeginners #PythonLearning #CodeSmart #STEMEducation #PythonForAll
To view or add a comment, sign in
-
### 🧠 **Day 48 – Python OOPs: Private, Protected, and Class Method Concepts** Today I learned how to use **private and protected variables** in Python classes and how **name mangling** helps access them safely. #### 🧩 **Code Summary** ```python class cl_new: def __init__(self, name, age): self.__name = name # Private variable self._age = age # Protected variable def m_new(self): print(f"name = {self.__name}, age = {self._age}") @classmethod def m_cl_ndth(cls, name, age): return cls(name, age) def m_2(self): self.__m_new() # Call private method internally # Object 1 n = cl_new("siva", 27) n._cl_new__m_new() # Access private method via name mangling print(n._cl_new__name) # Access private variable using mangling print(n._age) # Object 2 n2 = cl_new("krishna", 45) n2.m_new() # Class method usage prxy = cl_new.m_cl_ndth("pawan", 60) prxy.m_new() # Object 3 n3 = cl_new("kalyan", 20) n3.m_new() ``` --- ### 🧾 **Concepts Explained** #### 🔒 1. **Private Variables (`__var`)** * Declared with **double underscores (`__`)**. * Not directly accessible outside the class. * Accessed only using **name mangling** like: ```python object._ClassName__variable ``` * Example: `self.__name` #### 🛡️ 2. **Protected Variables (`_var`)** * Declared with a **single underscore (`_`)**. * Accessible within the class and subclasses, but **should not** be accessed directly from outside (by convention). * Example: `self._age` #### 🧩 3. **Private Methods** * Methods declared with `__` prefix. * Example: `__m_new()` * Can be accessed inside the class or externally using name mangling. #### 🧠 4. **Class Method** * Declared using `@classmethod` decorator. * Takes `cls` as the first parameter. * Used to create new objects using alternative constructors. --- ### 🖥️ **Output Explanation** ``` name = siva, age = 27 name = siva, age = 27 siva 27 name = krishna, age = 45 name = pawan, age = 60 name = kalyan, age = 20 ``` ✅ Demonstrates how to define and access private/protected members. ✅ Shows **class method** usage for creating objects dynamically. ✅ Explains **encapsulation**, one of the main OOPs principles. --- ### 💡 **Key Takeaway** Encapsulation in Python ensures data hiding and protects object integrity. Using **private, protected, and class methods**, we can control access to class data efficiently. --- ✨ Every day brings a deeper understanding of Object-Oriented Programming with Python! #Python #OOPs #Encapsulation #Day48 #LearningJourney #Programming #LinkedInLearning #ClassMethod #PrivateVariables
To view or add a comment, sign in
-
Top Five python tricks 1. Multiple Assignment & Swapping Variables # Instead of: a = 1 b = 2 c = 3 # Do this: a, b, c = 1, 2, 3 # Swap variables without temp variable x, y = 10, 20 x, y = y, x # Now x=20, y=10 # Unpacking iterables first, *middle, last = [1, 2, 3, 4, 5] print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5 2. List Comprehensions with Conditions # Instead of: squares = [] for i in range(10): if i % 2 == 0: squares.append(i**2) # Do this: squares = [i**2 for i in range(10) if i % 2 == 0] # More complex example: result = [x.upper() for x in ['hello', 'world', 'python'] if len(x) > 4] print(result) # ['HELLO', 'WORLD', 'PYTHON'] 3. The zip() Function for Parallel Iteration # Iterate over multiple lists simultaneously names = ['Alice', 'Bob', 'Charlie'] scores = [85, 92, 78] subjects = ['Math', 'Science', 'English'] for name, score, subject in zip(names, scores, subjects): print(f"{name} scored {score} in {subject}") # Create dictionary from two lists score_dict = dict(zip(names, scores)) print(score_dict) # {'Alice': 85, 'Bob': 92, 'Charlie': 78} 4. enumerate() for Index-Value Pairs # Instead of: fruits = ['apple', 'banana', 'cherry'] for i in range(len(fruits)): print(f"Index {i}: {fruits[i]}") # Do this: for i, fruit in enumerate(fruits): print(f"Index {i}: {fruit}") # With custom start index for i, fruit in enumerate(fruits, start=1): print(f"#{i}: {fruit}") 5. Dictionary Comprehensions & Merging # Create dictionary from list names = ['Alice', 'Bob', 'Charlie'] name_lengths = {name: len(name) for name in names} print(name_lengths) # {'Alice': 5, 'Bob': 3, 'Charlie': 7} # Merge dictionaries (Python 3.9+) dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4} # For older Python versions: merged = {**dict1, **dict2}
To view or add a comment, sign in
-
#!/usr/bin/env python3 """ KonomiML Markdown Runner - Execute Python code blocks from markdown files """ import os import re import sys import tempfile import subprocess from pathlib import Path def extract_code_block(markdown_file: Path) -> str: """Extract Python code block from markdown file""" if not markdown_file.exists(): raise FileNotFoundError(f"Markdown file not found: {markdown_file}") with open(markdown_file, 'r', encoding='utf-8') as f: content = f.read() # Find Python code blocks pattern = r'```python\s*\n(.*?)\n```' matches = re.findall(pattern, content, re.DOTALL) if not matches: raise ValueError(f"No Python code blocks found in {markdown_file.name}") # Return the first (main) code block return matches[0] def run_markdown_program(markdown_file: Path, args: list = None): """Run Python code from markdown file""" try: # Extract code block code_block = extract_code_block(markdown_file) # Create temporary file with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as temp_file: temp_file.write(code_block) temp_file_path = temp_file.name # Prepare command cmd = [sys.executable, temp_file_path] if args: cmd.extend(args) # Set environment env = os.environ.copy() docs_path = Path(__file__).parent root_path = docs_path.parent env['PYTHONPATH'] = f"{docs_path}:{root_path}:{env.get('PYTHONPATH', '')}" # Execute result = subprocess.run( cmd, cwd=str(docs_path), env=env ) # Clean up os.unlink(temp_file_path) return result.returncode except Exception as e: print(f"Error running markdown program: {e}") return 1 def main(): """Main function""" if len(sys.argv) < 2: print("Usage: python run_markdown.py <markdown_file> [args...]") return 1 markdown_file = Path(sys.argv[1]) args = sys.argv[2:] if len(sys.argv) > 2 else [] # If file doesn't have .md extension, add it if not markdown_file.suffix: markdown_file = markdown_file.with_suffix('.md') # Make path relative to docs directory if needed if not markdown_file.is_absolute(): docs_path = Path(__file__).parent markdown_file = docs_path / markdown_file return run_markdown_program(markdown_file, args) if __name__ == "__main__": sys.exit(main())
To view or add a comment, sign in
-
-
I use Cursor agents and the IDE everyday. I started this summer and have not looked back. I've been a fan of VS Code, so the transition was easy for me (Cursor is a fork of VS code). I primarily use it for .ipynb files for research topics and python applications/.exe's. Couple things I've learned: Context and prompts are the fundamentals. Context for me means taking bits and pieces of code from stuff that already works and directing the agent towards that code. Prompting means taking the time to think and explain what I need via voice or typing (win+H, or Cursor’s voice feature). Context explainers in my prompts sometimes look like: "𝘜𝘴𝘦 𝘭𝘪𝘯𝘦𝘴 2411-2512 𝘪𝘯 𝘦𝘹𝘢𝘮𝘱𝘭𝘦.𝘱𝘺 𝘵𝘰 𝘤𝘳𝘦𝘢𝘵𝘦 𝘢 𝘴𝘪𝘮𝘪𝘭𝘢𝘳 𝘦𝘭𝘦𝘮𝘦𝘯𝘵 𝘴𝘵𝘢𝘳𝘵𝘪𝘯𝘨 𝘢𝘵 𝘭𝘪𝘯𝘦 3456 𝘪𝘯 𝘢𝘱𝘱.𝘱𝘺" In my experience, the best predictor of success is if you understand what the agent needs to do in the code before letting it loose and are able to convey that information in the prompt. I think the human's prompt creation is similar to recognizing the type of problem in a Leetcode puzzle. There’s an aha moment: “Oh, this is a binary tree problem.” If you don’t recognize the type of problem and a path forward, there is absolutely no guarantee the agent will know (sometimes it does, sometimes it doesn’t) An example prompt thread from last week: “𝘜𝘴𝘦 𝘢 𝘱𝘺𝘵𝘩𝘰𝘯 𝘴𝘤𝘳𝘪𝘱𝘵 𝘵𝘰 𝘳𝘦𝘢𝘥 𝘵𝘩𝘦 @Tx_1_Rx_4_E_Field.csv 𝘱𝘩𝘢𝘴𝘦 𝘰𝘧 𝘵𝘩𝘦 𝘌𝘻 𝘤𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵 𝘢𝘯𝘥 𝘱𝘭𝘰𝘵 𝘪𝘵 𝘴𝘪𝘥𝘦 𝘣𝘺 𝘴𝘪𝘥𝘦 𝘸𝘪𝘵𝘩 𝘵𝘩𝘦 𝘱𝘩𝘢𝘴𝘦 𝘰𝘧 𝘵𝘩𝘦 𝘌𝘻 𝘢𝘧𝘵𝘦𝘳 𝘱𝘩𝘢𝘴𝘦 𝘶𝘯𝘸𝘳𝘢𝘱𝘱𝘪𝘯𝘨.” “𝘰𝘬 𝘨𝘳𝘦𝘢𝘵 𝘵𝘩𝘢𝘵 𝘸𝘰𝘳𝘬𝘦𝘥, 𝘯𝘰𝘸 𝘐 𝘩𝘢𝘷𝘦 𝘵𝘸𝘰 𝘴𝘦𝘵𝘴 𝘰𝘧 𝘥𝘢𝘵𝘢: 𝘛𝘩𝘦 𝘰𝘳𝘪𝘨𝘪𝘯𝘢𝘭 @Tx_1_Rx_4_E_Field.csv 𝘸𝘩𝘪𝘤𝘩 𝘪𝘴 𝘵𝘩𝘦 1 m 𝘴𝘱𝘢𝘤𝘪𝘯𝘨 𝘢𝘯𝘥 𝘵𝘩𝘦𝘯 @Tx_1_Rx_2_E_Field.csv 𝘸𝘩𝘪𝘤𝘩 𝘪𝘴 2 m 𝘴𝘱𝘢𝘤𝘪𝘯𝘨. 𝘱𝘭𝘰𝘵 𝘵𝘩𝘦𝘴𝘦 𝘵𝘰𝘨𝘦𝘵𝘩𝘦𝘳 𝘪𝘯 𝘵𝘩𝘦 𝘴𝘢𝘮𝘦 1x2 𝘱𝘭𝘰𝘵, 𝘧𝘪𝘳𝘴𝘵 𝘵𝘩𝘦 𝘰𝘳𝘪𝘨𝘪𝘯𝘢𝘭 𝘸𝘳𝘢𝘱𝘱𝘦𝘥 𝘢𝘯𝘥 𝘵𝘩𝘦𝘯 𝘵𝘩𝘦 𝘶𝘯𝘸𝘳𝘢𝘱𝘱𝘦𝘥.” “𝘰𝘬 𝘭𝘦𝘵𝘴 𝘥𝘰 𝘢 2x2 𝘱𝘭𝘰𝘵 𝘪𝘯𝘴𝘵𝘦𝘢𝘥 𝘣𝘦𝘤𝘢𝘶𝘴𝘦 𝘵𝘩𝘦 𝘹 𝘢𝘹𝘪𝘴 𝘪𝘴 𝘯𝘰𝘵 𝘲𝘶𝘪𝘵𝘦 𝘢𝘭𝘪𝘨𝘯𝘦𝘥.” This is a relatively simple example but this took maybe 2 minutes to generate and about 30 seconds for me to read and confirm it was applying numpy.unwrap to my data (which I could have explicitly mentioned). I sent this plot to a customer to explain why the phase data looked strange in Remcom's Wireless InSite simulation. The data simply needed to be unwrapped and sampled at a higher resolution. Now the time I would have taken to write code to read the .csv was spent on other more interesting tasks! Disclaimer: I am not sponsored by Cursor, but wish I was. #AI #Cursor #Agents #drama Remcom
To view or add a comment, sign in
-
-
🧮 NumPy Logic Building: Practice Session 🙋♀️ Since I am started with NumPy, it is crucial to understand its concepts manually. Therefore, I have started NumPy practice sessions from today where i will be building logic and practically solving NumPy problems in each session. 👉 The best way to practice a new skill, is not directly making projects. You rather start with: 1️⃣ Quizzes 2️⃣ Exercises/Pactice Questions 3️⃣ Logic Building Exercises 4️⃣ Syntax Practice 🤔 What's Next? 👉 Once ur comfortable with the concepts, pick a dataset and apply NumPy that u have learnt on it 🤔 This is how u can not only recognize the patterns but also work with real-world data in form of NumPy projects (for instance, data cleaning/preprocessing, data analyzing, applying arithmetical ops on data, and much more) 🤔 Should u be ashamed of ERRORS? 👉 The answer is NO! Be as shameless as u can if u want to learn and unlock a new skill. Be consistent on making errors so that u can recognize the patterns on the way! ‼️I won't be showcasing practice sessions in my captions instead, i would be dropping them in the comments, so that anyone who wants to practice NumPy concepts can use my practice sessions easily 🫡 Until we meet again, my fellow coders! ------------------------- ☺️ Here are Python (Beginner to Intermediate) GitHub Repos for you: 📁Python Variables: https://lnkd.in/e9rjz-_D 📁Python Operators: https://lnkd.in/e6hzgHSn 📁Python Conditionals: https://lnkd.in/egQNGZBF 📁Python Loops: https://lnkd.in/eezUg_-y 📁Python Functions: https://lnkd.in/eKdU6nex 📁Python Lists & Tuples: https://lnkd.in/eZ8KiQNs 📁Python Dictionaries & Sets: https://lnkd.in/eDmgj7pc 📁Python OOP: https://lnkd.in/eJFupCiK 📁Python DSAs: https://lnkd.in/ebR3rjkt ------------------------- 📊 Data Science For Beginners 🤓 NumPy (Beginner To Intermediate): 🧮 1. Arrays: https://lnkd.in/ebghYRYE 💻 2. Coders Of Delhi Project: https://lnkd.in/eRYc9j63 ------------------------- ⚡ Follow my learning journey: 📎 GitHub: https://lnkd.in/ehu8wX85 🔗 GitLab: https://lnkd.in/eiiQP2gw 💬 Feedback: I’d love your thoughts and tips! 🤝 Collab: If you’re also exploring Python, DM me! Let’s grow together! -------------------------- 📞Book A Call With Me: https://lnkd.in/e23BtnR9 -------------------------- #numpy #python #pythonfordatascience #numpylogic #pythonforbeginners #numpyforbeginners #datascience #datacleaning #datanalyzing
To view or add a comment, sign in
-
File Handling in Python: Saving Your Coffee Recipes 📁☕ Imagine creating the perfect coffee recipe today… but tomorrow you forget the steps! 😅 Wouldn’t it be great if you could save your recipes for later? That’s exactly what file handling does in Python - it helps you store and retrieve information whenever you want. 💾 🗂️ Reading & Writing Files In Python, you can easily create, write, and read files using the open() function. ✍️ Writing to a File file = open("recipes.txt", "w") # 'w' means write file.write("Latte = Coffee + Milk + Sugar\n") file.write("Espresso = Strong Coffee ☕\n") file.close() print("Recipes saved!") ✅ This creates a file called recipes.txt and writes inside it. 📖 Reading from a File file = open("recipes.txt", "r") # 'r' means read content = file.read() file.close() print("Your saved recipes:\n", content) ✅ Output: Your saved recipes: Latte = Coffee + Milk + Sugar Espresso = Strong Coffee ☕ 🔄 Modes in File Handling ->r - Read filew ->w - Write (overwrites old data) ->a - Append (adds new data) ->r+ - Read & write 🧠 Why It’s Important Saves data permanently Used in data analysis, web apps, and AI logs Helps automate real-world tasks Think of it as your digital recipe book - Python helps you write, store, and reuse your ideas anytime! 💡 💬 Try this today: Write a program that saves your favorite drink to a file and prints it back. #PythonWithKeshav #LearnPython #PythonBasics #FileHandling #CodingJourney #ProgrammingForBeginners #PythonForAll #Automation #STEMEducation #PythonLearning
To view or add a comment, sign in
-
🧮 Dissecting NumPy: Working With Intrinsic NumPy Objects For Array Creation 💪 It feels really exciting getting into the core of NumPy and seeing it unlocking its true strength infront of me! 🤔 Why NumPy Arrays Are Better Than Python Lists? - Fast Computation Of Large Datasets - Dont Require Loops - Easy Arithmetical Operations - Consume Less Memory ⚙️Today i digged a bit deeper into NumPy Array Creation With Intrinsic Objects like: - np.ones/np.zeros: gives arrays of 1s and 0s - np.arange(): gives a sequence of array unlike python range() that gives integers - np.linspace(): gives equally linear numbers in array between a start and stop value - np.reshape(): it can simply reshape a given array without changing its data, means generates a new array with a different number of rows and columns (as specified) But, listen up! ‼️One critical thing about NumPy Arrays is their Axis0(rows) and Axis1(coulums). ‼️It means we can perform some of the arithmetical ops on row elements and colum elements using their axis 💭 Its been a productive week by far getting into the world of NumPy and unlocking a new skill on the way of becoming a data scientist! 🫡 Until we meet again, my fellow coders! ------------------------- ☺️ Here are Python (Beginner to Intermediate) GitHub Repos for you: 📁Python Variables: https://lnkd.in/e9rjz-_D 📁Python Operators: https://lnkd.in/e6hzgHSn 📁Python Conditionals: https://lnkd.in/egQNGZBF 📁Python Loops: https://lnkd.in/eezUg_-y 📁Python Functions: https://lnkd.in/eKdU6nex 📁Python Lists & Tuples: https://lnkd.in/eZ8KiQNs 📁Python Dictionaries & Sets: https://lnkd.in/eDmgj7pc 📁Python OOP: https://lnkd.in/eJFupCiK 📁Python DSAs: https://lnkd.in/ebR3rjkt ------------------------- 🤓 NumPy (Beginner To Intermediate): 🧮Arrays: https://lnkd.in/ebghYRYE ------------------------- ⚡ Follow my learning journey: 📎 GitHub: https://lnkd.in/ehu8wX85 🔗 GitLab: https://lnkd.in/eiiQP2gw 💬 Feedback: I’d love your thoughts and tips! 🤝 Collab: If you’re also exploring Python, DM me! Let’s grow together! -------------------------- 📞Book A Call With Me: https://lnkd.in/e23BtnR9 -------------------------- #pythonnumpy #NumPy #pythonlibraries #pythonfordatascience #datascience #machinelearning #artificialintelligence
To view or add a comment, sign in
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