Python for Data Science and AI
Python Basics
The Building Blocks of Code
Python is known for its clean and readable syntax, which looks a lot like plain English. This makes it a great language for beginners. Let's start with the most basic concepts: variables and data types.
Variable
noun
A container for storing data values. In Python, you can think of it as a label you assign to a value.
When you create a variable, you don't need to specify the type of data it will hold. Python figures it out automatically. There are a few fundamental data types you'll use all the time:
| Data Type | Description | Example |
|---|---|---|
| Integer | Whole numbers | 10, -5, 0 |
| Float | Numbers with decimals | 3.14, -0.5 |
| String | Text, enclosed in quotes | "Hello, world!", 'Python' |
| Boolean | Represents truth values | True, False |
Here’s how you would create variables with these different data types.
# Assigning values to variables
# An integer
user_age = 28
# A float
item_price = 19.99
# A string
user_name = "Alex"
# A boolean
is_active = True
# You can print them to see their values
print(user_name)
print(item_price)
Making Decisions and Repeating Actions
Programs often need to make decisions or perform repetitive tasks. That's where control structures come in. They control the flow of your code.
To make decisions, we use if, elif (short for "else if"), and else statements. The code inside an if block only runs if its condition is true. If it's false, Python checks the next elif condition, and so on. The else block runs if no other conditions are met.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("It's a bit chilly.")
else:
print("The weather is pleasant.")
# Output will be: The weather is pleasant.
For repetitive tasks, we use loops. A for loop is great for iterating over a sequence of items, like a list of numbers or characters in a string. A while loop keeps running as long as a certain condition remains true.
# A for loop that prints numbers from 0 to 4
for i in range(5):
print(i)
# A while loop that counts down from 3
count = 3
while count > 0:
print(count)
count = count - 1 # or count -= 1
print("Liftoff!")
Loops are your best friend for automating tasks. If you find yourself writing the same line of code over and over, you probably need a loop.
Creating Reusable Code with Functions
As your programs get more complex, you'll want to organize your code into reusable pieces. Functions are perfect for this. A function is a named block of code that performs a specific task. You can "call" a function whenever you need it, instead of rewriting the same logic multiple times.
You define a function using the def keyword. Functions can take inputs, called parameters, and can return an output value using the return keyword.
# Define a function to greet a user
def greet(name):
return f"Hello, {name}! Welcome."
# Call the function with different inputs
message_for_maria = greet("Maria")
message_for_sam = greet("Sam")
print(message_for_maria)
print(message_for_sam)
Handling the Unexpected
Sometimes, code doesn't run as expected. An error, or an exception, can crash your program. For example, trying to divide a number by zero is a mathematical impossibility that will cause an error.
Instead of letting the program crash, you can handle these errors gracefully using a try...except block. You put the code that might cause an error in the try block. If an error occurs, the code in the except block is executed, and the program continues running.
numerator = 10
denominator = 0
try:
# This line will cause a ZeroDivisionError
result = numerator / denominator
print(result)
except ZeroDivisionError:
# This block runs because the error occurred
print("Error: You can't divide by zero!")
print("The program continued without crashing.")
With these fundamentals—variables, data types, control structures, functions, and error handling—you have the core tools to start writing powerful Python programs. Now, let's test your knowledge.