Which `strftime` format code would you use to get the full weekday name (e.g., "Monday", "Tuesday") from a `datetime` object?
Anonymous Quiz
0%
%d
0%
%w
0%
%A
100%
%B
β¨ Day 21: Decorators! β¨
Ready to level up your Python game? Today we dive into one of Python's most elegant and powerful features: **decorators**! π Decorators allow you to modify or enhance functions and methods without changing their core code. Think of them as wrappers that add extra functionality like logging, timing, authentication, and more. They make your code cleaner, more modular, and incredibly reusable! Let's explore how they work with a practical example. π
```python
import time
# Our simple decorator function
def timer_decorator(func):
"""
A decorator that measures the execution time of a function.
"""
def wrapper(*args, **kwargs):
start_time = time.time()
print(f"β±οΈ Starting '{func.__name__}'...")
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"β '{func.__name__}' finished in {end_time - start_time:.4f} seconds.")
return result
return wrapper
# Apply the decorator using the '@' syntax
@timer_decorator
def long_running_function(name):
"""A function that simulates some work."""
print(f"Hello, {name}! Doing some important stuff...")
time.sleep(1.5) # Simulate work for 1.5 seconds
print(f"Done with {name}'s task.")
return f"Task for {name} completed!"
print("--- Calling decorated function ---")
message = long_running_function("Alice")
print(f"Function returned: {message}n")
print("--- Another call with Bob ---")
long_running_function("Bob")
```
Output example:
```
--- Calling decorated function ---
β±οΈ Starting 'long_running_function'...
Hello, Alice! Doing some important stuff...
Done with Alice's task.
β 'long_running_function' finished in 1.5015 seconds.
Function returned: Task for Alice completed!
--- Another call with Bob ---
β±οΈ Starting 'long_running_function'...
Hello, Bob! Doing some important stuff...
Done with Bob's task.
β 'long_running_function' finished in 1.5009 seconds.
```
π‘ **Challenge:** Can you create another decorator, perhaps `log_arguments_decorator`, that prints all the arguments (`*args` and `**kwargs`) passed to the decorated function before it's executed? Apply it to `long_running_function` alongside `timer_decorator`! (Hint: you can stack decorators!). Good luck! π§
---
Ready to level up your Python game? Today we dive into one of Python's most elegant and powerful features: **decorators**! π Decorators allow you to modify or enhance functions and methods without changing their core code. Think of them as wrappers that add extra functionality like logging, timing, authentication, and more. They make your code cleaner, more modular, and incredibly reusable! Let's explore how they work with a practical example. π
```python
import time
# Our simple decorator function
def timer_decorator(func):
"""
A decorator that measures the execution time of a function.
"""
def wrapper(*args, **kwargs):
start_time = time.time()
print(f"β±οΈ Starting '{func.__name__}'...")
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"β '{func.__name__}' finished in {end_time - start_time:.4f} seconds.")
return result
return wrapper
# Apply the decorator using the '@' syntax
@timer_decorator
def long_running_function(name):
"""A function that simulates some work."""
print(f"Hello, {name}! Doing some important stuff...")
time.sleep(1.5) # Simulate work for 1.5 seconds
print(f"Done with {name}'s task.")
return f"Task for {name} completed!"
print("--- Calling decorated function ---")
message = long_running_function("Alice")
print(f"Function returned: {message}n")
print("--- Another call with Bob ---")
long_running_function("Bob")
```
Output example:
```
--- Calling decorated function ---
β±οΈ Starting 'long_running_function'...
Hello, Alice! Doing some important stuff...
Done with Alice's task.
β 'long_running_function' finished in 1.5015 seconds.
Function returned: Task for Alice completed!
--- Another call with Bob ---
β±οΈ Starting 'long_running_function'...
Hello, Bob! Doing some important stuff...
Done with Bob's task.
β 'long_running_function' finished in 1.5009 seconds.
```
π‘ **Challenge:** Can you create another decorator, perhaps `log_arguments_decorator`, that prints all the arguments (`*args` and `**kwargs`) passed to the decorated function before it's executed? Apply it to `long_running_function` alongside `timer_decorator`! (Hint: you can stack decorators!). Good luck! π§
---
What is the primary purpose of using a Python decorator?
Anonymous Quiz
0%
To define a new class.
0%
To modify or extend the behavior of a function or method without changing its source code.
0%
To handle exceptions in a try-except block.
0%
To create asynchronous functions.
π Day 22: Unlocking Python's Power with Generators & Iterators! π
Today, we're diving into two fundamental concepts that make your Python code more memory-efficient and elegant: Generators and Iterators! β¨ Learn how to create sequences on-the-fly without storing everything in memory, perfect for large datasets or infinite streams. Get ready to `yield` some amazing results! πͺ
```python
# Our simple generator function
def countdown(n):
"""A generator that counts down from n to 1."""
print(f"Starting countdown from {n}...")
while n > 0:
yield n # Pauses execution, returns n, and remembers its state
n -= 1
print("Countdown finished!")
# --- Using the generator with next() ---
print("--- Using next() on the generator ---")
my_gen = countdown(3) # Creates a generator object
print(f"First value: {next(my_gen)}")
print(f"Second value: {next(my_gen)}")
print(f"Third value: {next(my_gen)}")
# Trying to get another value would raise a StopIteration error
# --- Using the generator in a for loop ---
print("n--- Using a for loop on the generator ---")
for number in countdown(5):
print(f"Loop value: {number}")
```
Output example:
```
--- Using next() on the generator ---
Starting countdown from 3...
First value: 3
Second value: 2
Third value: 1
--- Using a for loop on the generator ---
Starting countdown from 5...
Loop value: 5
Loop value: 4
Loop value: 3
Loop value: 2
Loop value: 1
Countdown finished!
```
π‘ **Your Challenge:** Create a generator function that yields the first `N` even numbers. How would you then print only the third even number generated using `next()`? π€
---
Today, we're diving into two fundamental concepts that make your Python code more memory-efficient and elegant: Generators and Iterators! β¨ Learn how to create sequences on-the-fly without storing everything in memory, perfect for large datasets or infinite streams. Get ready to `yield` some amazing results! πͺ
```python
# Our simple generator function
def countdown(n):
"""A generator that counts down from n to 1."""
print(f"Starting countdown from {n}...")
while n > 0:
yield n # Pauses execution, returns n, and remembers its state
n -= 1
print("Countdown finished!")
# --- Using the generator with next() ---
print("--- Using next() on the generator ---")
my_gen = countdown(3) # Creates a generator object
print(f"First value: {next(my_gen)}")
print(f"Second value: {next(my_gen)}")
print(f"Third value: {next(my_gen)}")
# Trying to get another value would raise a StopIteration error
# --- Using the generator in a for loop ---
print("n--- Using a for loop on the generator ---")
for number in countdown(5):
print(f"Loop value: {number}")
```
Output example:
```
--- Using next() on the generator ---
Starting countdown from 3...
First value: 3
Second value: 2
Third value: 1
--- Using a for loop on the generator ---
Starting countdown from 5...
Loop value: 5
Loop value: 4
Loop value: 3
Loop value: 2
Loop value: 1
Countdown finished!
```
π‘ **Your Challenge:** Create a generator function that yields the first `N` even numbers. How would you then print only the third even number generated using `next()`? π€
---
What is the primary benefit of using a generator in Python compared to a function that returns a list of all elements, especially for large datasets?
Anonymous Quiz
0%
Generators are faster to write and debug.
0%
Generators store all elements in memory, making them easier to access quickly.
0%
Generators produce elements one at a time on demand, saving memory.
0%
Generators can only be used with the 'next()' function and not in 'for' loops.
π *Day 23: Context Managers (with statement)* π
Hello, Python learners! π Today, we're diving into one of Python's most elegant features for resource management: **Context Managers** using the `with` statement. Ever worry about closing files or releasing locks? The `with` statement ensures resources are properly acquired and released, even if errors occur. It makes your code cleaner, safer, and much more Pythonic! β¨ Let's explore how it simplifies resource handling.
```python
# Day 23: Context Managers (with statement)
print("--- Using 'with' for file handling ---")
# The 'with' statement ensures the file is automatically closed
# after the block, even if errors occur.
try:
with open("my_notes.txt", "w") as file:
file.write("Hello, Python learners!n")
file.write("Context managers make resource handling easy.n")
# No need for file.close() here!
print("File 'my_notes.txt' written successfully and closed automatically.")
print("n--- Reading content from 'my_notes.txt' ---")
with open("my_notes.txt", "r") as file:
content = file.read()
print(content)
print("File 'my_notes.txt' read successfully and closed automatically.")
except IOError as e:
print(f"An error occurred while handling the file: {e}")
print("--- End of demonstration ---")
```
Output example:
```
--- Using 'with' for file handling ---
File 'my_notes.txt' written successfully and closed automatically.
--- Reading content from 'my_notes.txt' ---
Hello, Python learners!
Context managers make resource handling easy.
File 'my_notes.txt' read successfully and closed automatically.
--- End of demonstration ---
```
**Small Challenge:**
How would you use a `with` statement to ensure a temporary directory is created and then automatically cleaned up after its use? (Hint: Explore the `tempfile` module in Python's standard library!) π§Ή
---
Hello, Python learners! π Today, we're diving into one of Python's most elegant features for resource management: **Context Managers** using the `with` statement. Ever worry about closing files or releasing locks? The `with` statement ensures resources are properly acquired and released, even if errors occur. It makes your code cleaner, safer, and much more Pythonic! β¨ Let's explore how it simplifies resource handling.
```python
# Day 23: Context Managers (with statement)
print("--- Using 'with' for file handling ---")
# The 'with' statement ensures the file is automatically closed
# after the block, even if errors occur.
try:
with open("my_notes.txt", "w") as file:
file.write("Hello, Python learners!n")
file.write("Context managers make resource handling easy.n")
# No need for file.close() here!
print("File 'my_notes.txt' written successfully and closed automatically.")
print("n--- Reading content from 'my_notes.txt' ---")
with open("my_notes.txt", "r") as file:
content = file.read()
print(content)
print("File 'my_notes.txt' read successfully and closed automatically.")
except IOError as e:
print(f"An error occurred while handling the file: {e}")
print("--- End of demonstration ---")
```
Output example:
```
--- Using 'with' for file handling ---
File 'my_notes.txt' written successfully and closed automatically.
--- Reading content from 'my_notes.txt' ---
Hello, Python learners!
Context managers make resource handling easy.
File 'my_notes.txt' read successfully and closed automatically.
--- End of demonstration ---
```
**Small Challenge:**
How would you use a `with` statement to ensure a temporary directory is created and then automatically cleaned up after its use? (Hint: Explore the `tempfile` module in Python's standard library!) π§Ή
---
π Day 24 is here! Today, we're diving into two incredibly powerful and Pythonic features: Lambda Functions and List Comprehensions! β¨
Lambda functions are small, anonymous functions perfect for quick, one-off operations. List comprehensions offer a super concise and readable way to create lists based on existing iterables. Master these to write cleaner, more efficient Python! π
```python
# Let's explore Lambda Functions and List Comprehensions!
# Example 1: Lambda Function with map()
# A lambda function is a small anonymous function.
# It can take any number of arguments, but can only have one expression.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(f"Squared numbers (using lambda with map): {squared_numbers}")
# Example 2: List Comprehension
# A concise way to create lists based on existing iterables.
# We'll filter for even numbers and then square them.
numbers_to_process = [10, 15, 20, 25, 30]
even_squared = [x**2 for x in numbers_to_process if x % 2 == 0]
print(f"Even numbers squared (using list comprehension): {even_squared}")
# Another example: Conditional expression in list comprehension
# Create a list of 'Even' or 'Odd' strings
parity_list = ["Even" if n % 2 == 0 else "Odd" for n in range(6)]
print(f"Parity list (using conditional comprehension): {parity_list}")
```
Output example:
```
Squared numbers (using lambda with map): [1, 4, 9, 16, 25]
Even numbers squared (using list comprehension): [100, 400, 900]
Parity list (using conditional comprehension): ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
```
Challenge: Can you use a *single* list comprehension to create a list of strings where each string says 'High' if a number is greater than 50, and 'Low' otherwise, for a given list of numbers like `[30, 70, 45, 90, 20]`? Share your solution! π
Lambda functions are small, anonymous functions perfect for quick, one-off operations. List comprehensions offer a super concise and readable way to create lists based on existing iterables. Master these to write cleaner, more efficient Python! π
```python
# Let's explore Lambda Functions and List Comprehensions!
# Example 1: Lambda Function with map()
# A lambda function is a small anonymous function.
# It can take any number of arguments, but can only have one expression.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(f"Squared numbers (using lambda with map): {squared_numbers}")
# Example 2: List Comprehension
# A concise way to create lists based on existing iterables.
# We'll filter for even numbers and then square them.
numbers_to_process = [10, 15, 20, 25, 30]
even_squared = [x**2 for x in numbers_to_process if x % 2 == 0]
print(f"Even numbers squared (using list comprehension): {even_squared}")
# Another example: Conditional expression in list comprehension
# Create a list of 'Even' or 'Odd' strings
parity_list = ["Even" if n % 2 == 0 else "Odd" for n in range(6)]
print(f"Parity list (using conditional comprehension): {parity_list}")
```
Output example:
```
Squared numbers (using lambda with map): [1, 4, 9, 16, 25]
Even numbers squared (using list comprehension): [100, 400, 900]
Parity list (using conditional comprehension): ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
```
Challenge: Can you use a *single* list comprehension to create a list of strings where each string says 'High' if a number is greater than 50, and 'Low' otherwise, for a given list of numbers like `[30, 70, 45, 90, 20]`? Share your solution! π
Here's your Telegram post for Day 25 on Unit Testing!
---
π **Day 25: Unit Testing - Build Robust Python Code!** π
Today, we're diving into a crucial practice for every developer: **Unit Testing!** π Learning to write tests ensures your code works as expected, catches bugs early, and makes future changes safer. Python's built-in `unittest` module makes it straightforward to test individual units (functions or methods) of your code. Let's see how! β
```python
# --- math_operations.py (or just part of your script for this example) ---
def add(a, b):
"""Adds two numbers and returns the sum."""
return a + b
def multiply(a, b):
"""Multiplies two numbers and returns the product."""
return a * b
# --- test_math_operations.py (or continue in the same file) ---
import unittest
# Assuming add and multiply functions are accessible (e.g., defined above or imported)
class TestMathOperations(unittest.TestCase):
def test_add_positive_numbers(self):
"""Test adding two positive numbers."""
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
"""Test adding two negative numbers."""
self.assertEqual(add(-1, -1), -2)
def test_add_zero(self):
"""Test adding a number to zero."""
self.assertEqual(add(0, 5), 5)
def test_multiply_positive_numbers(self):
"""Test multiplying two positive numbers."""
self.assertEqual(multiply(2, 4), 8)
def test_multiply_by_zero(self):
"""Test multiplying by zero."""
self.assertEqual(multiply(5, 0), 0)
def test_multiply_negative_numbers(self):
"""Test multiplying positive and negative numbers."""
self.assertEqual(multiply(3, -2), -6)
# This block allows you to run the tests directly from the script
if __name__ == '__main__':
unittest.main()
```
**Output example:**
```
......
----------------------------------------------------------------------
Ran 6 tests in 0.001s
OK
```
(You'd run this by saving the code as `test_math_operations.py` and then executing `python test_math_operations.py` in your terminal.)
### Small Challenge:
Can you add a new function `divide(a, b)` to our `math_operations.py` and write at least two test cases for it in `TestMathOperations`? Don't forget to consider edge cases like division by zero! π‘
---
---
π **Day 25: Unit Testing - Build Robust Python Code!** π
Today, we're diving into a crucial practice for every developer: **Unit Testing!** π Learning to write tests ensures your code works as expected, catches bugs early, and makes future changes safer. Python's built-in `unittest` module makes it straightforward to test individual units (functions or methods) of your code. Let's see how! β
```python
# --- math_operations.py (or just part of your script for this example) ---
def add(a, b):
"""Adds two numbers and returns the sum."""
return a + b
def multiply(a, b):
"""Multiplies two numbers and returns the product."""
return a * b
# --- test_math_operations.py (or continue in the same file) ---
import unittest
# Assuming add and multiply functions are accessible (e.g., defined above or imported)
class TestMathOperations(unittest.TestCase):
def test_add_positive_numbers(self):
"""Test adding two positive numbers."""
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
"""Test adding two negative numbers."""
self.assertEqual(add(-1, -1), -2)
def test_add_zero(self):
"""Test adding a number to zero."""
self.assertEqual(add(0, 5), 5)
def test_multiply_positive_numbers(self):
"""Test multiplying two positive numbers."""
self.assertEqual(multiply(2, 4), 8)
def test_multiply_by_zero(self):
"""Test multiplying by zero."""
self.assertEqual(multiply(5, 0), 0)
def test_multiply_negative_numbers(self):
"""Test multiplying positive and negative numbers."""
self.assertEqual(multiply(3, -2), -6)
# This block allows you to run the tests directly from the script
if __name__ == '__main__':
unittest.main()
```
**Output example:**
```
......
----------------------------------------------------------------------
Ran 6 tests in 0.001s
OK
```
(You'd run this by saving the code as `test_math_operations.py` and then executing `python test_math_operations.py` in your terminal.)
### Small Challenge:
Can you add a new function `divide(a, b)` to our `math_operations.py` and write at least two test cases for it in `TestMathOperations`? Don't forget to consider edge cases like division by zero! π‘
---
Which assertion method from `unittest.TestCase` would you use to check if two values are not equal?
Anonymous Quiz
0%
assertEqual()
0%
assertTrue()
0%
assertNotEqual()
0%
assertIsNone()
π **Day 26: Basic Web Scraping (Beautiful Soup)** π
Ready to dive into the exciting world of extracting data from websites? πΈοΈ Today, we're taking our first steps into web scraping with the powerful Beautiful Soup library! π₯£ Beautiful Soup makes parsing HTML and XML documents a breeze, allowing us to navigate, search, and modify the parse tree.
We'll learn how to fetch specific elements like titles, paragraphs, and links from a simple webpage. Get ready to turn unstructured web content into usable data! π»β¨
```python
import requests
from bs4 import BeautifulSoup
# In a real scenario, you'd fetch HTML from a URL:
# response = requests.get("https://example.com")
# html_doc = response.text
# For this example, we'll use a static HTML string
html_doc = """
<html>
<head>
<title>My Awesome Learning Page</title>
</head>
<body>
<h1>Welcome to Web Scraping!</h1>
<p class="intro">This is the first paragraph about our Python journey.</p>
<p>Day 26 is all about Beautiful Soup.</p>
<a href="https://beautiful-soup-4.readthedocs.io/en/latest/" id="bs_docs">Beautiful Soup Documentation</a>
</body>
</html>
"""
# Parse the HTML content using Beautiful Soup
soup = BeautifulSoup(html_doc, 'html.parser')
print("--- Extracted Data ---")
# 1. Get the title of the page
page_title = soup.title
print(f"Page Title: {page_title.string}")
# 2. Find the first h1 tag
h1_tag = soup.find('h1')
print(f"H1 Content: {h1_tag.text}")
# 3. Find a specific paragraph by its class
intro_paragraph = soup.find('p', class_='intro')
print(f"Intro Paragraph: {intro_paragraph.text}")
# 4. Find a link by its ID and get its href attribute
docs_link = soup.find(id='bs_docs')
print(f"Docs Link URL: {docs_link.get('href')}")
```
Output example:
```
--- Extracted Data ---
Page Title: My Awesome Learning Page
H1 Content: Welcome to Web Scraping!
Intro Paragraph: This is the first paragraph about our Python journey.
Docs Link URL: https://beautiful-soup-4.readthedocs.io/en/latest/
```
### Small Challenge:
Can you modify the code to find and print the text of *all* `<p>` tags on the page? Hint: Look for a method that finds multiple elements!
---
Ready to dive into the exciting world of extracting data from websites? πΈοΈ Today, we're taking our first steps into web scraping with the powerful Beautiful Soup library! π₯£ Beautiful Soup makes parsing HTML and XML documents a breeze, allowing us to navigate, search, and modify the parse tree.
We'll learn how to fetch specific elements like titles, paragraphs, and links from a simple webpage. Get ready to turn unstructured web content into usable data! π»β¨
```python
import requests
from bs4 import BeautifulSoup
# In a real scenario, you'd fetch HTML from a URL:
# response = requests.get("https://example.com")
# html_doc = response.text
# For this example, we'll use a static HTML string
html_doc = """
<html>
<head>
<title>My Awesome Learning Page</title>
</head>
<body>
<h1>Welcome to Web Scraping!</h1>
<p class="intro">This is the first paragraph about our Python journey.</p>
<p>Day 26 is all about Beautiful Soup.</p>
<a href="https://beautiful-soup-4.readthedocs.io/en/latest/" id="bs_docs">Beautiful Soup Documentation</a>
</body>
</html>
"""
# Parse the HTML content using Beautiful Soup
soup = BeautifulSoup(html_doc, 'html.parser')
print("--- Extracted Data ---")
# 1. Get the title of the page
page_title = soup.title
print(f"Page Title: {page_title.string}")
# 2. Find the first h1 tag
h1_tag = soup.find('h1')
print(f"H1 Content: {h1_tag.text}")
# 3. Find a specific paragraph by its class
intro_paragraph = soup.find('p', class_='intro')
print(f"Intro Paragraph: {intro_paragraph.text}")
# 4. Find a link by its ID and get its href attribute
docs_link = soup.find(id='bs_docs')
print(f"Docs Link URL: {docs_link.get('href')}")
```
Output example:
```
--- Extracted Data ---
Page Title: My Awesome Learning Page
H1 Content: Welcome to Web Scraping!
Intro Paragraph: This is the first paragraph about our Python journey.
Docs Link URL: https://beautiful-soup-4.readthedocs.io/en/latest/
```
### Small Challenge:
Can you modify the code to find and print the text of *all* `<p>` tags on the page? Hint: Look for a method that finds multiple elements!
---
Which of the following Beautiful Soup methods is used to find the *first* occurrence of a specific tag in an HTML document?
Anonymous Quiz
0%
find_all()
0%
select()
100%
find()
0%
get_text()
Here's your Telegram post for Day 27!
---
π Day 27: Introduction to Flask/Django! π
Hello, future web developers! π Today, we're taking our first exciting step into the world of Python web development. We're introducing you to Flask and Django, two incredibly powerful frameworks that let you build dynamic websites and web applications using Python. We'll start with a simple "Hello, World!" example using Flask to show you just how accessible web development can be! Get ready to bring your Python skills to life on the web! ππ»
```python
# Day 27: First steps with Flask!
# Make sure you have Flask installed:
# pip install Flask
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the home page ('/')
@app.route('/')
def hello_world():
"""Returns a simple greeting for the home page."""
return 'Hello from Flask, Day 27 Learners! π Welcome to Web Dev!'
# Define another route for an 'about' page
@app.route('/about')
def about_page():
"""Returns information about this app."""
return 'This is a basic Flask introduction app. Pretty cool, right?'
# Run the Flask app if this script is executed directly
if __name__ == '__main__':
# debug=True enables debug mode, which provides helpful error messages
# and automatically reloads the server on code changes.
app.run(debug=True)
```
**Output example:**
When you run the Python script (`python your_app_name.py`), you'll see output similar to this in your terminal:
```
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
```
Now, open your web browser and navigate to `http://127.0.0.1:5000/`. You should see:
`Hello from Flask, Day 27 Learners! π Welcome to Web Dev!`
If you go to `http://127.0.0.1:5000/about`, you'll see:
`This is a basic Flask introduction app. Pretty cool, right?`
**Small Challenge:**
1. Modify the `hello_world` function to display *your name* instead of "Day 27 Learners!".
2. Add a new route, `/greet/<name>`, that takes a name as part of the URL and returns a personalized greeting. For example, visiting `http://127.0.0.1:5000/greet/Alice` should show "Hello, Alice! Nice to meet you in Flask!". (Hint: Look up how to use variable rules in Flask routes!)
---
---
π Day 27: Introduction to Flask/Django! π
Hello, future web developers! π Today, we're taking our first exciting step into the world of Python web development. We're introducing you to Flask and Django, two incredibly powerful frameworks that let you build dynamic websites and web applications using Python. We'll start with a simple "Hello, World!" example using Flask to show you just how accessible web development can be! Get ready to bring your Python skills to life on the web! ππ»
```python
# Day 27: First steps with Flask!
# Make sure you have Flask installed:
# pip install Flask
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the home page ('/')
@app.route('/')
def hello_world():
"""Returns a simple greeting for the home page."""
return 'Hello from Flask, Day 27 Learners! π Welcome to Web Dev!'
# Define another route for an 'about' page
@app.route('/about')
def about_page():
"""Returns information about this app."""
return 'This is a basic Flask introduction app. Pretty cool, right?'
# Run the Flask app if this script is executed directly
if __name__ == '__main__':
# debug=True enables debug mode, which provides helpful error messages
# and automatically reloads the server on code changes.
app.run(debug=True)
```
**Output example:**
When you run the Python script (`python your_app_name.py`), you'll see output similar to this in your terminal:
```
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
```
Now, open your web browser and navigate to `http://127.0.0.1:5000/`. You should see:
`Hello from Flask, Day 27 Learners! π Welcome to Web Dev!`
If you go to `http://127.0.0.1:5000/about`, you'll see:
`This is a basic Flask introduction app. Pretty cool, right?`
**Small Challenge:**
1. Modify the `hello_world` function to display *your name* instead of "Day 27 Learners!".
2. Add a new route, `/greet/<name>`, that takes a name as part of the URL and returns a personalized greeting. For example, visiting `http://127.0.0.1:5000/greet/Alice` should show "Hello, Alice! Nice to meet you in Flask!". (Hint: Look up how to use variable rules in Flask routes!)
---
What is the primary purpose of web frameworks like Flask and Django in Python?
Anonymous Quiz
0%
To perform complex mathematical calculations and simulations.
0%
To build desktop graphical user interface (GUI) applications.
0%
To facilitate the development of web applications and dynamic websites.
0%
To manage large databases and perform data analysis.
π Day 28: Diving into Asynchronous Programming with `asyncio`! β³
Today, we're unlocking the power of non-blocking I/O with Python's `asyncio` library! π§ Ever wanted your program to do multiple things without waiting for each one to finish? That's what `asyncio` is for! It allows concurrent execution of operations, making your applications more responsive and efficient, especially for I/O-bound tasks like network requests or reading files. Get ready to `async` and `await` your way to faster Python code! π₯
```python
import asyncio
import time
# An asynchronous function simulating an I/O operation
async def fetch_data(item_id, delay):
print(f"[{time.strftime('%H:%M:%S')}] Fetching data for item {item_id}...")
await asyncio.sleep(delay) # Simulate a non-blocking delay
print(f"[{time.strftime('%H:%M:%S')}] Data for item {item_id} fetched after {delay}s.")
return f"Item {item_id} data"
# The main asynchronous function to orchestrate tasks
async def main():
print(f"[{time.strftime('%H:%M:%S')}] Starting main async operations.")
# Run multiple async tasks concurrently
# asyncio.gather waits for all specified awaitables to complete.
results = await asyncio.gather(
fetch_data("A", 3),
fetch_data("B", 1),
fetch_data("C", 2)
)
print(f"[{time.strftime('%H:%M:%S')}] All data fetching complete!")
print(f"Final results: {results}")
if __name__ == "__main__":
# asyncio.run() executes the top-level entry point and manages the event loop.
asyncio.run(main())
```
Output example:
```
[HH:MM:SS] Starting main async operations.
[HH:MM:SS] Fetching data for item A...
[HH:MM:SS] Fetching data for item B...
[HH:MM:SS] Fetching data for item C...
[HH:MM:SS] Data for item B fetched after 1s.
[HH:MM:SS] Data for item C fetched after 2s.
[HH:MM:SS] Data for item A fetched after 3s.
[HH:MM:SS] All data fetching complete!
Final results: ['Item A data', 'Item B data', 'Item C data']
```
*(Note: `HH:MM:SS` will reflect the actual execution time)*
### Small challenge:
Modify the `main` function to create a new task using `asyncio.create_task()` for fetching data for "D" with a 4-second delay, instead of adding it to `asyncio.gather`. How would you await its completion along with the `gather` call? Hint: You might need another `await`! π‘
---
Today, we're unlocking the power of non-blocking I/O with Python's `asyncio` library! π§ Ever wanted your program to do multiple things without waiting for each one to finish? That's what `asyncio` is for! It allows concurrent execution of operations, making your applications more responsive and efficient, especially for I/O-bound tasks like network requests or reading files. Get ready to `async` and `await` your way to faster Python code! π₯
```python
import asyncio
import time
# An asynchronous function simulating an I/O operation
async def fetch_data(item_id, delay):
print(f"[{time.strftime('%H:%M:%S')}] Fetching data for item {item_id}...")
await asyncio.sleep(delay) # Simulate a non-blocking delay
print(f"[{time.strftime('%H:%M:%S')}] Data for item {item_id} fetched after {delay}s.")
return f"Item {item_id} data"
# The main asynchronous function to orchestrate tasks
async def main():
print(f"[{time.strftime('%H:%M:%S')}] Starting main async operations.")
# Run multiple async tasks concurrently
# asyncio.gather waits for all specified awaitables to complete.
results = await asyncio.gather(
fetch_data("A", 3),
fetch_data("B", 1),
fetch_data("C", 2)
)
print(f"[{time.strftime('%H:%M:%S')}] All data fetching complete!")
print(f"Final results: {results}")
if __name__ == "__main__":
# asyncio.run() executes the top-level entry point and manages the event loop.
asyncio.run(main())
```
Output example:
```
[HH:MM:SS] Starting main async operations.
[HH:MM:SS] Fetching data for item A...
[HH:MM:SS] Fetching data for item B...
[HH:MM:SS] Fetching data for item C...
[HH:MM:SS] Data for item B fetched after 1s.
[HH:MM:SS] Data for item C fetched after 2s.
[HH:MM:SS] Data for item A fetched after 3s.
[HH:MM:SS] All data fetching complete!
Final results: ['Item A data', 'Item B data', 'Item C data']
```
*(Note: `HH:MM:SS` will reflect the actual execution time)*
### Small challenge:
Modify the `main` function to create a new task using `asyncio.create_task()` for fetching data for "D" with a 4-second delay, instead of adding it to `asyncio.gather`. How would you await its completion along with the `gather` call? Hint: You might need another `await`! π‘
---