M10 - Python for Analytics
Using Python for data analysis and visualization tasks.
Python Basics
Python Environment
To start programming in Python, it's essential to set up the Python environment. You can install Python from the official website (https://www.python.org/downloads/). Once installed, you can use various Integrated Development Environments (IDEs) like PyCharm, Jupyter Notebook, or even simple text editors like VSCode. After installation, you can verify your setup by opening a terminal or command prompt and typing python --version. This command should return the installed version of Python. Additionally, using a package manager like pip allows you to install libraries such as NumPy and pandas, which are crucial for data analytics. Key points to remember include:
- Ensure Python is added to your system's PATH.
- Familiarize yourself with the IDE of your choice.
- Learn how to run Python scripts from the command line.
Variables
Variables in Python are used to store data values. They are created by assigning a value to a name using the assignment operator =. Python is dynamically typed, meaning you do not need to declare the variable type explicitly. For example:
age = 30
name = "John"
In this example, age is an integer, and name is a string. Variable names must start with a letter or an underscore and can contain letters, numbers, and underscores. It's important to follow naming conventions for readability, such as using lowercase letters and underscores for multi-word variables (e.g., first_name). Key points include:
- Use meaningful variable names.
- Avoid using reserved keywords.
- Understand scope: variables defined inside a function are not accessible outside.
Data Types
Python has several built-in data types, which can be categorized into mutable and immutable types. The main data types include:
- Integers: Whole numbers, e.g.,
x = 5. - Floats: Decimal numbers, e.g.,
y = 3.14. - Strings: Text data, e.g.,
name = "Alice". - Booleans: True or False values, e.g.,
is_active = True. - Lists: Ordered collections of items, e.g.,
numbers = [1, 2, 3]. - Dictionaries: Key-value pairs, e.g.,
person = {"name": "John", "age": 30}. Understanding these data types is crucial for effective data manipulation and analysis. Remember that you can check the type of a variable using thetype()function, e.g.,type(name)will return<class 'str'>.
Operators
Operators in Python are used to perform operations on variables and values. They can be categorized into several types:
- Arithmetic Operators: Used for mathematical calculations. Examples include:
- Addition:
+ - Subtraction:
- - Multiplication:
* - Division:
/ - Modulus:
%
- Addition:
- Comparison Operators: Used to compare values. Examples include:
- Equal to:
== - Not equal to:
!= - Greater than:
> - Less than:
<
- Equal to:
- Logical Operators: Used to combine conditional statements. Examples include:
- AND:
and - OR:
or - NOT:
notFor instance, to check if a number is both greater than 10 and less than 20, you can use:
- AND:
if number > 10 and number < 20:
print("Number is between 10 and 20")
Understanding operators is essential for controlling the flow of your programs.
Program Flow
Conditional Statements
Conditional statements allow you to execute certain pieces of code based on specific conditions. The most common conditional statement is the if statement. The syntax is as follows:
if condition:
# code to execute if condition is True
elif another_condition:
# code to execute if another_condition is True
else:
# code to execute if all conditions are False
For example:
age = 18
if age >= 18:
print("You are an adult.")
elif age < 13:
print("You are a child.")
else:
print("You are a teenager.")
This structure allows for clear decision-making in your code. Remember to use proper indentation as it defines the blocks of code that belong to each condition.
Loops
Loops are used to execute a block of code repeatedly. Python has two primary types of loops: for loops and while loops. A for loop iterates over a sequence (like a list or a string). The syntax is:
for item in sequence:
# code to execute for each item
For example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
A while loop continues to execute as long as a specified condition is true:
while condition:
# code to execute while condition is True
For example:
count = 0
while count < 5:
print(count)
count += 1
Loops are essential for tasks that require repeated actions, such as iterating through data.
Functions
Functions are reusable blocks of code that perform a specific task. They help organize code and make it more manageable. You define a function using the def keyword followed by the function name and parentheses. For example:
def greet(name):
return f"Hello, {name}!"
You can call this function by passing an argument:
print(greet("Alice")) # Output: Hello, Alice!
Functions can also take multiple parameters and return values. They can improve code readability and reduce redundancy. Key points to remember:
- Use descriptive names for functions.
- Keep functions focused on a single task.
- Utilize return statements to output results.