Python Full-Stack Development Mastery
Python Basics
The Building Blocks
Every language, whether spoken or for programming, has its own grammar and rules. In Python, this is called syntax. It's the set of rules that defines how a Python program will be written and interpreted. The good news is that Python's syntax is known for being clean and readable, which makes it a great language for beginners.
One of the most fundamental concepts is the variable. Think of a variable as a labelled container where you can store information. You give it a name, and you can put data inside it. Later, you can refer to the data just by using the container's name.
Variable
noun
A symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name.
Assigning a value to a variable in Python is straightforward. You use the equals sign (=).
# This is a comment. Python ignores lines starting with #
# Assigning a string to a variable
user_name = "Alex"
# Assigning a number to a variable
year = 2024
# You can print the contents of a variable
print(user_name)
print(year)
Data Types and Structures
Variables can hold different kinds of data. These are called data types. Python has several built-in types, but the most common ones are numbers, strings (text), and booleans (true or false).
Besides simple types, Python also has data structures that can hold collections of data. The most common are lists, tuples, and dictionaries.
| Data Type | Description | Example |
|---|---|---|
String (str) | A sequence of characters | "Hello, World!" |
Integer (int) | A whole number | 102 |
Float (float) | A number with a decimal point | 98.6 |
Boolean (bool) | Represents True or False | True |
List (list) | An ordered, changeable collection of items | ["apple", "banana", "cherry"] |
Dictionary (dict) | An unordered collection of key-value pairs | {"name": "John", "age": 30} |
Lists are incredibly versatile. You can add, remove, and change items in a list. They are created using square brackets [].
# A list of numbers
scores = [88, 92, 100, 75]
# Access the first item (indexing starts at 0)
print(scores[0]) # Outputs: 88
# Add a new score to the end of the list
scores.append(95)
print(scores) # Outputs: [88, 92, 100, 75, 95]
Dictionaries store data in key-value pairs. Instead of accessing items by their position, you access them using a unique key. They are created with curly braces {}.
# A dictionary representing a user
user = {
"first_name": "Maria",
"last_name": "Lopez",
"is_active": True
}
# Access the value associated with the 'first_name' key
print(user["first_name"]) # Outputs: Maria
Making Decisions and Repeating Actions
A program's real power comes from its ability to make decisions and perform repetitive tasks. This is known as control flow.
To make decisions, we use if statements. An if statement checks if a condition is true. If it is, a block of code is executed. You can also provide elif (else if) and else clauses to handle other conditions.
temperature = 25
if temperature > 30:
print("It's a hot day!")
elif temperature > 20:
print("It's a pleasant day.")
else:
print("It's a bit chilly.")
# Outputs: It's a pleasant day.
To repeat actions, we use loops. There are two main types: for loops and while loops.
A for loop is used for iterating over a sequence (like a list). It runs once for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like to eat {fruit}s.")
A while loop repeats as long as a certain condition is true.
count = 0
while count < 3:
print(f"Count is {count}")
count = count + 1 # Increment the counter
Control flow structures like
ifstatements and loops allow you to write dynamic programs that can respond differently to different inputs and handle large amounts of data efficiently.
Reusable Code and Error Handling
As programs grow, you'll find yourself writing the same piece of code over and over. Functions allow you to package a block of code, give it a name, and then call it whenever you need it. This practice is called 'Don't Repeat Yourself' (DRY) and is a core principle of good programming.
# Define a function that greets a user
def greet_user(name):
return f"Hello, {name}!"
# Call the function with different arguments
message_one = greet_user("David")
message_two = greet_user("Sarah")
print(message_one)
print(message_two)
Sometimes, you need functionality that someone else has already written. Python has a vast standard library of code organised into modules. You can use the import keyword to bring that code into your program.
For example, the math module provides various mathematical functions.
# Import the math module to use its functions
import math
# Calculate the square root of 16
result = math.sqrt(16)
print(result) # Outputs: 4.0
Finally, things can go wrong in a program. A user might enter text where a number is expected, or a file you're trying to read might not exist. These events are called exceptions. Good programs anticipate these issues and handle them gracefully.
Python uses try and except blocks for error handling. You put the code that might cause an error in the try block, and the code to handle the error in the except block.
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"The result is {result}")
except ValueError:
print("That wasn't a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
This code tries to convert user input to an integer and divide 10 by it. If the user enters text, a ValueError occurs. If they enter 0, a ZeroDivisionError occurs. The except blocks 'catch' these specific errors and print a helpful message instead of crashing the program.
In Python, which symbol is used to assign a value to a variable?
Which data structure is created using curly braces {} and stores data in key-value pairs?
With these fundamentals—variables, data types, control flow, functions, and error handling—you have the core tools to start building useful programs in Python.