100% found this document useful (1 vote)
14 views

Django 2.2 & Python: The Ultimate Web Development Bootcamp: Build three complete websites, learn back and front-end web development, and publish your site online with DigitalOcean. Alam pdf download

The document promotes various ebooks focused on web development, particularly highlighting 'Django 2.2 & Python: The Ultimate Web Development Bootcamp'. It outlines the course content, including Python basics, project-based learning, and deployment on DigitalOcean. Additionally, it emphasizes the importance of mastering Python and Django for building functional web applications.

Uploaded by

linutemurwat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
14 views

Django 2.2 & Python: The Ultimate Web Development Bootcamp: Build three complete websites, learn back and front-end web development, and publish your site online with DigitalOcean. Alam pdf download

The document promotes various ebooks focused on web development, particularly highlighting 'Django 2.2 & Python: The Ultimate Web Development Bootcamp'. It outlines the course content, including Python basics, project-based learning, and deployment on DigitalOcean. Additionally, it emphasizes the importance of mastering Python and Django for building functional web applications.

Uploaded by

linutemurwat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Download the full version and explore a variety of ebooks

or textbooks at https://ebookmass.com

Django 2.2 & Python: The Ultimate Web Development


Bootcamp: Build three complete websites, learn
back and front-end web development, and publish
your site online with DigitalOcean. Alam

_____ Follow the link below to get your download now _____

https://ebookmass.com/product/django-2-2-python-the-
ultimate-web-development-bootcamp-build-three-complete-
websites-learn-back-and-front-end-web-development-and-
publish-your-site-online-with-digitalocean-alam/

Access ebookmass.com now to download high-quality


ebooks or textbooks
We have selected some products that you may be interested in
Click the link to download now or visit ebookmass.com
for more options!.

Kotlin for Web Development and Kotlin Collections: A


Beginner's Odyssey in Web Development 2 Books in 1 Jp
Parker
https://ebookmass.com/product/kotlin-for-web-development-and-kotlin-
collections-a-beginners-odyssey-in-web-development-2-books-in-1-jp-
parker/

Database-Driven Web Development: Learn to Operate at a


Professional Level with PERL and MySQL 2nd Edition Thomas
Valentine
https://ebookmass.com/product/database-driven-web-development-learn-
to-operate-at-a-professional-level-with-perl-and-mysql-2nd-edition-
thomas-valentine/

Learn Enough Ruby to Be Dangerous Michael Hartl

https://ebookmass.com/product/learn-enough-ruby-to-be-dangerous-
michael-hartl/

Beginner's Guide to Streamlit with Python: Build Web-Based


Data and Machine Learning Applications 1st Edition Sujay
Raghavendra
https://ebookmass.com/product/beginners-guide-to-streamlit-with-
python-build-web-based-data-and-machine-learning-applications-1st-
edition-sujay-raghavendra/
Beginning Game Development with Godot (for John Malkovec):
Learn to Create and Publish Your First 2D Platform Game
Maithili Dhule
https://ebookmass.com/product/beginning-game-development-with-godot-
for-john-malkovec-learn-to-create-and-publish-your-first-2d-platform-
game-maithili-dhule/

PHP 8 Basics: For Programming and Web Development Gunnard


Engebreth

https://ebookmass.com/product/php-8-basics-for-programming-and-web-
development-gunnard-engebreth/

Web API Development for the Absolute Beginner: A Step-by-


step Approach to Learning the Fundamentals of Web API
Development with .NET 7 1st Edition Irina Dominte
https://ebookmass.com/product/web-api-development-for-the-absolute-
beginner-a-step-by-step-approach-to-learning-the-fundamentals-of-web-
api-development-with-net-7-1st-edition-irina-dominte/

Fundamentals of Web Development 3rd Edition Randy Connolly

https://ebookmass.com/product/fundamentals-of-web-development-3rd-
edition-randy-connolly/

High-Performance Web Apps with FastAPI: The Asynchronous


