What will be the output of the following Python code?
```python
text = " Hello World! " result = text.strip().lower().replace("world", "python") print(result) ```
```python
text = " Hello World! " result = text.strip().lower().replace("world", "python") print(result) ```
Anonymous Quiz
100%
hello python!
0%
Hello Python!
0%
hello python!
0%
hello world!
Here's your Telegram post and quiz!
---
🎉 **Python Learning Series - Day 10: File I/O (Input/Output)** 🎉
Time to level up! 🚀 On Day 10, we're diving into *File I/O* in Python. No more just printing to the console – now you can store and retrieve data persistently! We'll learn how to `open`, `read`, `write`, and manage files safely using the `with` statement. Get ready to make your programs remember! 💾📝
```python
# --- Day 10: File I/O ---
# 1. Writing to a file (mode 'w' - write, overwrites existing file)
# The 'with' statement ensures the file is automatically closed.
with open("my_notes.txt", "w") as file:
file.write("Hello from Day 10!n")
file.write("Python file I/O is fun. 😊n")
file.write("This is a new line.n")
print("Data written to my_notes.txt")
# 2. Reading from a file (mode 'r' - read)
print("n--- Reading file content ---")
with open("my_notes.txt", "r") as file:
content = file.read() # Reads the entire file content
print(content)
# 3. Appending to a file (mode 'a' - append, adds to the end)
with open("my_notes.txt", "a") as file:
file.write("This line was appended later. ✨n")
print("Data appended to my_notes.txt")
# 4. Reading again to see the appended content
print("n--- Reading file content after append ---")
with open("my_notes.txt", "r") as file:
print(file.read())
```
Output example:
```
Data written to my_notes.txt
--- Reading file content ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
Data appended to my_notes.txt
--- Reading file content after append ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
This line was appended later. ✨
```
---
💡 **Small Challenge:**
Can you write a Python script that asks the user for 3 different shopping list items and then saves each item to a file named `shopping_list.txt`, with each item on a new line? (Hint: Use a loop and input()!)
---
---
🎉 **Python Learning Series - Day 10: File I/O (Input/Output)** 🎉
Time to level up! 🚀 On Day 10, we're diving into *File I/O* in Python. No more just printing to the console – now you can store and retrieve data persistently! We'll learn how to `open`, `read`, `write`, and manage files safely using the `with` statement. Get ready to make your programs remember! 💾📝
```python
# --- Day 10: File I/O ---
# 1. Writing to a file (mode 'w' - write, overwrites existing file)
# The 'with' statement ensures the file is automatically closed.
with open("my_notes.txt", "w") as file:
file.write("Hello from Day 10!n")
file.write("Python file I/O is fun. 😊n")
file.write("This is a new line.n")
print("Data written to my_notes.txt")
# 2. Reading from a file (mode 'r' - read)
print("n--- Reading file content ---")
with open("my_notes.txt", "r") as file:
content = file.read() # Reads the entire file content
print(content)
# 3. Appending to a file (mode 'a' - append, adds to the end)
with open("my_notes.txt", "a") as file:
file.write("This line was appended later. ✨n")
print("Data appended to my_notes.txt")
# 4. Reading again to see the appended content
print("n--- Reading file content after append ---")
with open("my_notes.txt", "r") as file:
print(file.read())
```
Output example:
```
Data written to my_notes.txt
--- Reading file content ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
Data appended to my_notes.txt
--- Reading file content after append ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
This line was appended later. ✨
```
---
💡 **Small Challenge:**
Can you write a Python script that asks the user for 3 different shopping list items and then saves each item to a file named `shopping_list.txt`, with each item on a new line? (Hint: Use a loop and input()!)
---
What is the primary benefit of using the `with open(...) as file:` statement when working with files in Python?
Anonymous Quiz
0%
A. It automatically creates the file if it doesn't exist, regardless of the mode.
0%
B. It ensures the file is automatically closed, even if errors occur.
0%
C. It allows writing to binary files without explicit encoding.
100%
D. It makes file operations significantly faster.
Hey Python Learners! 👋 Ready to make your code bulletproof? 🛡️ Today is Day 11, and we're diving into *Error Handling* with `try` and `except`! 🐛 No one likes a crashing program. Learning to anticipate and gracefully handle errors means your scripts can recover instead of stopping dead in their tracks. Let's write robust code that users will love! ✨
```python
print("--- Python Error Handling ---")
def calculate_division(numerator, denominator):
try:
# Code that might raise an exception
result = float(numerator) / float(denominator)
except ZeroDivisionError:
# Handles specific error: division by zero
print("🚫 Error: Cannot divide by zero!")
return None
except ValueError:
# Handles specific error: non-numeric input for float conversion
print("🔢 Error: Please enter valid numbers for calculation.")
return None
except Exception as e:
# Catches any other unexpected errors
print(f"❌ An unexpected error occurred: {e}")
return None
else:
# Code runs ONLY if no exceptions occurred in the try block
print(f"✅ Division successful! Result: {result}")
return result
finally:
# Code runs ALWAYS, regardless of success or failure
print("➡️ Division attempt concluded.")
# --- Test Cases ---
print("n--- Test 1: Valid Division ---")
calculate_division(10, 2)
print("n--- Test 2: Division by Zero ---")
calculate_division(10, 0)
print("n--- Test 3: Invalid Input (string) ---")
calculate_division("ten", 2)
print("n--- Test 4: Another Valid Division ---")
calculate_division(25, 4)
```
Output example:
```
--- Python Error Handling ---
--- Test 1: Valid Division ---
✅ Division successful! Result: 5.0
➡️ Division attempt concluded.
--- Test 2: Division by Zero ---
🚫 Error: Cannot divide by zero!
➡️ Division attempt concluded.
--- Test 3: Invalid Input (string) ---
🔢 Error: Please enter valid numbers for calculation.
➡️ Division attempt concluded.
--- Test 4: Another Valid Division ---
✅ Division successful! Result: 6.25
➡️ Division attempt concluded.
```
💡 **Challenge Time!**
Modify the `calculate_division` function to also handle a `TypeError` specifically if you try to pass an object type that cannot be converted to `float` (e.g., `calculate_division([1,2], 2)`). Where would you place this new `except` block? 🤔 Share your thoughts or code snippets!
```python
print("--- Python Error Handling ---")
def calculate_division(numerator, denominator):
try:
# Code that might raise an exception
result = float(numerator) / float(denominator)
except ZeroDivisionError:
# Handles specific error: division by zero
print("🚫 Error: Cannot divide by zero!")
return None
except ValueError:
# Handles specific error: non-numeric input for float conversion
print("🔢 Error: Please enter valid numbers for calculation.")
return None
except Exception as e:
# Catches any other unexpected errors
print(f"❌ An unexpected error occurred: {e}")
return None
else:
# Code runs ONLY if no exceptions occurred in the try block
print(f"✅ Division successful! Result: {result}")
return result
finally:
# Code runs ALWAYS, regardless of success or failure
print("➡️ Division attempt concluded.")
# --- Test Cases ---
print("n--- Test 1: Valid Division ---")
calculate_division(10, 2)
print("n--- Test 2: Division by Zero ---")
calculate_division(10, 0)
print("n--- Test 3: Invalid Input (string) ---")
calculate_division("ten", 2)
print("n--- Test 4: Another Valid Division ---")
calculate_division(25, 4)
```
Output example:
```
--- Python Error Handling ---
--- Test 1: Valid Division ---
✅ Division successful! Result: 5.0
➡️ Division attempt concluded.
--- Test 2: Division by Zero ---
🚫 Error: Cannot divide by zero!
➡️ Division attempt concluded.
--- Test 3: Invalid Input (string) ---
🔢 Error: Please enter valid numbers for calculation.
➡️ Division attempt concluded.
--- Test 4: Another Valid Division ---
✅ Division successful! Result: 6.25
➡️ Division attempt concluded.
```
💡 **Challenge Time!**
Modify the `calculate_division` function to also handle a `TypeError` specifically if you try to pass an object type that cannot be converted to `float` (e.g., `calculate_division([1,2], 2)`). Where would you place this new `except` block? 🤔 Share your thoughts or code snippets!
What is the primary purpose of the `else` block in a `try-except-else-finally` construct in Python?
Anonymous Quiz
100%
A. To execute code only if an exception occurred in the `try` block.
0%
B. To execute code regardless of whether an exception occurred or not.
0%
C. To define the code that might raise an exception.
0%
D. To execute code only if no exceptions occurred in the `try` block.
Here's your Telegram post and quiz question!
---
🚀 Day 12 is here, Pythonistas! Today, we're unlocking the power of **Python Modules and Packages**! 📦✨
No more monolithic scripts! Modules help us organize our code into reusable files, making our projects cleaner, more manageable, and incredibly efficient. Think of them as toolboxes you can bring into any project. Let's dive in and see how easy it is to bring external functionality into your projects! 👇
```python
# --- my_module.py ---
# This file acts as our custom module
PI = 3.14159
def greet(name):
"""Greets a user."""
return f"Hello, {name}! Welcome to our module."
def add(a, b):
"""Adds two numbers."""
return a + b
def multiply(a, b):
"""Multiplies two numbers."""
return a * b
# --- main_app.py ---
# This file imports and uses functions/variables from my_module.py
# Make sure both files are in the same directory!
import my_module
from my_module import add, PI as MY_PI_VALUE # Can rename imported items
print("--- Using 'import my_module' ---")
message = my_module.greet("Alice")
print(message)
print(f"PI from my_module: {my_module.PI}")
print(f"Product of 4 and 6: {my_module.multiply(4, 6)}")
print("n--- Using 'from my_module import ...' ---")
sum_result = add(10, 5) # No need for my_module.add
print(f"Sum of 10 and 5: {sum_result}")
print(f"PI (renamed import): {MY_PI_VALUE}")
# You can even see what's inside a module!
print("n--- Items in my_module after import (top 5) ---")
print([item for item in dir(my_module) if not item.startswith('__')][:5])
```
Output example:
```
--- Using 'import my_module' ---
Hello, Alice! Welcome to our module.
PI from my_module: 3.14159
Product of 4 and 6: 24
--- Using 'from my_module import ...' ---
Sum of 10 and 5: 15
PI (renamed import): 3.14159
--- Items in my_module after import (top 5) ---
['PI', 'add', 'greet', 'multiply']
```
**Challenge Time! 🧠**
Create a new Python file called `string_helpers.py`. Inside it, define two functions:
1. `reverse_string(text)`: Returns the input string reversed.
2. `is_palindrome(text)`: Returns `True` if the string is a palindrome (reads the same forwards and backward, ignoring case), `False` otherwise.
Then, in your `main_app.py` (or a new file), import these functions and test them with a few strings! Share your solutions! 👇
---
---
🚀 Day 12 is here, Pythonistas! Today, we're unlocking the power of **Python Modules and Packages**! 📦✨
No more monolithic scripts! Modules help us organize our code into reusable files, making our projects cleaner, more manageable, and incredibly efficient. Think of them as toolboxes you can bring into any project. Let's dive in and see how easy it is to bring external functionality into your projects! 👇
```python
# --- my_module.py ---
# This file acts as our custom module
PI = 3.14159
def greet(name):
"""Greets a user."""
return f"Hello, {name}! Welcome to our module."
def add(a, b):
"""Adds two numbers."""
return a + b
def multiply(a, b):
"""Multiplies two numbers."""
return a * b
# --- main_app.py ---
# This file imports and uses functions/variables from my_module.py
# Make sure both files are in the same directory!
import my_module
from my_module import add, PI as MY_PI_VALUE # Can rename imported items
print("--- Using 'import my_module' ---")
message = my_module.greet("Alice")
print(message)
print(f"PI from my_module: {my_module.PI}")
print(f"Product of 4 and 6: {my_module.multiply(4, 6)}")
print("n--- Using 'from my_module import ...' ---")
sum_result = add(10, 5) # No need for my_module.add
print(f"Sum of 10 and 5: {sum_result}")
print(f"PI (renamed import): {MY_PI_VALUE}")
# You can even see what's inside a module!
print("n--- Items in my_module after import (top 5) ---")
print([item for item in dir(my_module) if not item.startswith('__')][:5])
```
Output example:
```
--- Using 'import my_module' ---
Hello, Alice! Welcome to our module.
PI from my_module: 3.14159
Product of 4 and 6: 24
--- Using 'from my_module import ...' ---
Sum of 10 and 5: 15
PI (renamed import): 3.14159
--- Items in my_module after import (top 5) ---
['PI', 'add', 'greet', 'multiply']
```
**Challenge Time! 🧠**
Create a new Python file called `string_helpers.py`. Inside it, define two functions:
1. `reverse_string(text)`: Returns the input string reversed.
2. `is_palindrome(text)`: Returns `True` if the string is a palindrome (reads the same forwards and backward, ignoring case), `False` otherwise.
Then, in your `main_app.py` (or a new file), import these functions and test them with a few strings! Share your solutions! 👇
---
Here's your Telegram post for Day 13 of the Python learning series:
---
🚀 **Day 13: Object-Oriented Programming (Classes and Objects)** 🏗️
Ready to build more organized and reusable Python code? Today, we're diving into the powerful world of Object-Oriented Programming (OOP)! 💡
Think of a **class** as a blueprint – a design for creating something. An **object** is then an actual item built from that blueprint. We'll learn how to define classes, create objects (instances), and give them attributes (data) and methods (functions that perform actions). This concept is fundamental to writing clean, scalable, and maintainable applications! Let's get started! 👇
```python
# Define a simple class called 'Dog'
class Dog:
# The __init__ method is a constructor. It's called when a new object is created.
# 'self' refers to the instance of the class itself.
def __init__(self, name, breed, age):
self.name = name # Assign arguments to instance attributes
self.breed = breed
self.age = age
# A method (function) that belongs to the Dog class
def bark(self):
return f"{self.name} says Woof! Woof!"
# Another method to display dog's info
def display_info(self):
return f"This is {self.name}, a {self.age}-year-old {self.breed}."
# Create objects (instances) of the Dog class
my_dog = Dog("Buddy", "Golden Retriever", 3)
your_dog = Dog("Lucy", "Beagle", 2)
# Access attributes of the objects
print(f"My dog's name: {my_dog.name}")
print(f"Your dog's breed: {your_dog.breed}")
# Call methods on the objects
print(my_dog.bark())
print(your_dog.display_info())
```
Output example:
```
My dog's name: Buddy
Your dog's breed: Beagle
Buddy says Woof! Woof!
This is Lucy, a 2-year-old Beagle.
```
🐾 **Small Challenge:**
Add another method to the `Dog` class, like `celebrate_birthday()`, which increments the dog's `age` attribute and prints a celebratory message! Try calling it for `my_dog`! 🎉
---
---
🚀 **Day 13: Object-Oriented Programming (Classes and Objects)** 🏗️
Ready to build more organized and reusable Python code? Today, we're diving into the powerful world of Object-Oriented Programming (OOP)! 💡
Think of a **class** as a blueprint – a design for creating something. An **object** is then an actual item built from that blueprint. We'll learn how to define classes, create objects (instances), and give them attributes (data) and methods (functions that perform actions). This concept is fundamental to writing clean, scalable, and maintainable applications! Let's get started! 👇
```python
# Define a simple class called 'Dog'
class Dog:
# The __init__ method is a constructor. It's called when a new object is created.
# 'self' refers to the instance of the class itself.
def __init__(self, name, breed, age):
self.name = name # Assign arguments to instance attributes
self.breed = breed
self.age = age
# A method (function) that belongs to the Dog class
def bark(self):
return f"{self.name} says Woof! Woof!"
# Another method to display dog's info
def display_info(self):
return f"This is {self.name}, a {self.age}-year-old {self.breed}."
# Create objects (instances) of the Dog class
my_dog = Dog("Buddy", "Golden Retriever", 3)
your_dog = Dog("Lucy", "Beagle", 2)
# Access attributes of the objects
print(f"My dog's name: {my_dog.name}")
print(f"Your dog's breed: {your_dog.breed}")
# Call methods on the objects
print(my_dog.bark())
print(your_dog.display_info())
```
Output example:
```
My dog's name: Buddy
Your dog's breed: Beagle
Buddy says Woof! Woof!
This is Lucy, a 2-year-old Beagle.
```
🐾 **Small Challenge:**
Add another method to the `Dog` class, like `celebrate_birthday()`, which increments the dog's `age` attribute and prints a celebratory message! Try calling it for `my_dog`! 🎉
---
What is a 'class' in Object-Oriented Programming (OOP)?
Anonymous Quiz
0%
A specific instance of an object.
0%
A blueprint or a template for creating objects.
100%
A function that performs an action on an object.
0%
The data stored inside an object.
🚀 Day 14 of our Python journey is here! Today, we're diving into the powerful concepts of *Inheritance* and *Polymorphism*. 🐍 Inheritance allows us to build new classes based on existing ones, reusing code and creating a clear hierarchy. Polymorphism, on the other hand, lets objects of different classes be treated as objects of a common type, responding to the same method calls in their own unique ways. Get ready to write more organized and flexible code! ✨
```python
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return "Generic animal sound"
def describe(self):
return f"I am a {self.__class__.__name__} named {self.name}."
class Dog(Animal): # Inheritance: Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name) # Call parent's constructor
self.breed = breed
def make_sound(self): # Polymorphism: Overriding parent method
return "Woof! Woof!"
def fetch(self):
return f"{self.name} is fetching the ball!"
class Cat(Animal): # Inheritance: Cat inherits from Animal
def __init__(self, name, color):
super().__init__(name)
self.color = color
def make_sound(self): # Polymorphism: Overriding parent method
return "Meow!"
def scratch(self):
return f"{self.name} is scratching the couch."
# Demonstrating Inheritance and Polymorphism
print("--- Inheritance Example ---")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.describe()) # Inherited method
print(my_dog.make_sound()) # Overridden method
print(my_dog.fetch()) # Dog's specific method
my_cat = Cat("Whiskers", "Tabby")
print(my_cat.describe()) # Inherited method
print(my_cat.make_sound()) # Overridden method
print(my_cat.scratch()) # Cat's specific method
print("n--- Polymorphism Example ---")
animals = [
Dog("Max", "German Shepherd"),
Cat("Bella", "Siamese"),
Animal("Unknown Creature") # An instance of the base class
]
for animal in animals:
print(f"{animal.name} says: {animal.make_sound()}")
```
Output example:
```
--- Inheritance Example ---
I am a Dog named Buddy.
Woof! Woof!
Buddy is fetching the ball!
I am a Cat named Whiskers.
Meow!
Whiskers is scratching the couch.
--- Polymorphism Example ---
Max says: Woof! Woof!
Bella says: Meow!
Unknown Creature says: Generic animal sound
```
**Small Challenge:**
Can you create another animal class, like `Bird`, that inherits from `Animal` and overrides the `make_sound` method? Add an instance of your `Bird` to the `animals` list and observe the polymorphic behavior! 🐦
```python
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return "Generic animal sound"
def describe(self):
return f"I am a {self.__class__.__name__} named {self.name}."
class Dog(Animal): # Inheritance: Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name) # Call parent's constructor
self.breed = breed
def make_sound(self): # Polymorphism: Overriding parent method
return "Woof! Woof!"
def fetch(self):
return f"{self.name} is fetching the ball!"
class Cat(Animal): # Inheritance: Cat inherits from Animal
def __init__(self, name, color):
super().__init__(name)
self.color = color
def make_sound(self): # Polymorphism: Overriding parent method
return "Meow!"
def scratch(self):
return f"{self.name} is scratching the couch."
# Demonstrating Inheritance and Polymorphism
print("--- Inheritance Example ---")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.describe()) # Inherited method
print(my_dog.make_sound()) # Overridden method
print(my_dog.fetch()) # Dog's specific method
my_cat = Cat("Whiskers", "Tabby")
print(my_cat.describe()) # Inherited method
print(my_cat.make_sound()) # Overridden method
print(my_cat.scratch()) # Cat's specific method
print("n--- Polymorphism Example ---")
animals = [
Dog("Max", "German Shepherd"),
Cat("Bella", "Siamese"),
Animal("Unknown Creature") # An instance of the base class
]
for animal in animals:
print(f"{animal.name} says: {animal.make_sound()}")
```
Output example:
```
--- Inheritance Example ---
I am a Dog named Buddy.
Woof! Woof!
Buddy is fetching the ball!
I am a Cat named Whiskers.
Meow!
Whiskers is scratching the couch.
--- Polymorphism Example ---
Max says: Woof! Woof!
Bella says: Meow!
Unknown Creature says: Generic animal sound
```
**Small Challenge:**
Can you create another animal class, like `Bird`, that inherits from `Animal` and overrides the `make_sound` method? Add an instance of your `Bird` to the `animals` list and observe the polymorphic behavior! 🐦
Here's your Telegram post for Day 15 of your Python learning series!
---
🚀 Day 15: Dive into Python Libraries! 📚 Today, we're unlocking the power of external modules by introducing you to the incredible `requests` library! 🌐 Ever wanted to fetch data from the internet or interact with web APIs? `requests` makes it super easy and intuitive. Say goodbye to complex HTTP handling and hello to elegant web interactions! Let's get started with our first web request!
```python
import requests
# Make a GET request to a placeholder API
# This fetches data for post with ID 1
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(f"Status Code: {response.status_code}")
print(f"Content-Type: {response.headers['content-type']}") # Access specific header
print("Response JSON:")
print(response.json()) # Print the JSON content as a Python dictionary
```
Output example:
```
Status Code: 200
Content-Type: application/json; charset=utf-8
Response JSON:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto'}
```
💡 **Your Challenge:**
Modify the code to make a `GET` request to `https://api.ipify.org?format=json` and print *only* your public IP address from the JSON response. Hint: The response will be a dictionary, and you'll need to access a specific key! 🕵️♀️
---
---
🚀 Day 15: Dive into Python Libraries! 📚 Today, we're unlocking the power of external modules by introducing you to the incredible `requests` library! 🌐 Ever wanted to fetch data from the internet or interact with web APIs? `requests` makes it super easy and intuitive. Say goodbye to complex HTTP handling and hello to elegant web interactions! Let's get started with our first web request!
```python
import requests
# Make a GET request to a placeholder API
# This fetches data for post with ID 1
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(f"Status Code: {response.status_code}")
print(f"Content-Type: {response.headers['content-type']}") # Access specific header
print("Response JSON:")
print(response.json()) # Print the JSON content as a Python dictionary
```
Output example:
```
Status Code: 200
Content-Type: application/json; charset=utf-8
Response JSON:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto'}
```
💡 **Your Challenge:**
Modify the code to make a `GET` request to `https://api.ipify.org?format=json` and print *only* your public IP address from the JSON response. Hint: The response will be a dictionary, and you'll need to access a specific key! 🕵️♀️
---
What is the primary purpose of the `requests` library in Python?
Anonymous Quiz
0%
Performing complex mathematical calculations
50%
Building graphical user interfaces (GUIs)
0%
Making HTTP requests to web servers (e.g., GET, POST, PUT)
50%
Managing local file system operations
Hey Python Learners! 👋
It's Day 16, and we're unlocking the power of the internet! 🌐 Today, we're diving into **Working with APIs (Application Programming Interfaces)**. Ever wondered how apps get real-time data like weather, stock prices, or news? It's often through APIs! Python makes it incredibly easy to interact with these services using the `requests` library. Get ready to fetch data from the web like a pro! 🚀 Let's make our Python scripts communicate with the world! ✨
```python
import requests
# Define the API endpoint we want to access
# This is a public API for placeholder data
url = "https://jsonplaceholder.typicode.com/todos/1"
print(f"Making a GET request to: {url}")
try:
# Make a GET request to the API
response = requests.get(url)
# Check if the request was successful (status code 200 means OK)
if response.status_code == 200:
# Parse the JSON response into a Python dictionary
todo_item = response.json()
print("nSuccessfully fetched data! ✅")
print(f"Item ID: {todo_item['id']}")
print(f"User ID: {todo_item['userId']}")
print(f"Title: {todo_item['title']}")
print(f"Completed: {todo_item['completed']}")
else:
print(f"nError fetching data. Status code: {response.status_code}")
print(f"Response text: {response.text}")
except requests.exceptions.RequestException as e:
print(f"nAn error occurred during the request: {e}")
```
Output example:
```
Making a GET request to: https://jsonplaceholder.typicode.com/todos/1
Successfully fetched data! ✅
Item ID: 1
User ID: 1
Title: delectus aut autem
Completed: False
```
### Your Small Challenge! 👇
Can you modify the code to fetch a different resource? Try changing the `url` to `"https://jsonplaceholder.typicode.com/posts/2"` and print out the `title` and `body` of that post. What do you get? Share your results! 💡
---
It's Day 16, and we're unlocking the power of the internet! 🌐 Today, we're diving into **Working with APIs (Application Programming Interfaces)**. Ever wondered how apps get real-time data like weather, stock prices, or news? It's often through APIs! Python makes it incredibly easy to interact with these services using the `requests` library. Get ready to fetch data from the web like a pro! 🚀 Let's make our Python scripts communicate with the world! ✨
```python
import requests
# Define the API endpoint we want to access
# This is a public API for placeholder data
url = "https://jsonplaceholder.typicode.com/todos/1"
print(f"Making a GET request to: {url}")
try:
# Make a GET request to the API
response = requests.get(url)
# Check if the request was successful (status code 200 means OK)
if response.status_code == 200:
# Parse the JSON response into a Python dictionary
todo_item = response.json()
print("nSuccessfully fetched data! ✅")
print(f"Item ID: {todo_item['id']}")
print(f"User ID: {todo_item['userId']}")
print(f"Title: {todo_item['title']}")
print(f"Completed: {todo_item['completed']}")
else:
print(f"nError fetching data. Status code: {response.status_code}")
print(f"Response text: {response.text}")
except requests.exceptions.RequestException as e:
print(f"nAn error occurred during the request: {e}")
```
Output example:
```
Making a GET request to: https://jsonplaceholder.typicode.com/todos/1
Successfully fetched data! ✅
Item ID: 1
User ID: 1
Title: delectus aut autem
Completed: False
```
### Your Small Challenge! 👇
Can you modify the code to fetch a different resource? Try changing the `url` to `"https://jsonplaceholder.typicode.com/posts/2"` and print out the `title` and `body` of that post. What do you get? Share your results! 💡
---
Which Python library is commonly used for making HTTP requests to interact with web APIs?
Anonymous Quiz
0%
requests
0%
urllib
100%
http.client
0%
socket