What will be the output of the following Python code?
```python
text = "Hello, World!" new_text = text.replace("World", "Python").replace("!", "!!!") print(new_text) ```
```python
text = "Hello, World!" new_text = text.replace("World", "Python").replace("!", "!!!") print(new_text) ```
Anonymous Quiz
0%
Hello, Python!
0%
Hello, Python!!!
0%
Hello, World!!!
0%
Hello, Python
🎉 *Day 10: Unlocking File I/O in Python!* 📂
Ever wondered how to save data beyond your program's runtime? Today, we're diving into **File Input/Output (I/O)**! You'll learn to read from, write to, and append data in files using Python. It's crucial for logging, data persistence, and so much more. We'll use the `open()` function and the super handy `with` statement for safe file handling. Get ready to make your programs remember! ✍️
```python
import os
# Define file name
file_name = 'my_notes.txt'
# --- Writing to a file (will create if not exists, overwrite if exists) ---
print("--- Writing to 'my_notes.txt' ---")
with open(file_name, 'w') as file:
file.write("Python File I/O is fun!n")
file.write("This is the first line written.n")
file.write("And this is the second line written.n")
print("Content written successfully.n")
# --- Appending to a file (will add to the end) ---
print("--- Appending to 'my_notes.txt' ---")
with open(file_name, 'a') as file:
file.write("Appending new content here.n")
file.write("Don't forget the newline character for new lines!n")
print("Content appended successfully.n")
# --- Reading from a file (reads entire content) ---
print("--- Reading 'my_notes.txt' (Full Content) ---")
with open(file_name, 'r') as file:
full_content = file.read() # Reads the entire file as a single string
print("nFull Content:n", full_content)
# --- Reading from a file line by line ---
print("--- Reading 'my_notes.txt' (Line by Line) ---")
with open(file_name, 'r') as file:
print("nContent Line by Line:")
for line in file: # Iterates over lines in the file
print(f"Line: {line.strip()}") # .strip() removes trailing newline characters
# Optional: Clean up the created file
# os.remove(file_name)
# print(f"n'{file_name}' has been removed.")
```
Output example:
```
--- Writing to 'my_notes.txt' ---
Content written successfully.
--- Appending to 'my_notes.txt' ---
Content appended successfully.
--- Reading 'my_notes.txt' (Full Content) ---
Full Content:
Python File I/O is fun!
This is the first line written.
And this is the second line written.
Appending new content here.
Don't forget the newline character for new lines!
--- Reading 'my_notes.txt' (Line by Line) ---
Content Line by Line:
Line: Python File I/O is fun!
Line: This is the first line written.
Line: And this is the second line written.
Line: Appending new content here.
Line: Don't forget the newline character for new lines!
```
💡 **Small Challenge:**
Modify the reading part of the code to:
1. Read only the **first 3 lines** of `my_notes.txt` using `readlines()`.
2. Count how many lines in the file contain the word "line" (case-insensitive).
Share your solutions or questions below! 👇
---
Ever wondered how to save data beyond your program's runtime? Today, we're diving into **File Input/Output (I/O)**! You'll learn to read from, write to, and append data in files using Python. It's crucial for logging, data persistence, and so much more. We'll use the `open()` function and the super handy `with` statement for safe file handling. Get ready to make your programs remember! ✍️
```python
import os
# Define file name
file_name = 'my_notes.txt'
# --- Writing to a file (will create if not exists, overwrite if exists) ---
print("--- Writing to 'my_notes.txt' ---")
with open(file_name, 'w') as file:
file.write("Python File I/O is fun!n")
file.write("This is the first line written.n")
file.write("And this is the second line written.n")
print("Content written successfully.n")
# --- Appending to a file (will add to the end) ---
print("--- Appending to 'my_notes.txt' ---")
with open(file_name, 'a') as file:
file.write("Appending new content here.n")
file.write("Don't forget the newline character for new lines!n")
print("Content appended successfully.n")
# --- Reading from a file (reads entire content) ---
print("--- Reading 'my_notes.txt' (Full Content) ---")
with open(file_name, 'r') as file:
full_content = file.read() # Reads the entire file as a single string
print("nFull Content:n", full_content)
# --- Reading from a file line by line ---
print("--- Reading 'my_notes.txt' (Line by Line) ---")
with open(file_name, 'r') as file:
print("nContent Line by Line:")
for line in file: # Iterates over lines in the file
print(f"Line: {line.strip()}") # .strip() removes trailing newline characters
# Optional: Clean up the created file
# os.remove(file_name)
# print(f"n'{file_name}' has been removed.")
```
Output example:
```
--- Writing to 'my_notes.txt' ---
Content written successfully.
--- Appending to 'my_notes.txt' ---
Content appended successfully.
--- Reading 'my_notes.txt' (Full Content) ---
Full Content:
Python File I/O is fun!
This is the first line written.
And this is the second line written.
Appending new content here.
Don't forget the newline character for new lines!
--- Reading 'my_notes.txt' (Line by Line) ---
Content Line by Line:
Line: Python File I/O is fun!
Line: This is the first line written.
Line: And this is the second line written.
Line: Appending new content here.
Line: Don't forget the newline character for new lines!
```
💡 **Small Challenge:**
Modify the reading part of the code to:
1. Read only the **first 3 lines** of `my_notes.txt` using `readlines()`.
2. Count how many lines in the file contain the word "line" (case-insensitive).
Share your solutions or questions below! 👇
---
What is the primary advantage of using the `with open(...)` statement for file operations in Python?
Anonymous Quiz
0%
It automatically closes the file, even if errors occur.
100%
It makes the file read-only, preventing accidental writes.
0%
It encrypts the file content for security.
0%
It opens the file in binary mode by default.
🎉 Day 11: Error Handling (try, except) 🎉
Ever had your Python script crash unexpectedly? 💥 It's frustrating, right? Today, we're diving into *Error Handling* using `try` and `except` blocks! 🛡️
These powerful tools allow your programs to gracefully manage errors and exceptions, preventing crashes and providing a smoother user experience. Instead of stopping dead, your code can catch the error and respond intelligently. Let's make our code more robust! 💪
```python
print("--- Day 11: Error Handling (try, except) ---")
def safely_get_integer_input():
try:
# Code that might raise an error goes here
user_input = input("Please enter an integer: ")
number = int(user_input) # This might raise a ValueError
print(f"Successfully processed: {number} 🎉")
except ValueError:
# This block executes ONLY if a ValueError occurs in the 'try' block
print("Oops! That's not a valid integer. Please try again. 🤔")
except Exception as e: # A general catch-all for other unexpected errors
# This block catches any other type of error not specifically handled
print(f"An unexpected error occurred: {e} 🐛")
finally:
# The 'finally' block always executes, regardless of whether an error occurred
print("Execution of the input block finished.")
# Example 1: Successful run
print("n--- Scenario 1: Valid Input ---")
safely_get_integer_input()
# Example 2: Error run
print("n--- Scenario 2: Invalid Input ---")
safely_get_integer_input()
# A quick look at another common error type: ZeroDivisionError
print("n--- Quick Example: Division ---")
try:
result = 10 / 0 # This will raise a ZeroDivisionError
print(result)
except ZeroDivisionError:
print("Error: You tried to divide by zero! 🚫")
except Exception as e:
print(f"An unexpected error in division: {e} 😬")
```
Output example:
```
--- Day 11: Error Handling (try, except) ---
--- Scenario 1: Valid Input ---
Please enter an integer: 42
Successfully processed: 42 🎉
Execution of the input block finished.
--- Scenario 2: Invalid Input ---
Please enter an integer: hello_world
Oops! That's not a valid integer. Please try again. 🤔
Execution of the input block finished.
--- Quick Example: Division ---
Error: You tried to divide by zero! 🚫
```
### Small Challenge:
Your Challenge: Modify the `safely_get_integer_input` function to keep asking for input until a valid integer is provided. (Hint: Think about loops! 😉) Share your solution!
---
Ever had your Python script crash unexpectedly? 💥 It's frustrating, right? Today, we're diving into *Error Handling* using `try` and `except` blocks! 🛡️
These powerful tools allow your programs to gracefully manage errors and exceptions, preventing crashes and providing a smoother user experience. Instead of stopping dead, your code can catch the error and respond intelligently. Let's make our code more robust! 💪
```python
print("--- Day 11: Error Handling (try, except) ---")
def safely_get_integer_input():
try:
# Code that might raise an error goes here
user_input = input("Please enter an integer: ")
number = int(user_input) # This might raise a ValueError
print(f"Successfully processed: {number} 🎉")
except ValueError:
# This block executes ONLY if a ValueError occurs in the 'try' block
print("Oops! That's not a valid integer. Please try again. 🤔")
except Exception as e: # A general catch-all for other unexpected errors
# This block catches any other type of error not specifically handled
print(f"An unexpected error occurred: {e} 🐛")
finally:
# The 'finally' block always executes, regardless of whether an error occurred
print("Execution of the input block finished.")
# Example 1: Successful run
print("n--- Scenario 1: Valid Input ---")
safely_get_integer_input()
# Example 2: Error run
print("n--- Scenario 2: Invalid Input ---")
safely_get_integer_input()
# A quick look at another common error type: ZeroDivisionError
print("n--- Quick Example: Division ---")
try:
result = 10 / 0 # This will raise a ZeroDivisionError
print(result)
except ZeroDivisionError:
print("Error: You tried to divide by zero! 🚫")
except Exception as e:
print(f"An unexpected error in division: {e} 😬")
```
Output example:
```
--- Day 11: Error Handling (try, except) ---
--- Scenario 1: Valid Input ---
Please enter an integer: 42
Successfully processed: 42 🎉
Execution of the input block finished.
--- Scenario 2: Invalid Input ---
Please enter an integer: hello_world
Oops! That's not a valid integer. Please try again. 🤔
Execution of the input block finished.
--- Quick Example: Division ---
Error: You tried to divide by zero! 🚫
```
### Small Challenge:
Your Challenge: Modify the `safely_get_integer_input` function to keep asking for input until a valid integer is provided. (Hint: Think about loops! 😉) Share your solution!
---
What is the primary purpose of using `try` and `except` blocks in Python?
Anonymous Quiz
100%
To define a new function and its parameters.
0%
To catch and handle errors or exceptions gracefully, preventing program crashes.
0%
To create a loop that iterates over a sequence.
0%
To import external modules into a script.
🚀 **Day 12: Unlocking the Power of Python Modules & Packages!** 📦
Hello, Python learners! Today, we're diving into an essential concept that elevates your code from simple scripts to well-organized, reusable projects: **Modules and Packages**.
Think of modules as individual Python files (`.py`) containing functions, classes, and variables. They help you break down large programs into smaller, manageable pieces. Packages take this a step further, allowing you to group related modules into directories, making your project structure clean and scalable. Get ready to write more efficient and maintainable code! ✨
---
**Example Code:**
First, create a file named `my_utility.py`:
```python
# my_utility.py
def say_hello(name):
return f"Hello, {name} from my_utility!"
APP_VERSION = "1.0.0"
```
Now, create your main application file, `main_app.py`:
```python
# main_app.py
import math # Importing a built-in module
import my_utility # Importing our custom module
from my_utility import say_hello as greeting_func # Importing a specific item with an alias
print(f"Using math.pi: {math.pi}")
print(f"Accessing my_utility.APP_VERSION: {my_utility.APP_VERSION}")
print(my_utility.say_hello("Alice")) # Using the function via module name
print(greeting_func("Bob")) # Using the aliased function
print("n--- Understanding Packages ---")
print("Packages are directories containing modules and an '__init__.py' file (even if empty).")
print("They allow for hierarchical organization, e.g., 'from my_package.sub_module import func'.")
print("The '__init__.py' file signals that the directory should be treated as a Python package.")
```
---
**Output example:**
```
Using math.pi: 3.141592653589793
Accessing my_utility.APP_VERSION: 1.0.0
Hello, Alice from my_utility!
Hello, Bob from my_utility!
--- Understanding Packages ---
Packages are directories containing modules and an '__init__.py' file (even if empty).
They allow for hierarchical organization, e.g., 'from my_package.sub_module import func'.
The '__init__.py' file signals that the directory should be treated as a Python package.
```
---
💡 **Small Challenge:**
1. Create a new file named `calculations.py`.
2. Inside `calculations.py`, define a function `add(a, b)` that returns the sum of `a` and `b`.
3. Modify your `main_app.py` to import `add` from `calculations.py` and use it to print the sum of 10 and 20.
4. Can you explain *why* `__init__.py` is important for a directory to be considered a package?
---
**Quiz Question:**
Hello, Python learners! Today, we're diving into an essential concept that elevates your code from simple scripts to well-organized, reusable projects: **Modules and Packages**.
Think of modules as individual Python files (`.py`) containing functions, classes, and variables. They help you break down large programs into smaller, manageable pieces. Packages take this a step further, allowing you to group related modules into directories, making your project structure clean and scalable. Get ready to write more efficient and maintainable code! ✨
---
**Example Code:**
First, create a file named `my_utility.py`:
```python
# my_utility.py
def say_hello(name):
return f"Hello, {name} from my_utility!"
APP_VERSION = "1.0.0"
```
Now, create your main application file, `main_app.py`:
```python
# main_app.py
import math # Importing a built-in module
import my_utility # Importing our custom module
from my_utility import say_hello as greeting_func # Importing a specific item with an alias
print(f"Using math.pi: {math.pi}")
print(f"Accessing my_utility.APP_VERSION: {my_utility.APP_VERSION}")
print(my_utility.say_hello("Alice")) # Using the function via module name
print(greeting_func("Bob")) # Using the aliased function
print("n--- Understanding Packages ---")
print("Packages are directories containing modules and an '__init__.py' file (even if empty).")
print("They allow for hierarchical organization, e.g., 'from my_package.sub_module import func'.")
print("The '__init__.py' file signals that the directory should be treated as a Python package.")
```
---
**Output example:**
```
Using math.pi: 3.141592653589793
Accessing my_utility.APP_VERSION: 1.0.0
Hello, Alice from my_utility!
Hello, Bob from my_utility!
--- Understanding Packages ---
Packages are directories containing modules and an '__init__.py' file (even if empty).
They allow for hierarchical organization, e.g., 'from my_package.sub_module import func'.
The '__init__.py' file signals that the directory should be treated as a Python package.
```
---
💡 **Small Challenge:**
1. Create a new file named `calculations.py`.
2. Inside `calculations.py`, define a function `add(a, b)` that returns the sum of `a` and `b`.
3. Modify your `main_app.py` to import `add` from `calculations.py` and use it to print the sum of 10 and 20.
4. Can you explain *why* `__init__.py` is important for a directory to be considered a package?
---
**Quiz Question:**
What is the primary purpose of a Python module?
Anonymous Quiz
0%
To define classes for object-oriented programming.
0%
To store global variables for an entire application.
0%
To organize related Python code into a single, reusable file.
0%
To provide a graphical user interface for a script.
Here's your Telegram post for Day 13 of the Python learning series!
---
**Welcome to Day 13 of our Python learning journey! 🐍**
Today, we're diving into one of the most powerful and fundamental concepts: Object-Oriented Programming (OOP) with Classes and Objects! ✨ OOP allows us to structure our code by bundling data (attributes) and functions (methods) into reusable blueprints called 'classes'. Think of a class as a cookie cutter 🍪 and an object as the actual cookie. It helps model real-world entities and build robust, scalable applications. Let's create our first class! 🏗️
```python
# Define a Class named 'Dog'
class Dog:
# The __init__ method is a special method called when a new object is created.
# 'self' refers to the instance of the class being created.
def __init__(self, name, breed):
self.name = name # Assign 'name' to the object's attribute
self.breed = breed # Assign 'breed' to the object's attribute
print(f"A new dog, {self.name} the {self.breed}, has been created!")
# Define a method (a function associated with the class)
def bark(self):
return f"{self.name} says Woof! Woof!"
def describe(self):
return f"{self.name} is a friendly {self.breed}."
# Create objects (instances) of the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Labrador")
# Access attributes of the objects
print(f"nMy dog's name is {my_dog.name} and breed is {my_dog.breed}.")
print(f"Your dog's name is {your_dog.name}.")
# Call methods on the objects
print(my_dog.bark())
print(your_dog.describe())
```
**Output example:**
```
A new dog, Buddy the Golden Retriever, has been created!
A new dog, Lucy the Labrador, has been created!
My dog's name is Buddy and breed is Golden Retriever.
Your dog's name is Lucy.
Buddy says Woof! Woof!
Lucy is a friendly Labrador.
```
**Small challenge: 💪**
Modify the `Dog` class:
1. Add a new attribute `age` to the `__init__` method.
2. Add a new method `celebrate_birthday` that increments the dog's `age` and prints a happy message! 🎉
---
---
**Welcome to Day 13 of our Python learning journey! 🐍**
Today, we're diving into one of the most powerful and fundamental concepts: Object-Oriented Programming (OOP) with Classes and Objects! ✨ OOP allows us to structure our code by bundling data (attributes) and functions (methods) into reusable blueprints called 'classes'. Think of a class as a cookie cutter 🍪 and an object as the actual cookie. It helps model real-world entities and build robust, scalable applications. Let's create our first class! 🏗️
```python
# Define a Class named 'Dog'
class Dog:
# The __init__ method is a special method called when a new object is created.
# 'self' refers to the instance of the class being created.
def __init__(self, name, breed):
self.name = name # Assign 'name' to the object's attribute
self.breed = breed # Assign 'breed' to the object's attribute
print(f"A new dog, {self.name} the {self.breed}, has been created!")
# Define a method (a function associated with the class)
def bark(self):
return f"{self.name} says Woof! Woof!"
def describe(self):
return f"{self.name} is a friendly {self.breed}."
# Create objects (instances) of the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Labrador")
# Access attributes of the objects
print(f"nMy dog's name is {my_dog.name} and breed is {my_dog.breed}.")
print(f"Your dog's name is {your_dog.name}.")
# Call methods on the objects
print(my_dog.bark())
print(your_dog.describe())
```
**Output example:**
```
A new dog, Buddy the Golden Retriever, has been created!
A new dog, Lucy the Labrador, has been created!
My dog's name is Buddy and breed is Golden Retriever.
Your dog's name is Lucy.
Buddy says Woof! Woof!
Lucy is a friendly Labrador.
```
**Small challenge: 💪**
Modify the `Dog` class:
1. Add a new attribute `age` to the `__init__` method.
2. Add a new method `celebrate_birthday` that increments the dog's `age` and prints a happy message! 🎉
---
In Python, what is the primary purpose of the `__init__` method within a class?
Anonymous Quiz
0%
To define static methods that belong to the class.
0%
To initialize a new instance (object) of the class by setting its initial attributes.
0%
To destroy an object when it is no longer needed.
0%
To make a method private and inaccessible from outside the class.
🚀 Day 14 is here! Ready to unlock the power of Object-Oriented Programming? 🧱 Today, we dive deep into *Inheritance* and *Polymorphism*! Learn how to reuse code efficiently with inheritance, creating a clear "is-a" relationship between classes. Then, discover polymorphism, allowing objects of different classes to be treated through a common interface, behaving differently based on their type. Get ready to write more flexible and maintainable Python code! ✨
```python
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
# This method is intended to be overridden by subclasses
raise NotImplementedError("Subclass must implement the make_sound method")
class Dog(Animal):
def make_sound(self):
return f"{self.name} barks! Woof! Woof!"
class Cat(Animal):
def make_sound(self):
return f"{self.name} meows! Meow!"
class Duck(Animal):
def make_sound(self):
return f"{self.name} quacks! Quack! Quack!"
# Demonstrate Polymorphism: A function that can take any 'Animal' object
def animal_sound_party(animal):
print(animal.make_sound())
print("--- Animal Sounds Party! 🥳 ---")
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
my_duck = Duck("Daffy")
animal_sound_party(my_dog)
animal_sound_party(my_cat)
animal_sound_party(my_duck)
print("n--- Direct Calls ---")
print(my_dog.make_sound())
print(my_cat.make_sound())
```
Output example:
```
--- Animal Sounds Party! 🥳 ---
Buddy barks! Woof! Woof!
Whiskers meows! Meow!
Daffy quacks! Quack! Quack!
--- Direct Calls ---
Buddy barks! Woof! Woof!
Whiskers meows! Meow!
```
Small Challenge:
Challenge: Add a new class `Lion` 🦁 that inherits from `Animal` and implements its own unique `make_sound()` method. Then, add a `lion` object to our `animal_sound_party` function! Share your mighty solution! 🐾
---
```python
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
# This method is intended to be overridden by subclasses
raise NotImplementedError("Subclass must implement the make_sound method")
class Dog(Animal):
def make_sound(self):
return f"{self.name} barks! Woof! Woof!"
class Cat(Animal):
def make_sound(self):
return f"{self.name} meows! Meow!"
class Duck(Animal):
def make_sound(self):
return f"{self.name} quacks! Quack! Quack!"
# Demonstrate Polymorphism: A function that can take any 'Animal' object
def animal_sound_party(animal):
print(animal.make_sound())
print("--- Animal Sounds Party! 🥳 ---")
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
my_duck = Duck("Daffy")
animal_sound_party(my_dog)
animal_sound_party(my_cat)
animal_sound_party(my_duck)
print("n--- Direct Calls ---")
print(my_dog.make_sound())
print(my_cat.make_sound())
```
Output example:
```
--- Animal Sounds Party! 🥳 ---
Buddy barks! Woof! Woof!
Whiskers meows! Meow!
Daffy quacks! Quack! Quack!
--- Direct Calls ---
Buddy barks! Woof! Woof!
Whiskers meows! Meow!
```
Small Challenge:
Challenge: Add a new class `Lion` 🦁 that inherits from `Animal` and implements its own unique `make_sound()` method. Then, add a `lion` object to our `animal_sound_party` function! Share your mighty solution! 🐾
---
Which OOP principle allows objects of different classes to be treated as objects of a common superclass, enabling a single interface to represent different types?
Anonymous Quiz
0%
Inheritance
0%
Encapsulation
0%
Polymorphism
0%
Abstraction
Here's your Telegram post for Day 15!
---
**Day 15: Introduction to Python Libraries (requests)**
Day 15 is here! 🚀 Today, we're diving into the exciting world of Python libraries by exploring `requests`! 🌐 This powerful library makes interacting with web services and APIs incredibly easy. Forget complex built-in modules; `requests` simplifies making HTTP requests, fetching data, and much more. Get ready to connect your Python scripts to the vast internet! 💻 Let's make some web requests!
```python
import requests
# Define the URL of a public API endpoint
# This endpoint returns a sample ToDo item in JSON format
url = "https://jsonplaceholder.typicode.com/todos/1"
try:
# Make an HTTP GET request to the specified URL
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
print("Request successful! 🎉")
# Parse the JSON response
data = response.json()
print("nParsed JSON Data:")
print(f"User ID: {data['userId']}")
print(f"ID: {data['id']}")
print(f"Title: {data['title']}")
print(f"Completed: {data['completed']}")
else:
print(f"Request failed with status code: {response.status_code} 😢")
print("Response text:", response.text)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e} 💔")
```
Output example:
Request successful! 🎉
Parsed JSON Data:
User ID: 1
ID: 1
Title: delectus aut autem
Completed: False
Your Challenge: 🧠
Try changing the `url` to fetch a different ToDo item (e.g., `https://jsonplaceholder.typicode.com/todos/5`) or explore a different public API. Can you print only the `title` and `completed` status for the new item? Share your findings! 👇
---
---
**Day 15: Introduction to Python Libraries (requests)**
Day 15 is here! 🚀 Today, we're diving into the exciting world of Python libraries by exploring `requests`! 🌐 This powerful library makes interacting with web services and APIs incredibly easy. Forget complex built-in modules; `requests` simplifies making HTTP requests, fetching data, and much more. Get ready to connect your Python scripts to the vast internet! 💻 Let's make some web requests!
```python
import requests
# Define the URL of a public API endpoint
# This endpoint returns a sample ToDo item in JSON format
url = "https://jsonplaceholder.typicode.com/todos/1"
try:
# Make an HTTP GET request to the specified URL
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
print("Request successful! 🎉")
# Parse the JSON response
data = response.json()
print("nParsed JSON Data:")
print(f"User ID: {data['userId']}")
print(f"ID: {data['id']}")
print(f"Title: {data['title']}")
print(f"Completed: {data['completed']}")
else:
print(f"Request failed with status code: {response.status_code} 😢")
print("Response text:", response.text)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e} 💔")
```
Output example:
Request successful! 🎉
Parsed JSON Data:
User ID: 1
ID: 1
Title: delectus aut autem
Completed: False
Your Challenge: 🧠
Try changing the `url` to fetch a different ToDo item (e.g., `https://jsonplaceholder.typicode.com/todos/5`) or explore a different public API. Can you print only the `title` and `completed` status for the new item? Share your findings! 👇
---
What is the primary purpose of Python's 'requests' library?
Anonymous Quiz
0%
Performing complex mathematical calculations.
0%
Interacting with local file systems.
0%
Making HTTP requests to web servers and APIs.
0%
Building graphical user interfaces (GUIs).
Hey Python learners! 👋 Day 17 is here, and we're diving into the world of **JSON (JavaScript Object Notation)**! 🌐 Ever wondered how web services exchange data? Often, it's through JSON – a lightweight, human-readable format. Python makes handling JSON a breeze with its built-in `json` module. Let's learn to convert Python data structures into JSON strings and parse them back! Get ready to serialize and deserialize! 🚀
```python
import json
# A Python dictionary representing some data
person_data = {
"name": "Alice Wonderland",
"age": 30,
"isStudent": False,
"courses_taken": ["Python Basics", "Web Development"],
"contact": {
"email": "alice@example.com",
"phone": None
}
}
print("--- Original Python Dictionary ---")
print(person_data)
print(f"Type: {type(person_data)}n")
# 1. Convert Python dictionary to a JSON string (Serialization)
# The 'indent' parameter makes the output pretty-printed
json_string = json.dumps(person_data, indent=4)
print("--- Python Dictionary as JSON String ---")
print(json_string)
print(f"Type: {type(json_string)}n")
# 2. Convert JSON string back to a Python dictionary (Deserialization)
parsed_data = json.loads(json_string)
print("--- JSON String parsed back to Python Dictionary ---")
print(parsed_data)
print(f"Type: {type(parsed_data)}n")
# You can now work with the parsed_data as a regular Python dictionary
print(f"Alice's age (from parsed data): {parsed_data['age']}")
```
Output example:
```
--- Original Python Dictionary ---
{'name': 'Alice Wonderland', 'age': 30, 'isStudent': False, 'courses_taken': ['Python Basics', 'Web Development'], 'contact': {'email': 'alice@example.com', 'phone': None}}
Type: <class 'dict'>
--- Python Dictionary as JSON String ---
{
"name": "Alice Wonderland",
"age": 30,
"isStudent": false,
"courses_taken": [
"Python Basics",
"Web Development"
],
"contact": {
"email": "alice@example.com",
"phone": null
}
}
Type: <class 'str'>
--- JSON String parsed back to Python Dictionary ---
{'name': 'Alice Wonderland', 'age': 30, 'isStudent': False, 'courses_taken': ['Python Basics', 'Web Development'], 'contact': {'email': 'alice@example.com', 'phone': None}}
Type: <class 'dict'>
Alice's age (from parsed data): 30
```
### Your Challenge! 🧠
Can you modify the code to:
1. Save the `person_data` dictionary directly into a file named `user_profile.json` using `json.dump()`.
2. Then, in a separate part of your script (or a new script), load the data back from `user_profile.json` using `json.load()` and print its content?
---
```python
import json
# A Python dictionary representing some data
person_data = {
"name": "Alice Wonderland",
"age": 30,
"isStudent": False,
"courses_taken": ["Python Basics", "Web Development"],
"contact": {
"email": "alice@example.com",
"phone": None
}
}
print("--- Original Python Dictionary ---")
print(person_data)
print(f"Type: {type(person_data)}n")
# 1. Convert Python dictionary to a JSON string (Serialization)
# The 'indent' parameter makes the output pretty-printed
json_string = json.dumps(person_data, indent=4)
print("--- Python Dictionary as JSON String ---")
print(json_string)
print(f"Type: {type(json_string)}n")
# 2. Convert JSON string back to a Python dictionary (Deserialization)
parsed_data = json.loads(json_string)
print("--- JSON String parsed back to Python Dictionary ---")
print(parsed_data)
print(f"Type: {type(parsed_data)}n")
# You can now work with the parsed_data as a regular Python dictionary
print(f"Alice's age (from parsed data): {parsed_data['age']}")
```
Output example:
```
--- Original Python Dictionary ---
{'name': 'Alice Wonderland', 'age': 30, 'isStudent': False, 'courses_taken': ['Python Basics', 'Web Development'], 'contact': {'email': 'alice@example.com', 'phone': None}}
Type: <class 'dict'>
--- Python Dictionary as JSON String ---
{
"name": "Alice Wonderland",
"age": 30,
"isStudent": false,
"courses_taken": [
"Python Basics",
"Web Development"
],
"contact": {
"email": "alice@example.com",
"phone": null
}
}
Type: <class 'str'>
--- JSON String parsed back to Python Dictionary ---
{'name': 'Alice Wonderland', 'age': 30, 'isStudent': False, 'courses_taken': ['Python Basics', 'Web Development'], 'contact': {'email': 'alice@example.com', 'phone': None}}
Type: <class 'dict'>
Alice's age (from parsed data): 30
```
### Your Challenge! 🧠
Can you modify the code to:
1. Save the `person_data` dictionary directly into a file named `user_profile.json` using `json.dump()`.
2. Then, in a separate part of your script (or a new script), load the data back from `user_profile.json` using `json.load()` and print its content?
---
Which Python `json` module function is used to convert a Python dictionary into a JSON formatted *string*?
Anonymous Quiz
0%
json.load()
0%
json.dump()
0%
json.loads()
0%
json.dumps()