Web Framework Based on Modern Python 1st Edition Malhar
Lathkar
https://ebookmass.com/product/high-performance-web-apps-with-fastapi-
the-asynchronous-web-framework-based-on-modern-python-1st-edition-
malhar-lathkar/
Course Content
~ Introduction
Section 1: Python Refresher
Chapter 1: Install Python
Chapter 2: Variables, Strings, Ints, and Print
Chapter 3: If Statements and Comments
Chapter 4: Functions
Chapter 5: Lists
Chapter 6: Loops
Chapter 7: Dictionaries
Chapter 8: Classes
Section 2: Project #1 - Word Counter Website
Chapter 9: Project Intro
Chapter 10: Django Cheat Sheet
Chapter 11: Installing Django
Chapter 12: Running the Django Server
Chapter 13: Project Tour
Chapter 14: URLs
Chapter 15: Templates
Chapter 16: Forms
Chapter 17: Counting the words
Chapter 18: Challenge
Chapter 19: Solution
Section 3: Git
Chapter 20: Intro to Git
Chapter 21: Installing Git A-Z
Chapter 22: Troubleshooting
Section 4: Project #2 - Your Personal Portfolio
Website
Chapter 23: Project Intro
Chapter 24: Sketch
Chapter 25: Virtualenv
Chapter 26: Gitignore
Chapter 27: Apps
Chapter 28: Models
Chapter 29: Admin
Chapter 30: psycopg2 fix
Chapter 31: Postgres
Chapter 32: Test Your Skills - Blog Model
Chapter 33: Home Page
Chapter 34: Bootstrap
Chapter 35: Show Jobs
Chapter 36: All Blogs
Chapter 37: Blog Detail
Chapter 38: Static Files
Chapter 39: Polish
Section 5: VPS
Chapter 40: Intro
Chapter 41: Digital Ocean
Chapter 42: Security
Chapter 43: Postgres and Virtualenv
Chapter 44: Git Push and Pull
Chapter 45: Gunicorn
Chapter 46: Nginx
Chapter 47: Domains
Section 6: Project #3 - Product Hunt Clone Website
Chapter 48: Project Intro
Chapter 49: Sketch
Chapter 50: Extending Templates
Chapter 51: Base Styling
Chapter 52: Sign Up
Chapter 53: Login and Logout
Chapter 54: Products Model
Chapter 55: Creating Products
Chapter 56: Iconic
Chapter 57: Product Details
Chapter 58: Home Page
Chapter 59: Polish
~ Conclusion

