Mastering NLP with Python and Scikit-learn
Python Basics
The Building Blocks of Python
Python is known for its clean and readable syntax. It feels a lot like writing in plain English, which makes it a great language for beginners. Let's start with the absolute basics: variables and data types.
A variable is like a labeled box where you can store information. You give it a name and put something inside. In Python, you can create a variable and assign it a value using the equals sign (=).
# This is a comment. Python ignores it.
# A variable storing an integer (a whole number)
user_age = 30
# A variable storing a float (a number with a decimal)
item_price = 19.99
# A variable storing a string (text)
user_name = "Alex"
# A variable storing a boolean (True or False)
is_logged_in = True
The type of data a variable holds is important. In the example above, user_age is an integer, item_price is a float, user_name is a string, and is_logged_in is a boolean. Python figures out the type automatically, so you don't have to declare it explicitly.
Storing and Organizing Data
Often, you need to work with collections of data, not just single values. That's where data structures come in. They are containers that organize and group data in different ways. The two most common ones you'll use are lists and dictionaries.
A list is an ordered collection of items. Think of it as a grocery list where the order of items matters. You can add, remove, or change items in a list.
# A list of numbers
scores = [88, 92, 100, 75]
# A list of strings
shopping_list = ["apples", "bread", "milk"]
# Accessing an item by its index (starts at 0)
first_item = shopping_list[0] # This will be "apples"
# Changing an item
shopping_list[1] = "whole wheat bread"
A dictionary, on the other hand, stores data as key-value pairs. Instead of using a numeric index, you use a unique key to access its corresponding value. This is useful when you want to store related pieces of information, like data about a specific user.
# A dictionary representing a user
user_profile = {
"name": "Alex",
"age": 30,
"city": "New York"
}
# Accessing a value by its key
user_city = user_profile["city"] # This will be "New York"
# Adding a new key-value pair
user_profile["email"] = "alex@example.com"
Making Decisions and Repeating Actions
Programs rarely run straight from top to bottom. They need to make decisions and perform repetitive tasks. This is handled by control flow statements. The most common are if statements and loops.
An if statement checks if a condition is true and runs a block of code only if it is. You can also add elif (else if) and else to handle other conditions.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("Better bring a jacket.")
else:
print("The weather is pleasant.")
Loops are for repeating actions. A for loop is great for going through each item in a sequence, like a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like to eat {fruit}s.")
A while loop continues running as long as a certain condition remains true. It's useful when you don't know ahead of time how many times you need to repeat the action.
count = 0
while count < 3:
print(f"Count is {count}")
count = count + 1 # Increment the count
Reusable Code with Functions and Modules
As your programs get bigger, you'll find yourself writing the same bits of code over and over. Functions allow you to package a block of code, give it a name, and run it whenever you want. This principle is known as Don't Repeat Yourself (DRY).
function
noun
A named block of code that performs a specific task and can be called on demand.
# Define a function that takes two numbers and adds them
def add_numbers(num1, num2):
result = num1 + num2
return result
# Call the function and store its output
sum_result = add_numbers(5, 10)
print(sum_result) # This will print 15
Python also has a vast standard library of pre-written code that you can use. This code is organized into modules. A module is simply a Python file with functions, variables, and other code that you can import into your own scripts.
For example, if you need to perform complex mathematical operations, you can import the
mathmodule.
# Import the math module to use its contents
import math
# Use the sqrt function from the math module
number = 64
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}")
Learning to import and use modules is a key skill. It saves you from reinventing the wheel and gives you access to powerful, optimized code written by others.
Now, let's test your understanding of these core concepts.
What is the final value of count after this code runs?
count = 0
while count < 5:
count += 1
Which data structure in Python is used to store data in key-value pairs?
With these building blocks, you have a solid foundation for writing Python programs. You can store data, control how your code executes, and organize it into reusable pieces.