PYTHON JOURNEY - Day 37 / 50..!! TOPIC – Python Dictionaries Today I explored Dictionaries — one of the most powerful and widely used data structures in Python. Unlike lists, dictionaries store data in Key:Value pairs! 1. Creating a Dictionary Think of it like a real-life dictionary: you look up a Word (Key) to find its Meaning (Value). Python student = { "name": "Srikanth", "course": "Python", "day": 37 } print(student["name"]) # Output: Srikanth 2. Adding & Updating Data Dictionaries are mutable, meaning you can change them easily. Python # Adding a new key-value pair student["status"] = "Learning" # Updating an existing value student["day"] = 38 3. Dictionary Methods Useful ways to extract information from your dictionary. Python print(student.keys()) # Gets all keys print(student.values()) # Gets all values print(student.items()) # Gets both in pairs Why Use Dictionaries? Fast Lookups: You don't need to know the index; just the name of the key. Organized Data: Perfect for representing real-world objects (like a user profile or a product's details). Readable: It makes your code look much more intuitive. Mini Task Write a program that: Creates a dictionary for a Smartphone (Brand, Model, and Price). Updates the price of the phone. Adds a new key called "Color". Prints the final dictionary using an f-string. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
Python Dictionaries: Key-Value Pairs and Data Storage
More Relevant Posts
-
PYTHON JOURNEY - Day 46 / 50..!! TOPIC – Python Modules Today I explored Modules — a way to organize code into separate files and use pre-written code from Python’s massive library. It’s like having a giant toolbox where you only pick the tools you need! 1. Importing Built-in Modules Python comes with many "batteries included" modules. To use them, we simply use the import keyword. Python import math print(math.sqrt(64)) # Output: 8.0 print(math.pi) # Output: 3.14159... 2. Using the random Module Perfect for games or selecting random data. Python import random options = ["Rock", "Paper", "Scissors"] print(random.choice(options)) # Picks a random item print(random.randint(1, 10)) # Random number between 1 and 10 3. Using alias and from You can give a module a nickname or import only a specific part of it to save memory. Python import datetime as dt from math import factorial print(dt.datetime.now()) print(factorial(5)) # Output: 120 Why Use Modules? Efficiency: Don't reinvent the wheel! Use proven code written by experts. Organization: Keep your project files clean by separating logic. Power: Modules allow Python to do everything from web scraping to Data Science and AI. Mini Task Write a program that: Imports the random module. Creates a list called players = ["Alice", "Bob", "Charlie", "David"]. Uses random.choice() to pick a random "Winner" from the list. Prints: "And the winner is... <name>! #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 34 / 50..!! TOPIC – Python Lists (Basics) Today I explored Lists in Python — a powerful way to store multiple items in a single variable. 1. Creating a List Python fruits = ["Apple", "Banana", "Cherry"] print(fruits) 2. Accessing Items (Indexing) Python starts counting at 0! Python fruits = ["Apple", "Banana", "Cherry"] print(fruits[0]) # Output: Apple print(fruits[-1]) # Output: Cherry (Last item) 3. Adding & Removing Items Python fruits.append("Orange") # Adds to the end fruits.remove("Banana") # Removes specific item print(fruits) Why Use Lists? Keep related data organized They are "mutable" (you can change them after creation) Can hold different data types (Strings, Integers, etc.) Mini Task Write a program that: Creates a list of your 3 favorite movies. Adds one more movie to the list using .append(). Prints the first movie and the total length of the list using len(). #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 47 / 50..!! TOPIC – List Comprehensions Today I explored one of Python’s most "elegant" features — List Comprehensions. It’s a shorthand way to create new lists based on existing ones, turning 4 lines of code into just 1! 1. The Traditional Way vs. Comprehension Normally, to create a list of squares, you’d need a for loop and .append(). With comprehension, it’s a single line! Python # Traditional Way nums = [1, 2, 3] squares = [] for x in nums: squares.append(x * x) # List Comprehension (The Pythonic Way) squares = [x * x for x in nums] print(squares) # Output: [1, 4, 9] 2. Adding a Condition (The if part) You can filter items while creating the list. Python prices = [10, 55, 80, 25, 100] # Only keep prices over 50 expensive = [p for p in prices if p > 50] print(expensive) # Output: [55, 80, 100] 3. String Manipulation It works perfectly for transforming text data too. Python names = ["srikanth", "python", "dev"] capitalized = [n.capitalize() for n in names] print(capitalized) # Output: ['Srikanth', 'Python', 'Dev'] Why Use List Comprehensions? Readability: Once you learn the syntax, it's much easier to read at a glance. Performance: They are generally faster than standard for-loops for creating lists. Professional: It is a hallmark of "Pythonic" code—showing you really know the language! Mini Task Write a program that: Creates a list of numbers from 1 to 10. Uses List Comprehension to create a new list containing only the even numbers. Prints the resulting list. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 36 / 50..!! TOPIC – Python Tuples Today I explored Tuples — the "reliable cousin" of the list. While they look similar, they have one major difference that makes them special! 1. Creating a Tuple Tuples use parentheses () instead of square brackets. Python coordinates = (10.5, 20.0) colors = ("Red", "Green", "Blue") print(colors) 2. The Golden Rule: Immutability Once a tuple is created, you cannot change, add, or remove its items. This makes them "read-only." Python # This will cause an ERROR: # colors[0] = "Yellow" 3. Packing and Unpacking A cool Python feature where you can assign tuple values to multiple variables at once! Python point = (5, 10) x, y = point # Unpacking print(f"X: {x}, Y: {y}") Why Use Tuples? Safety: Use them for data that should never change (like GPS coordinates or constants). Speed: Tuples are slightly faster than lists in terms of performance. Integrity: Prevents accidental data modification in larger programs. Mini Task Write a program that: Creates a tuple containing the name of a country and its capital city. Try to change the capital city and observe the TypeError. Unpack the tuple into two variables: country and capital, and print them. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
Day 461: 8/1/2026 Why Python Strings Are Immutable? Python strings cannot be modified after creation. At first glance, this feels restrictive — but immutability is a deliberate design choice with important performance and correctness benefits. Let’s break down why Python does this. ⚙️ 1. Immutability Enables Safe Hashing Strings are commonly used as: --> dictionary keys --> set elements --> For this to work reliably, their hash value must never change. If strings were mutable: --> changing a string would change its hash --> dictionary lookups would break --> internal hash tables would become inconsistent By making strings immutable: --> the hash can be computed once --> cached inside the object --> reused safely for O(1) lookups This is a foundational guarantee for Python’s data structures. 🔐 2. Immutability Makes Strings Thread-Safe Immutable objects: --> cannot be modified --> can be shared freely across threads --> require no locks or synchronization This simplifies Python’s memory model and avoids subtle concurrency bugs. Even in multi-threaded environments, the same string object can be reused safely without defensive copying. 🚀 3. Enables Memory Reuse and Optimizations Because strings never change, Python can: --> reuse string objects internally --> safely share references --> avoid defensive copies Example: --> multiple variables can point to the same string --> no risk that one modification affects another This reduces: --> memory usage --> allocation overhead --> unnecessary copying 🧠 4. Predictable Performance Characteristics Immutability allows Python to store: --> string length --> hash value --> directly inside the object. As a result: --> len(s) is O(1) --> hashing is fast after the first computation --> slicing and iteration don’t need recomputation --> This predictability improves performance across many operations. Stay tuned for more AI insights! 😊 #Python #Programming #Performance #MemoryManagement
To view or add a comment, sign in
-
Python with Machine Learning — Chapter 9 📘 Topic: Python Class 🔍 Today, we're diving into a core concept: the Python Class. Think of a class as a blueprint for creating objects. It helps us organize our code in a clean, reusable way—like a recipe for making cookies! 🍪 **Why it matters in real-world learning:** In machine learning and data science, classes help us structure complex models and data pipelines. They make our code modular and easier to debug. Learning this now builds a strong foundation for advanced topics later. You've got this! 💪 **Constructor: Your Object's First Step** A constructor is a special method inside a class that runs automatically when you create a new object. Its job is to set up the object's initial state—like adding ingredients when you bake a cookie. In Python, the constructor is always named `__init__`. Let's see a simple example: [CODE] class Cookie: def __init__(self, flavor, color): self.flavor = flavor # Attribute set by constructor self.color = color print(f"A new {self.color} {self.flavor} cookie is ready!") # Create a cookie object choco_cookie = Cookie("chocolate", "brown") [/CODE] Here, `__init__` takes parameters `flavor` and `color` and assigns them to the object's attributes using `self`. When we create `choco\_cookie`, the constructor runs and prints a welcome message. Key takeaway: Every class can have one `__init__` constructor to initialize objects. It's your go-to tool for setting up data. Practice this in your code! Try creating your own class. Share your thoughts or questions below—I'm here to guide you. 🚀 #Python #MachineLearning #Beginners #Coding
To view or add a comment, sign in
-
✅ Python Conditional Statement Quiz Answers 🧠 Quiz 1: What will this code print? python x = 15 if x> 10: print("A") elif x> 5: print("B") else: print("C") Answer: A Explanation: The first condition `x> 10` is `True`, so it prints `"A"` and skips the rest. 🧠 Quiz 2: Which operator checks if two values are equal? Answer: B. `==` Explanation: `==` checks for equality. `=` is used for assignment. 🧠 Quiz 3: What is the output of this code? python a = 5 b = 10 if a> b: print("a is greater") else: print("b is greater") Answer: B. b is greater Explanation: Since `5> 10` is `False`, it goes to the `else` block. 🧠 Quiz 4: Which of the following is a correct way to check if a number is divisible by both 3 and 5? Answer: C. `if num % 3 == 0 and num % 5 == 0:` Explanation: This checks both conditions correctly using the `and` logical operator. 🧠 Quiz 5: What is the mistake in this code? python age = 17 if age>= 18 print("Adult") Answer: B. Missing colon after `if` Explanation: Python requires a colon `:` at the end of `if` statements.
To view or add a comment, sign in
-
🐍 Python in 60 Seconds — Day 5 User Input & Typecasting This is where Python starts talking back to you 😄 🧑💻 Getting input from the user name = input("Enter your name: ") Let’s say the user types: World print("Hello", name) → Hello, World ⚠️ Important rule (memorise this) input() always returns a string even if numeric data is inputed . Example: x = input("Enter a number: ") print(x + x) Input: 5 Output: 55 ❗ Why? Because "5" + "5" is text joining, not math. 🔄 Typecasting (telling Python what you mean) Typecasting means converting one data type into another. To turn user input into numbers: age = int(input("Enter your age: ")) height = float(input("Enter your height: ")) Now Python knows these are numbers, not text. ➕ Now Python can do math print(age + 1) ✅ This works Because age is an int, not a string. ❌ Common beginner mistake age = input("Enter your age: ") print(age + 1) → Error 🚫 Python won’t guess what you want. You must be explicit. 💡 Insight Python is flexible — but not psychic 🧠 You decide what a value means. Consistency beats motivation. Next: Typecasting in depth #Python #LearnPython #Programming #Coding #TechCareers #DataScience #10DaysOfCode
To view or add a comment, sign in
-
-
Python Loops & Iterations: Loops are the backbone of automation and data processing in Python. 🔁 1. for Loop — Iterate Over a List Use for when you want to loop through items one by one. nums = [1, 2, 3, 4, 5] for num in nums: print(num) ⛔ 2. break — Exit the Loop Immediately Stops the loop as soon as a condition is met. nums = [10, 20, 30, 40, 50] for num in nums: if num == 40: print("Target hit! Exiting loop") break print(num) ⏭️ 3. continue — Skip Current Iteration Skips the rest of the loop for that iteration. for num in range(1, 11): if num % 2 != 0: continue print(f"Even → {num}") 🔂 4. Nested Loops — Loop Inside Another Loop Common in tables, combinations, and comparisons. for i in [2, 3, 4]: for j in range(1, 6): print(f"{i} × {j} = {i * j}") 🔢 5. range() — Numeric Iteration Perfect for counting and stepping through numbers. for i in range(5, 16): print(i) for i in range(0, 51, 5): print(i) 🔄 6. While Loop — Repeat While Condition Is True Best when the number of iterations is unknown. count = 8 while count > 0: print(f"T-minus {count}...") count -= 1 print("Launch!") ♾️ 7. Infinite Loop + break — Controlled Exit A powerful pattern for user input and games. secret = 6 while True: guess = int(input("Guess (1-10): ")) if guess == secret: print("Perfect! You got it!") break elif guess < secret: print("Too low!") else: print("Too high!") #Python
To view or add a comment, sign in
More from this author
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