This lesson introduces you to the world of Python and Flask, the core technologies for building your backend for your Progressive Web App. You will learn the fundamentals of Python programming, including basic syntax and data structures, and then use this knowledge to create a simple "Hello, World!" web application using Flask.
Before we dive into code, you need a development environment. First, install Python. You can download it from the official Python website (python.org). Choose the latest stable version. During installation, be sure to check the box that adds Python to your PATH environment variable. This allows you to run Python from your command line/terminal.
Next, choose a text editor or IDE. Popular choices for beginners include VS Code, Sublime Text, Atom, or even the built-in IDLE (though IDEs like VS Code often offer more features out-of-the-box). Download and install your chosen editor. For this lesson, we will assume you have downloaded Visual Studio Code. A text editor with syntax highlighting and code completion will be very helpful. If you choose VS Code, install the Python extension from the Marketplace. This will add helpful features such as auto-completion and debugging.
Python is known for its readability. Let's start with the basics:
python
name = "Alice"
age = 30
is_active = True
str
(string): Text, e.g., "Hello"
int
(integer): Whole numbers, e.g., 10
float
(floating-point): Decimal numbers, e.g., 3.14
bool
(boolean): True
or False
python
# Arithmetic
sum_result = 10 + 5
product = 3 * 4
division = 10 / 2 # Result is a float (5.0)
remainder = 10 % 3 # Remainder of the division (1)
# Comparison
is_equal = (5 == 5) # True
is_greater = (10 > 5) # True
if/else
statements: Execute code conditionally.python
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
for
loops: Iterate over a sequence (e.g., a list).python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while
loops: Repeat code as long as a condition is true.python
count = 0
while count < 3:
print(count)
count += 1
Python provides several built-in data structures:
[]
.python
my_list = [1, 2, 3, "apple", True]
print(my_list[0]) # Access the first element (1) - lists are zero-indexed
my_list.append(4) # Add an element to the end
print(my_list)
{}
.python
my_dict = {"name": "Bob", "age": 25, "city": "New York"}
print(my_dict["name"]) # Access the value associated with the key "name" ("Bob")
my_dict["occupation"] = "Developer" # Add a new key-value pair
print(my_dict)
Flask is a lightweight web framework written in Python. It's perfect for beginners and allows you to build web applications easily. First, install Flask using pip (the Python package installer). Open your terminal/command prompt and type: pip install flask
Now, let's create a simple "Hello, World!" Flask application. Create a new Python file (e.g., app.py
) and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route("/") # This is a route decorator. It binds a URL (/) to a function.
def hello_world():
return "Hello, World!"
if __name__ == "__main__":
app.run(debug=True) # Run the app. debug=True is helpful during development.
from flask import Flask
: Imports the Flask class.app = Flask(__name__)
: Creates a Flask application instance.@app.route("/")
: A decorator that tells Flask which URL should trigger the hello_world
function.def hello_world():
: The function that will be executed when the user visits the root URL (/
).return "Hello, World!"
: Returns the text to display in the browser.app.run(debug=True)
: Runs the development server. debug=True
provides useful error messages during development.Save the file, open your terminal, navigate to the directory where you saved the file, and run it with: python app.py
. Open your web browser and go to http://127.0.0.1:5000/
(or whatever address is printed by the terminal). You should see "Hello, World!" displayed in your browser. Congratulations, you've created your first web app!
Explore advanced insights, examples, and bonus exercises to deepen understanding.
Congratulations on creating your first "Hello, World!" Flask application! You've successfully navigated the initial steps of backend development for your PWA. Now, let's delve deeper into the concepts you've learned, explore alternative ways of approaching them, and consider how they connect to real-world scenarios. We'll focus on expanding on the knowledge of Python, Flask, and laying groundwork for eventual Android system notification support, which we will touch upon later in the overall course.
You understand the basic structure of a Flask application. Let's explore it a bit further. Flask apps generally follow a structure that promotes organization and maintainability. The core is the Flask instance, which manages incoming requests and routes them to the appropriate functions.
@app.route('/')
, for example) are like URLs. They map specific URLs to *view functions*. The view functions process requests and return responses (usually HTML, JSON, etc.).
/static/style.css
).
Understanding this structure is crucial as your applications grow. It allows you to logically organize your code, add features (like database interactions and user authentication) and ensure code reusability. Think of it like a well-organized house β everything has its place!
Modify your "Hello, World!" Flask application to accept a name as a parameter in the URL (e.g., /hello/YourName
). Your application should then display "Hello, YourName!". Hint: use @app.route('/hello/
and a view function that uses the `name` variable.
Create a basic HTML file (e.g., index.html
) with a heading and some text. Modify your Flask application so that when you visit the root URL (/
), it renders this HTML file using Flask's render_template
function. You'll need to create a 'templates' folder in your project root, and place index.html
in there. You'll have to install Flask-related modules for templates (e.g., Jinja2).
These foundational concepts are applicable across a vast range of applications:
Create a Flask application that serves an HTML form (e.g., with an input field for a name). When the form is submitted, the application should display the name the user entered. Use the GET and POST methods to handle form submissions.
Create a Python file and declare variables for your name, age, city, and whether you are a student. Print each variable to the console.
Write a Python program that takes a number as input from the user. If the number is even, print "Even". If the number is odd, print "Odd".
Create a list of your favorite fruits. Add a new fruit to the list using the `append()` method. Print the updated list to the console.
Modify your "Hello, World!" Flask application to display a personalized greeting. For example, instead of just "Hello, World!", display "Hello, [Your Name]!". Replace [Your Name] with a variable you declare.
Imagine you're building a simple website to display a to-do list. Using what you've learned about Python and Flask, you could create a basic backend that stores and displays the list items.
In the next lesson, we'll delve deeper into Flask, explore routing and templates, and begin building the foundation for your PWA's backend. Please install VSCode and try to use it. Make sure you are familiar with the installation directory for pip packages, as you will need to access them later.
We're automatically tracking your progress. Sign up for free to keep your learning paths forever and unlock advanced features like detailed analytics and personalized recommendations.