Introduc on
Assets and Resources:
- Django Official Website ([Visit Here](
https://www.djangoproject.com/ ))
- Python Official Website ([Visit Here](
https://www.python.org/ ))
- DigitalOcean’s Overview & Documentation ([Visit Here](
https://www.digitalocean.com/docs/ ))

Welcome to “Django 2.2 & Python: The Ultimate Web


Development Bootcamp”. This book is designed to be
your one-stop guide to mastering the powerful
combination of Django, a high-level web framework, and
Python, one of the world’s most versatile programming
languages. By the end of this bootcamp, you will not only
have built three functional web applications but will also
be equipped with the knowledge and confidence to
embark on your own web development projects.

Why Django and Python?


When venturing into the world of web development, the
sheer number of languages, frameworks, and tools can
be overwhelming. So why focus on Django and Python?
Python is celebrated for its simplicity, versatility, and
readability, making it a top choice for beginners and
seasoned developers alike. It powers a myriad of
applications, from simple scripts to machine learning
algorithms and large-scale web applications.
Django, on the other hand, was birthed from Python’s
philosophy. Often referred to as the framework “for
perfectionists with deadlines,” Django makes it
significantly faster to build high-quality web applications.
It’s designed to avoid repetitive tasks and encourage the
rapid development of robust applications, making your
development journey smoother and more enjoyable.

What’s Inside this Bootcamp?


As you delve into the upcoming sections and chapters,
here’s what you can expect:
1. Python Refresher: Even if you’ve never written a line
of Python code, we’ve got you covered. We begin with
the basics, ensuring you’re well-equipped to tackle
Django with confidence.
2. Three Comprehensive Projects: From a simple word-
counting website to your own portfolio and a clone of the
renowned Product Hunt platform, you’ll be applying your
newfound knowledge in practical, tangible ways.
3. Insights into Git: Dive into version control with Git, a
must-know tool for every developer. You’ll learn why it’s
crucial, how to set it up, and how to use it effectively.
4. Deploying with DigitalOcean: We won’t just leave you
with applications on your local machine. We’ll guide you
through deploying your projects to a Virtual Private
Server (VPS) on DigitalOcean, making them accessible
to the world.

Are You Ready?


Whether you’re a novice curious about web development
or a Python enthusiast eager to dip your toes into web
frameworks, this book is crafted for you. Our approach is
hands-on, interspersed with challenges and solutions,
ensuring you not only consume content but also actively
engage with it.
Before you dive into the next sections, ensure you have
a functioning computer and a stable internet connection.
While no prior experience with Django or Python is
required, a basic understanding of general programming
concepts will be beneficial.
And most importantly, come with an open mind and a
thirst for knowledge. The world of web development is
vast and fascinating, and we’re thrilled to be your guide
on this journey.
Prepare yourself for an immersive, enlightening, and,
above all, fun exploration of Django 2.2 and Python.
Let’s begin!

Section 1:
Python Refresher
Install Python
Assets and Resources for this Chapter:
- Python Installer: Available from the official Python
website ([Download here](
https://www.python.org/downloads/ ))
- Python Documentation: Helpful for any installation
troubleshooting or additional details ([Visit here](
https://docs.python.org/3/ ))

Introduction
Before we dive into the world of Django, it’s essential to
familiarize ourselves with the foundational language
upon which it’s built: Python. While Django is a powerful
web framework, Python is the heart and soul that powers
it. In this chapter, we’ll ensure you have Python installed
and set up correctly on your machine.

Why Python?
Python is one of the world’s most popular programming
languages. It is known for its simplicity, readability, and
vast array of libraries and frameworks, making it versatile
for everything from web development to data analysis to
artificial intelligence and more.

Choosing a Python Version


While there are multiple versions of Python available, as
of writing this book, Python 3.9 is the latest stable
release. It is always advisable to use the latest version
unless you have a specific need for an older version.
Django 2.2, which we’ll be focusing on in this book,
requires Python 3.5 or newer.
Steps to Install Python:
1. Visit the Official Python Website
- Open your browser and navigate to [Python’s official
website]( https://www.python.org/downloads/ ).
2. Download the Installer
- You’ll see a button labeled “Download Python 3.9.x”
(or the latest version). Click on it to start the download.
3. Run the Installer
- Once the download is complete, locate the installer
in your downloads folder and double-click to run it.
- Important: Ensure you check the box that says “Add
Python 3.9 to PATH” before proceeding. This will allow
you to run Python from your command line or terminal
without any extra configuration.
4. Choose Installation Options
- For most users, the default installation options will
suffice. However, if you’re an advanced user and want to
customize the installation, feel free to do so.
- Click “Install Now” to begin the installation process.
5. Installation Complete
- Once the installation is finished, you’ll see a screen
indicating that Python was installed successfully.
6. Verify the Installation
- Open your command line or terminal and type
`python —version` and press enter. This should return
the version number, confirming that Python was installed
correctly.

Potential Issues and Troubleshooting:


- If you receive an error when trying to verify the
installation, it’s possible that Python wasn’t added to
your system’s PATH. Make sure you checked the “Add
Python to PATH” option during installation.
- On some systems, you might need to use `python3`
instead of `python` to invoke Python.

Conclusion
Congratulations! You’ve successfully installed Python on
your machine. As we delve deeper into Django and web
development in the subsequent chapters, you’ll see the
power and flexibility that Python offers. But for now, take
a moment to celebrate this first step in your web
development journey. In the next chapter, we’ll dive into
some fundamental Python concepts to get you warmed
up.

Next Steps:
Before moving on, consider playing around with the
Python interactive shell by typing `python` (or `python3`
on some systems) into your command line or terminal.
This will give you a prompt where you can type and
execute Python code directly, providing an excellent way
to practice and experiment.

Variables, Strings, Ints,


and Print
Assets & Resources:
- Python (Version 3.7 or later) ([Download and install
from Python’s official website](
https://www.python.org/downloads/ ))
- A Text Editor or IDE (Recommendation: VS Code or
PyCharm)

Introduction:
Before diving deep into the world of Django and web
development, it’s crucial to have a strong foundation in
Python. This chapter will guide you through the basics of
variables, strings, integers, and the print function in
Python, setting the stage for the upcoming chapters.
1. Variables:
A variable in Python is like a container or storage
location that holds data values. A variable is assigned
with a value, and you can change this value based on
your needs.
Syntax:
“`python
variable_name = value
“`
Example:
“`python
greeting = “Hello, World!”
“`
In this example, `greeting` is a variable that holds the
string “Hello, World!”.

2. Strings:
Strings in Python are a sequence of characters,
enclosed within single (`’ ‘`) or double (`” “`) quotes.
Examples:
“`python
name = “John”
message = ‘Welcome to the world of Python!’
“`
String Concatenation:
You can also combine or concatenate strings using the
`+` operator:
“`python
first_name = “John”
last_name = “Doe”
full_name = first_name + ” ” + last_name
“`

3. Integers (Ints):
Integers are whole numbers (without decimal points). In
Python, you can perform various arithmetic operations
with integers.
Examples:
“`python
age = 25
days_in_week = 7
“`
Basic Arithmetic Operations:
“`python
sum = 5 + 3 # Addition
difference = 5 - 3 # Subtraction
product = 5 * 3 # Multiplication
quotient = 5 / 3 # Division
remainder = 5 % 3 # Modulus (returns the remainder of
the division)
“`

4. The Print Function:


The `print()` function in Python is used to output data to
the console. It’s a great tool for debugging and for
displaying results to users.
Syntax:
“`python
print(value1, value2, …, sep=’ ‘, end=’\n’)
“`
Examples:
“`python
print(“Hello, World!”)
print(“Your age is:”, age)
print(first_name, last_name, sep=” “, end=”!\n”)
“`
In the last example, `sep` is used to define a separator
between the values, and `end` defines what to print at
the end. The default values are a space (`’ ‘`) for `sep`
and a newline (`’\n’`) for `end`.

Practice Exercise:
Now that you have a basic understanding of variables,
strings, integers, and the print function, try the following:
1. Create a variable called `course` and assign it the
string value “Python for Web Development”.
2. Create two variables, `students` and `teachers`, and
assign them the integer values 200 and 5, respectively.
3. Use the `print()` function to display the following
message:
“`
Welcome to the course: Python for Web Development.
We have 200 students and 5 teachers.
“`
Remember to use string concatenation and the variables
you’ve created!

Conclusion:
Understanding the basics of variables, strings, and
integers, and how to display them using the `print()`
function is fundamental in Python. This knowledge will
be instrumental as we proceed further into more complex
topics and start our journey with Django. Make sure to
practice the concepts you’ve learned here, as practice is
the key to mastering any programming language.
In the next chapter, we will explore conditional
statements in Python. Stay tuned!

Note: This chapter serves as a brief refresher. If any


topic seems challenging, consider referring to the Python
official documentation or other in-depth Python beginner
courses to gain a deeper understanding.

If Statements and
Comments
Assets and Resources:
- Python 3.x (You can download and install Python from
[python.org]( https://www.python.org/downloads/ ))
- Integrated Development Environment (IDE) like
PyCharm or Visual Studio Code (You can choose any
IDE, but for beginners, I recommend [PyCharm
Community Edition](
https://www.jetbrains.com/pycharm/download/ ))

Introduction
Before diving into web development with Django, it’s
crucial to have a firm grasp on the basic building blocks
of Python. One of the core concepts of any programming
language is conditional statements, with “if statements”
being the most commonly used. In this chapter, we’ll be
exploring if statements, along with Python comments
which play an essential role in making our code
understandable.

If Statements
At its heart, an if statement is a simple decision-making
tool that Python provides. It evaluates an expression
and, based on whether that expression is `True` or
`False`, will execute a block of code.

Basic If Statement
“`python
x = 10
if x > 5:
print(“x is greater than 5”)
“`
In the code above, Python checks if the value of `x` is
greater than 5. If it is, the message “x is greater than 5”
is printed to the console.

If-Else Statement
Often, you’ll want to have an alternative action in case
the if condition isn’t met:
“`python
x=3
if x > 5:
print(“x is greater than 5”)
else:
print(“x is not greater than 5”)
“`

If-Elif-Else Statement
For multiple conditions, Python provides the `elif`
keyword:
“`python
x=5
if x > 10:
print(“x is greater than 10”)
elif x == 5:
print(“x is 5”)
else:
print(“x is less than 10 but not 5”)
“`
In the example above, since `x` is 5, the message “x is
5” will be printed.

Comments in Python
Comments are an essential part of any programming
language. They allow developers to describe what’s
happening in the code, which can be invaluable for both
the original developer and others who might work on the
code in the future.
In Python, the `#` symbol is used to denote a comment.
Any text following this symbol on the same line is
considered a comment and will not be executed by
Python.
“`python
# This is a single-line comment in Python
x = 5 # Assigning value 5 to variable x
“`
For multi-line comments, Python developers often use
triple quotes, though this is technically a multi-line string.
Python simply ignores this string if it’s not assigned to a
variable:
“`python
”’
This is a multi-line
comment in Python
”’
x = 10
“`

Conclusion
If statements form the backbone of decision-making in
Python, allowing us to conditionally execute blocks of
code. Together with comments, which help in clarifying
and explaining our code, these tools are foundational for
any aspiring Python developer.
In the next chapter, we’ll explore functions, another
essential building block in Python.

Func ons
Assets and Resources Required:
1. Python (Version used in this book: Python 3.9) *(You
can download and install Python from the official website
[python.org]( https://www.python.org/downloads/ ).
Ensure you select the version 3.9 or newer during the
setup.)*
2. An IDE or text editor (Recommended: Visual Studio
Code) *(Available for free at [Visual Studio Code’s official
website]( https://code.visualstudio.com/download ).)
3. A working terminal or command prompt to execute
scripts.

Introduction
Functions are a cornerstone of programming in any
language. In Python, functions enable you to bundle a
sequence of statements into a single, reusable entity.
This chapter introduces you to the world of functions,
explaining how to create and use them.
Defining a Function
A function is defined using the `def` keyword, followed by
a name for the function, and then a pair of parentheses.
The code block within every function is indented, which
is a critical aspect of Python syntax.
Here’s a simple function definition:
“`python
def greet():
print(“Hello, World!”)
“`
In the above code, we’ve defined a function named
`greet` that, when called, will print “Hello, World!” to the
console.

Calling a Function
To execute the statements inside a function, you need to
call or invoke the function. To call a function, you simply
use the function name followed by parentheses.
“`python
greet() # This will print “Hello, World!”
“`

Parameters and Arguments


Functions can also accept values, known as parameters,
which allow you to pass data to be processed. When you
define a function and specify parameters, they act like
variables.
Here’s an example:
“`python
def greet(name):
print(f”Hello, {name}!”)
“`
When calling this function, you provide a value, known
as an argument, for the specified parameter:
“`python
greet(“Alice”) # This will print “Hello, Alice!”
“`

Return Values
Functions can also return values using the `return`
keyword. This is useful when you want a function to
evaluate data and give something back.
Here’s an example of a function that takes two numbers,
adds them, and then returns the result:
“`python
def add_numbers(a, b):
result = a + b
return result
sum_result = add_numbers(5, 3)
print(sum_result) # This will print 8
“`

Default Parameter Values


Python allows you to set default values for function
parameters. This means if an argument for that
parameter is omitted when the function is called, the
default value will be used.
“`python
def greet(name=“User”):
print(f”Hello, {name}!”)
greet() # This will print “Hello, User!”
greet(“Bob”) # This will print “Hello, Bob!”
“`

Variable-length Arguments
There might be scenarios where you don’t know the
number of arguments that will be passed into a function.
Python allows you to handle this kind of situation through
*args and kwargs.
“`python
# Using *args
def print_all_args(*args):
for arg in args:
print(arg)
print_all_args(1, “apple”, True, 42.5)
“`

Scope of Variables
In Python, a variable declared inside a function has a
local scope, which means it’s accessible only within that
function. Conversely, variables declared outside all
functions have a global scope.
“`python
global_variable = “I’m global!”
def demo_function():
local_variable = “I’m local!”
print(global_variable) # This is valid
print(local_variable) # This is valid within the
function
print(global_variable) # This will print “I’m global!”
# print(local_variable) # This would result in an error
“`
Summary
In this chapter, we explored the essentials of functions in
Python, which included defining, calling, and returning
values from functions. We also delved into parameter
handling with default values and variable-length
arguments. Grasping the concept of functions and their
flexibility is vital for any budding Python developer. As
you continue in this book, you’ll find that functions play
an integral role in building Django applications.
In the next chapter, we’ll explore Python lists, a crucial
data structure in Python, which will aid us further when
diving into Django’s capabilities.

Lists
Assets and Resources Required for this Chapter:
- Python (version 3.6 or higher) [Can be downloaded and
installed from the official Python website at `
https://www.python.org/downloads/ `]
- A code editor (preferably IDLE, which comes with
Python installation) or any other code editor of your
choice.

Introduction:
Lists are one of the most powerful tools in Python. They
allow you to store multiple items in a single variable.
These items can be of any type, and you can mix types
within a list. This flexibility allows lists to support a
myriad of use cases, from simple collections of numbers
to complex data structures.

Creating a List:
To create a list, use square brackets and separate the
items with commas.
“`python
fruits = [“apple”, “banana”, “cherry”]
print(fruits)
“`
Output:
“`
[‘apple’, ‘banana’, ‘cherry’]
“`

Accessing Items in a List:


To access an item in a list, use its index number. Index
numbers start from 0 for the first item.
“`python
print(fruits[1])
“`
Output:
“`
banana
“`

Modifying Items in a List:


To modify an item in a list, refer to its index number and
assign a new value.
“`python
fruits[1] = “blueberry”
print(fruits)
“`
Output:
“`
[‘apple’, ‘blueberry’, ‘cherry’]
“`

Adding Items to a List:


1. Using the `append()` method: This adds the item to
the end of the list.
“`python
fruits.append(“orange”)
print(fruits)
“`
Output:
“`
[‘apple’, ‘blueberry’, ‘cherry’, ‘orange’]
“`
2. Using the `insert()` method: This adds an item at any
position you choose.
“`python
fruits.insert(1, “kiwi”)
print(fruits)
“`
Output:
“`
[‘apple’, ‘kiwi’, ‘blueberry’, ‘cherry’, ‘orange’]
“`

Removing Items from a List:


1. Using the `remove()` method: This removes the
specified item.
“`python
fruits.remove(“kiwi”)
print(fruits)
“`
Output:
“`
[‘apple’, ‘blueberry’, ‘cherry’, ‘orange’]
“`
2. Using the `pop()` method: Without any argument, it
removes the last item, but you can also specify an index.
“`python
fruits.pop(1)
print(fruits)
“`
Output:
“`
[‘apple’, ‘cherry’, ‘orange’]
“`

Sorting a List:
1. Using the `sort()` method: This sorts the list in
ascending order by default.
“`python
numbers = [34, 1, 98, 23]
numbers.sort()
print(numbers)
“`
Output:
“`
[1, 23, 34, 98]
“`
2. Using the `sorted()` function: This returns a new
sorted list and keeps the original list unchanged.
“`python
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)
“`
Output:
“`
[98, 34, 23, 1]
“`

List Slicing:
You can return a range of items by specifying a start and
an end index. Remember, the end index is exclusive.
“`python
letters = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
print(letters[2:5])
“`
Output:
“`
[‘c’, ‘d’, ‘e’]
“`

List Comprehensions:
This is a concise way to create lists based on existing
lists.
“`python
squared_numbers = [n2 for n in numbers if n > 2]
print(squared_numbers)
“`
Output:
“`
[1156, 529, 9604]
“`

Conclusion:
Lists are one of the foundational data structures in
Python. Their versatility makes them suitable for a range
of applications. By mastering lists, you are taking an
essential step in becoming proficient in Python.
Remember to practice these concepts with various
examples to strengthen your understanding and increase
retention. Happy coding!

Loops
Assets and Resources:
- Python (3.x) - [Can be downloaded from the official
Python website]( https://www.python.org/downloads/ )
- Python Integrated Development Environment (IDE) –
[We recommend the default IDLE or PyCharm for
beginners](
https://www.jetbrains.com/pycharm/download/ )

Introduction:
Loops in programming allow us to execute a block of
code multiple times. Instead of writing the same code
again and again, you can simply loop through it. Python
provides two main types of loops: `for` and `while`. In
this chapter, we’ll explore both types and their practical
applications.

1. The ‘for’ Loop:


In Python, the `for` loop is used to iterate over a
sequence such as a list, tuple, string, or range.
Syntax:
“`python
for variable in sequence:
# code to execute
“`
Example:
Let’s loop through a list of fruits:
“`python
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
“`
Output:
“`
apple
banana
cherry
“`
2. The ‘range()’ Function with ‘for’ Loop:
When you want to repeat a block of code a specific
number of times, you can use the `range()` function with
a `for` loop.
Syntax:
“`python
for variable in range(start, stop, step):
# code to execute
“`
- `start`: (Optional) The starting value. Default is 0.
- `stop`: The ending value (exclusive).
- `step`: (Optional) The increment value. Default is 1.
Example:
Print numbers from 1 to 5:
“`python
for i in range(1, 6):
print(i)
“`
Output:
“`
1
2
3
4
5
“`

3. The ‘while’ Loop:


A `while` loop continues to execute a block of code as
long as a condition remains true.
Syntax:
“`python
while condition:
# code to execute
“`
Example:
Print numbers from 1 to 5 using a `while` loop:
“`python
count = 1
while count <= 5:
print(count)
count += 1
“`
Output:
“`
1
2
3
4
5
“`

4. ‘break’ and ‘continue’ Statements:


- `break`: Exits the loop prematurely.
- `continue`: Skips the rest of the loop’s current iteration
and moves to the next one.
Example (break):
Find the first number divisible by 7 in a range:
“`python
for num in range(1, 50):
if num % 7 == 0:
print(f”The first number divisible by 7 is {num}.”)
break
“`
Output:
“`
The first number divisible by 7 is 7.
“`
Example (continue):
Print only odd numbers between 1 and 10:
“`python
for num in range(1, 11):
if num % 2 == 0:
continue
print(num)
“`
Output:
“`
1
3
5
7
9
“`

5. Nested Loops:
A loop inside another loop is known as a nested loop. It
can be a combination of `for` and `while` loops.
Example:
Printing a pattern using nested loops:
“`python
for i in range(1, 5):
for j in range(i):
print(“*”, end=”**”)
print()
“`
Output:
“`
*
**
***
****
“`

Conclusion:
Loops play a crucial role in programming, allowing for
repetitive tasks to be handled efficiently. With the
combination of `for` and `while` loops, and the control
offered by `break` and `continue`, Python offers flexibility
and power in managing iterations. Practice is key, so try
to implement these in your Python refresher tasks and
see the magic of loops unfold.

Next, we will dive deeper into Python by exploring one of


its core data structures: Dictionaries. Stay tuned!

Dic onaries
Assets and Resources:
1. Python 3 (Acquire: [Download Python](
https://www.python.org/downloads/ ))
2. A text editor or Integrated Development Environment
(IDE) like PyCharm, Visual Studio Code, or Atom.
3. Terminal (on MacOS/Linux) or Command
Prompt/Powershell (on Windows)

Introduction:
In the Python programming language, a dictionary is a
mutable, unordered collection of items. Every item in the
dictionary has a key/value pair. Dictionaries are used to
store data in a key-value pair format where each key
must be unique. If you come from other programming
languages, you can think of dictionaries as hash maps or
associative arrays.

Creating a Dictionary:
Creating a dictionary is straightforward. You use curly
brackets `{}` to define a dictionary and then specify key-
value pairs. Here’s a simple example:
“`python
person = {
“first_name”: “John”,
“last_name”: “Doe”,
“age”: 30
}
“`
Here, `first_name`, `last_name`, and `age` are keys, and
“John”, “Doe”, and 30 are their respective values.

Accessing Items:
To access the items of a dictionary, you’ll use the key
inside square brackets `[]`:
“`python
print(person[“first_name”]) # Outputs: John
“`
If you try to access a key that doesn’t exist, Python will
raise an error. To prevent this, use the `get()` method:
“`python
print(person.get(“address”, “Not Available”)) # Outputs:
Not Available
“`

Modifying a Dictionary:
You can change the value of a specific item by referring
to its key:
“`python
person[“age”] = 31 # Modifies the age to 31
“`
To add a new key-value pair:
“`python
person[“address”] = “123 Main St” # Adds a new key-
value pair
“`

Removing Items:
Use the `pop()` method to remove an item by its key:
“`python
person.pop(“age”)
“`
Use the `del` statement to remove an item by its key:
“`python
del person[“last_name”]
“`
To clear all items from the dictionary, use the `clear()`
method:
“`python
person.clear()
“`

Iterating Through a Dictionary:


You can loop through a dictionary by using a for loop:
“`python
# Print all keys
for key in person:
print(key)
# Print all values
for key in person:
print(person[key])
# Using the items() method for both keys and values
for key, value in person.items():
print(key, value)
“`

Dictionary Methods:
Python dictionaries offer various methods to make
dictionary manipulations more straightforward:
- `keys()`: Returns a list of dictionary keys.
- `values()`: Returns a list of dictionary values.
- `items()`: Returns a list of dictionary’s key-value tuple
pairs.
- `copy()`: Returns a copy of the dictionary.
- `fromkeys()`: Creates a new dictionary with the
provided keys and values.

Nested Dictionaries:
A dictionary can contain dictionaries, this is called nested
dictionaries.
“`python
family = {
“child1”: {
“name”: “John”,
“year”: 2000
},
“child2”: {
“name”: “Jane”,
“year”: 2003
}
}
“`

Conclusion:
Dictionaries are a fundamental data structure in Python,
and they’re indispensable for any Python programmer.
They provide a clear and intuitive way to store data as
key-value pairs, allowing for efficient data retrieval. With
a good understanding of dictionaries, you’ve now added
a powerful tool to your Python arsenal!
In the next chapter, we’ll explore how to work with
Python classes and learn the basics of object-oriented
programming.

Classes
Assets and Resources:
- Python (Ensure that you have Python installed. If not,
refer to Chapter 1)
- A text editor (Any text editor of your choice, e.g., Visual
Studio Code, PyCharm)

Introduction:
In the realm of programming, a class serves as a
blueprint for creating objects. Objects have member
variables and can perform actions through functions.
Classes are a central part of the object-oriented
programming paradigm that Python supports. Let’s dive
into the concept of classes and understand their
significance and application.

What is a Class?
A class can be visualized as a template or blueprint for
creating objects (instances of the class). These objects
represent data structures composed of attributes (often
called fields or properties) and methods (functions) that
can be applied to the data.
Consider a class as a blueprint for a house. While the
blueprint itself isn’t a house, it dictates how a house
should be built. Similarly, while a class isn’t an instance
of the object, it defines how an object should be created
and behave.

Defining a Class in Python:


Creating a class in Python is simple. Use the `class`
keyword, followed by the class’s name:
“`python
class MyClass:
pass
“`
Here, we’ve defined an empty class named `MyClass`.

Attributes and Methods:


Attributes are the characteristics of a class, whereas
methods represent the actions or behaviors.
Attributes:
Attributes are variables that belong to the class. They
represent data that the class holds.
“`python
class Dog:
species = “Canis familiaris” # This is a class attribute
“`
Methods:
Methods are functions that belong to the class and
define actions.
“`python
class Dog:
species = “Canis familiaris”
def bark(self): # This is a class method
return “Woof!”
“`
The `__init__` Method:
The `__init__` method is a special method in Python,
known as a dunder (double underscore) method. It gets
called automatically when an instance of the class is
created. It’s used to initialize attributes:
“`python
class Dog:
species = “Canis familiaris”
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f”{self.name} says Woof!”
“`
Here, when you create an instance of the Dog class,
you’ll need to provide a name and age, which will be
assigned to the `self.name` and `self.age` attributes,
respectively.

Creating Instances:
Once the class is defined, you can create instances
(objects) of that class:
“`python
dog1 = Dog(“Buddy”, 5)
dog2 = Dog(“Daisy”, 3)
print(dog1.name) # Output: Buddy
print(dog2.bark()) # Output: Daisy says Woof!
“`

Inheritance:
Inheritance is a mechanism where a new class inherits
attributes and methods from an existing class. The
existing class is called the parent or superclass, and the
new class is the child or subclass.
“`python
class GermanShepherd(Dog):
def guard(self):
return f”{self.name} is guarding!”
gs = GermanShepherd(“Rex”, 4)
print(gs.guard()) # Output: Rex is guarding!
“`
Here, the `GermanShepherd` class inherits from the
`Dog` class, thus inheriting the attributes and methods of
the `Dog` class.

Encapsulation:
In OOP, encapsulation means restricting access to some
of the object’s components, preventing the accidental
modification of data. Python uses underscores to
achieve this:
- `_protected`: With a single underscore, it’s a
convention to treat these as “protected”.
- `__private`: With double underscores, Python name-
mangles the attribute name to make it harder to access.
“`python
class Car:
def __init__(self):
self._speed = 0 # protected attribute
self.__color = “Red” # private attribute
“`
Conclusion:
Understanding classes and OOP concepts in Python
lays a foundational base for the Django framework and
web development in general. With this refresher on
Python classes, you’re now prepared to dive into more
intricate Python-related tasks and tackle Django with
confidence!

Remember, practice is key. The more you experiment


with classes, create different objects, and play around
with attributes and methods, the better you’ll understand
the intricacies and potential of Python’s OOP
capabilities.

Section 2:
Project #1 - Word Counter
Website
Project Intro
Assets & Resources:
1. Django Documentation ([available here](
https://docs.djangoproject.com/en/2.2/ ))
2. Python Software Foundation ([available here](
https://www.python.org/ ))
3. Visual Studio Code or any preferred text editor (You
can download Visual Studio Code [here](
https://code.visualstudio.com/ ))

Introduction
Welcome to the first major section of our journey: Project
#1 - Word Counter Website. This project aims to provide
you with a gentle introduction to the world of Django
while ensuring you grasp the fundamental concepts. It
might seem simple, but the Word Counter Website is
carefully chosen to help you understand the basics of
Django’s flow, URL routing, template rendering, and form
handling.

Overview of the Word Counter Website


Imagine a scenario where you have a long essay,
speech, or document, and you want to know which
words appear the most frequently. Our Word Counter
Website is a tool that will do just that. Users will enter
their text, and the application will display the frequency
of each word in descending order. While this might
sound straightforward, you’ll learn numerous
foundational Django concepts along the way.

What will we build?


Homepage: This is where users will be greeted with a
simple interface where they can paste or type their text.
They will then have the option to submit this text to get
the word count.
Results Page: After submitting the text, users will be
taken to this page where the words and their frequencies
will be displayed.

Why start with the Word Counter Website?


As beginners, it’s essential to start with something that
isn’t overwhelming. The Word Counter Website is perfect
because:
1. Simplicity: The project is straightforward, which means
you won’t get lost in complex logic or multiple
functionalities.
2. Covers the Basics: Despite its simplicity, it introduces
the core elements of a Django application: URL routing,
views, templates, and form handling.
3. Immediate Results: This project will give you the
satisfaction of building a complete web application,
motivating you for the more complex projects ahead.

What will you gain?


By the end of this section, you will:
1. Understand how to set up a new Django project.
2. Familiarize yourself with Django’s directory structure.
3. Handle URL routing and link it with specific views.
4. Design templates to display content to the end-users.
5. Process user input through forms.
6. Learn how to display processed data back to the user.

Pre-requisites
Before diving into the project, ensure you have:
1. Completed the Python refresher section. This project
assumes you are familiar with basic Python concepts.
2. Installed Django (We’ll cover this in the next to next
chapter if you haven’t).
3. A text editor ready, like Visual Studio Code.
4. An open mind and the eagerness to learn!

Conclusion
The Word Counter Website will be our stepping stone
into the vast and exciting world of Django. By the end of
this project, not only will you have a functional website to
show for your efforts, but you’ll also possess the
foundational knowledge necessary to tackle more
advanced Django projects.

Django Cheat Sheet


Assets and Resources for this Chapter:
- Django documentation: [Official Django Documentation]
( https://docs.djangoproject.com/ )
- Django source code: Available via pip install command
- Python: [Official Python Download Page](
https://www.python.org/downloads/ )

Introduction:
A cheat sheet is a compact collection of information,
used for quick references. In this chapter, we will put
together some of the most commonly used Django
commands, concepts, and snippets, tailored specifically
for our Word Counter Website project. Keep this chapter
handy while working through the project, as it can act as
your quick guide to recalling the basics.

1. Setting Up Django
- Install Django:
“`python
pip install django
“`
- Start a new Django project:
“`bash
django-admin startproject projectname
“`
- Start a new Django app:
“`bash
python manage.py startapp appname
“`

2. Django Project Structure Overview


- `manage.py`: The command-line utility for
administrative tasks.
- `__init__.py`: Tells Python that this folder should be
considered a package.
- `settings.py`: Settings/configuration for the Django
project.
- `urls.py`: The URL declarations for the Django project.
- `wsgi.py`: An entry point for WSGI-compatible web
servers to serve the project.

3. Basic Commands
- Run the development server:
“`bash
python manage.py runserver
“`
- Run migrations: (to apply changes made in models to
the database)
“`bash
python manage.py migrate
“`
- Make migrations after model changes:
“`bash
python manage.py makemigrations
“`
- Create a superuser for the admin interface:
“`bash
python manage.py createsuperuser
“`

4. Defining URLs
urls.py:
“`python
from django.urls import path
from . import views
urlpatterns = [
path(”, views.home, name=‘home’),
]
“`
5. Views and Templates
views.py:
“`python
from django.shortcuts import render
def home(request):
return render(request, ‘home.html’)
“`
home.html:
“`html
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
</head>
<body>
<h1>Welcome to Word Counter!</h1>
</body>
</html>
“`

6. Forms
forms.py: (you may need to create this file inside your
app folder)
“`python
from django import forms
class WordInputForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
“`
home.html: (using the form)
“`html
<form method=“post”>
{% csrf_token %}
{{ form.as_p }}
<button type=“submit”>Count</button>
</form>
“`

7. Model Basics
models.py:
“`python
from django.db import models
class Word(models.Model):
text = models.CharField(max_length=255)
“`
- Using the model in views:
“`python
from .models import Word
def save_word(request):
word = Word(text=request.POST[‘text’])
word.save()
“`

8. Admin Interface
- Register models with admin:
admin.py:
“`python
from django.contrib import admin
from .models import Word
admin.site.register(Word)
“`

9. Static Files
home.html: (linking to a static CSS file)
“`html
Other documents randomly have
different content
back
back
back
back
back
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like