Introduction to Python and Flask

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.

Learning Objectives

  • Install Python and a suitable code editor.
  • Understand basic Python syntax and data types (strings, numbers, booleans).
  • Write simple Python programs using variables, operators, and control flow (if/else, loops).
  • Install Flask and create a basic web application that displays "Hello, World!".
  • Explain the basic structure of a Flask application.

Lesson Content

1. Setting Up Your Environment: Python and Editor

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.

2. Introduction to Python Basics

Python is known for its readability. Let's start with the basics:

  • Variables: Store data. You don't need to declare the data type explicitly. Examples:
    python name = "Alice" age = 30 is_active = True
  • Data Types:
    • 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
  • Operators: Perform actions. Examples:
    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
  • Control Flow:
    • 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

3. Working with Data Structures (Lists, Dictionaries)

Python provides several built-in data structures:

  • Lists: Ordered, mutable (changeable) collections of items. Defined using square brackets [].
    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)
  • Dictionaries: Unordered collections of key-value pairs. Defined using curly braces {}.
    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)

4. Introducing Flask: Your First Web App

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!

Deep Dive

Explore advanced insights, examples, and bonus exercises to deepen understanding.

Day 4 Extended Learning: Flask & Python Deep Dive

Day 4 Extended Learning: Deep Dive into Flask & Python for PWAs

Recap & Beyond: Building on Your Foundation

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.

Deep Dive: Flask Application Structure & Routes

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.

  • Routes and Views: Routes (using @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.).
  • Templating Engines (like Jinja2): While you've used simple returns, Flask can render HTML templates. This separates your presentation logic from your Python code. Templates allow dynamic content creation, making your app more flexible. For instance, you might pass data to the template to display a user's name.
  • Static Files: Your application will serve static files (CSS, JavaScript, images). Flask usually has a 'static' folder for these, making them accessible through URLs (e.g., /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!

Bonus Exercises: Expand Your Skills

Exercise 1: Create a Route with a Variable

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.

Exercise 2: Serve a Simple HTML File

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).

Real-World Connections: Beyond "Hello, World!"

These foundational concepts are applicable across a vast range of applications:

  • Web APIs: Building APIs (Application Programming Interfaces) is a core function of Flask. APIs allow your PWA to communicate with other services, databases, and other applications.
  • Dynamic Websites: Flask is used to build dynamic web applications where content changes based on user input or other factors. Think of social media feeds, e-commerce sites, and interactive dashboards.
  • Data Processing & Automation: Flask can serve as a backend for applications performing tasks such as processing data, automating tasks (e.g., sending email notifications), and interacting with databases.

Challenge Yourself: Building a Simple Form

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.

Further Learning: Expanding Your Horizons

  • Flask Documentation: The official documentation is the primary reference.
  • Python W3Schools Tutorial: Refresh your Python basics or learn more.
  • HTML Reference (Mozilla): Build upon your HTML skills.
  • Database Integration: Explore how to connect Flask applications to databases (e.g., SQLite, PostgreSQL, MySQL) to store and retrieve data. This will be crucial in later lessons for user data and notification management.
  • RESTful APIs: Learn about building RESTful APIs with Flask, including the use of methods like GET, POST, PUT, and DELETE.

Interactive Exercises

Exercise 1: Variable Practice

Create a Python file and declare variables for your name, age, city, and whether you are a student. Print each variable to the console.

Exercise 2: Control Flow Challenge

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".

Exercise 3: List Manipulation

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.

Exercise 4: Flask Modification

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.

Knowledge Check

Question 1: Which data type is used to store whole numbers?

Question 2: What is the purpose of the `app.route()` decorator in Flask?

Question 3: What will the following code print? `my_list = [1, 2, 3]; print(my_list[1])`

Question 4: Which of the following is a valid way to declare a string variable in Python?

Question 5: What does `pip` stand for?

Practical Application

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.

Key Takeaways

Next Steps

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.

Your Progress is Being Saved!

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.

Next Lesson (Day 5)