Build a Django Web App with Python
Python Basics
Python's Clean Syntax
Python is famous for its clean and readable syntax. Unlike many other programming languages that use curly braces {} to define blocks of code, Python uses indentation. This might seem strange at first, but it forces programmers to write code that is visually organized and easy to follow.
Think of it like an outline for a paper. Major points are flush left, sub-points are indented, and points under those are indented even further. Python code follows a similar structure. This strict indentation rule makes the code remarkably consistent, no matter who writes it.
In Python, whitespace isn't just for looks—it's part of the syntax that gives the code its structure.
Let's look at the classic first program everyone writes, "Hello, World!".
# This is a comment. Python ignores lines starting with #
print("Hello, World!")
Core Data Types
At its core, programming is about working with data. Python has several built-in data types to represent different kinds of information. When you create a variable, you're essentially giving a name to a piece of data stored in memory.
# Assigning the integer 42 to the variable 'age'
age = 42
# Assigning the string "Alice" to the variable 'name'
name = "Alice"
Here are some of the most common data types you'll encounter.
| Data Type | Description | Example |
|---|---|---|
String (str) | A sequence of characters, used for text. | "Hello" or 'Python' |
Integer (int) | Whole numbers without a fractional part. | 10, -5, 0 |
Float (float) | Numbers with a decimal point. | 3.14, -0.001 |
Boolean (bool) | Represents truth values. | True or False |
Making Decisions and Repeating Actions
Control structures allow you to direct the flow of your program. You can make it execute certain code only if a condition is met, or repeat a block of code multiple times. These are the tools that make programs dynamic and intelligent.
The if statement is for making decisions. It checks if a condition is true and runs a block of code accordingly. You can add elif (else if) for more conditions and else for a default action.
temperature = 25
if temperature > 30:
print("It's a hot day!")
elif temperature > 20:
print("It's a pleasant day.")
else:
print("It might be cold.")
# Output: It's a pleasant day.
For repetition, we use loops. A for loop iterates over a sequence (like a list of items), while a while loop runs as long as a condition remains true.
# A for loop to print numbers 0 to 4
for i in range(5):
print(i)
# A while loop that counts down from 3
count = 3
while count > 0:
print(f"Countdown: {count}")
count = count - 1 # or count -= 1
Functions and Error Handling
As your programs grow, you'll find yourself writing the same code over and over. Functions are reusable blocks of code that perform a specific task. You define a function once and can then "call" it whenever you need it. This keeps your code organized, efficient, and easy to debug.
function
noun
A named sequence of statements that performs a computation. It can take inputs, called arguments, and may return an output value.
# Define a function that greets a person
def greet(name):
return f"Hello, {name}!"
# Call the function with an argument
message = greet("Bob")
print(message)
# Output: Hello, Bob!
But what happens when things go wrong? A user might enter text where a number is expected, or a file you're trying to read might not exist. These situations cause errors, or exceptions, that can crash your program.
To prevent this, Python uses try...except blocks for error handling. You place the code that might fail inside the try block. If an error occurs, the code in the except block is executed, and the program can continue running gracefully.
try:
# This line will cause a ZeroDivisionError
result = 10 / 0
print(result)
except ZeroDivisionError:
print("Oops! You can't divide by zero.")
print("The program continued without crashing.")
Good error handling makes your application robust and user-friendly by anticipating problems before they happen.
Now let's check your understanding of these fundamental concepts.
How does Python define the structure and scope of code blocks?
Which code block is designed to catch and handle errors that might occur during program execution?
These building blocks—syntax, data types, control structures, functions, and error handling—form the foundation of all Python programming. Mastering them is the first and most important step toward building anything, from simple scripts to complex web applications.