Python Basics

Table of Contents

  • Setting Up Python
  • Python Syntax
  • Basic Operations
  • Control Flow
  • Data Structures
  • Functions
  • Modules and Libraries
  • Introduction to Pandas
  • Data Visualization

Why Scripting?

  • Reproducibility
  • Handling large data sets
  • Advanced statistical analysis
  • Graphs and visualizations

Introduction to Python

  • What is Python?
    • Python is a high-level, interpreted programming language known for its simplicity and readability.
  • Why Python?
    • Versatile: Python can be used for web development, data analysis, machine learning, and more.
    • Large Community: Python has a vast user community and a rich ecosystem of libraries.
    • Cross-Platform: Python runs on various platforms, including Windows, macOS, and Linux.

Setting Up Python

  • Programming Language: Python

  • Interface IDE: VS Code, Jupyter Notebooks

  • https://colab.research.google.com/

Python Syntax

Assignment Operators

  • In Python, assignment operators are used to assign values to variables.
  • The = operator is used.
  • # Example of assignment with = operator
    x = 10  # Assigns the value 10 to the variable x
    print("x =", x)

Naming Conventions

In Python, there are naming conventions for variables and functions:

  • name_like_this (snake_case) - Used for variable and function names.

  • # Example of snake_case
    my_variable_name = 42
    print("Variable:", my_variable_name)
    
    def my_function_name():
        pass
  • name.like.this - Not used in Python.

  • name like this - Wrong naming convention in Python.

Variables and Data Types

name = "John" #string
print(name)

age = 30 #integer 
print(age)

height = 6.2 #float
print(height)

is_student = True # boolean
print(is_student)

Comments

# This is a single-line comment

"""
This is a
multi-line comment
"""

Indentation

if age > 18:
    print("Adult")
else:
    print("Minor")

Basic Operations

Logical Operators

Operation Description Operation Description
a == b a equal to b a != b a not equal to b
a < b a less than b a > b a greater than b
a <= b a less than or equal to b a >= b a greater than or equal to b

Logical operators are used for comparisons and logical operations.

  • == is used to check if two values are equal.
  • # Example of ==
    x = 5
    y = 10
    is_equal = x == y  # is_equal will be False
    print("Is x equal to y?", is_equal)
  • < is used to check if one value is less than another.
  • # Example of <
    x = 5
    y = 10
    is_less = x < y  # is_less will be True
    print("Is x less than y?", is_less)
  • > is used to check if one value is greater than another.

  • # Example of >
    x = 5
    y = 10
    is_greater = x > y  # is_greater will be False
    print("Is x greater than y?", is_greater)
  • or is used for logical OR operations.

  • # Example of or
    has_apple = True
    has_banana = False
    want_fruit = has_apple or has_banana  # want_fruit will be True
    print("Do you want fruit?", want_fruit)
  • and is used for logical AND operations.
  • # Example of and
    is_adult = True
    has_id = True
    can_enter_club = is_adult and has_id  # can_enter_club will be True
    print("Can you enter the club?", can_enter_club)

Arithmetic Operations

Operator Name Description
a + b Addition Sum of a and b
a - b Subtraction Difference of a and b
a * b Multiplication Product of a and b
a / b True division Quotient of a and b
a // b Floor division Quotient of a and b, removing fractional parts
a % b Modulus Integer remainder after division of a by b
a ** b Exponentiation a raised to the power of b
-a Negation The negative of a
+a Unary plus a unchanged (rarely used)
addition = 5 + 3
print(addition)

subtraction = 10 - 2
print(subtraction)

multiplication = 4 * 6
print(multiplication)

division = 15 / 3
print(division)

String Operations

greeting = "Hello, "
name = "Alice"
full_greeting = greeting + name
print(full_greeting)

Data Structures

Lists

numbers = [1, 2, 3, 4, 5]
print(numbers)

# Access the first element

fruits = ["apple", "banana", "cherry"]
first_fruit = fruits[0]
print(first_fruit)

Tuples

coordinates = (3, 4)
print(coordinates)

# Access the second element
y_coordinate = coordinates[1]
print(y_coordinate)

Dictionaries

student = {
    "name": "Alice",
    "age": 20,
    "grade": "A"
}
print(student)

# Access the age
student_age = student["age"]
print(student_age)

Sets

unique_numbers = {1, 2, 3, 4, 5}
print(unique_numbers)

Control Flow

Loops

for loop

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

while loop

count = 0
while count < 5:
    print(count)
    count += 1

Conditional Statements (if, elif, else)

age = 20
if age < 18:
    print("You are a minor")
elif age >= 18 and age < 65:
    print("You are an adult")
else:
    print("You are a senior citizen")

Functions

In Built Functions

  • Functions in Python are blocks of code that perform specific tasks.
  • We use functions by calling them with parentheses ().
  • # Example of using a built-in function
    numbers = [1, 2, 3, 4, 5]
    result = sum(numbers)  # Calls the sum function to calculate the sum
    print("Sum of numbers:", result)
  • Functions can also take arguments, perform actions, and return values.

User Defined Functions

def greet(name):
    return "Hello, " + name

# Call the function
greeting = greet("John")
print(greeting)

Function Arguments

def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)

Return Statements

def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

# Check if a number is even
even = is_even(6)
print(even)

–> –> –> –> –>

Modules and Libraries

Installation

  • Install once per machine
  • 
    pip install `package_name`
  • Load once per session
  • 
    import `package_name`

Importing Modules

import math
print(math.sqrt(25))

Using Built-in Modules (e.g., math, random)

import random
random_number = random.randint(1, 10)
print(random_number)

Introduction to Pandas

What is Pandas?

  • Pandas is a powerful Python library for data manipulation and analysis.
  • It provides easy-to-use data structures and data analysis tools.

Why Pandas?

  • Pandas is widely used in data science and data analysis due to its efficiency and versatility.
  • It excels at handling structured data, such as spreadsheets or databases.

Pandas Basics

  • Installing Pandas
  • # How to install Pandas using pip.
  • Importing Pandas
  • import pandas as pd

Pandas Data Structures

Series

data = [10, 20, 30, 40, 50]
series = pd.Series(data)
print(series)

DataFrame

data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)

Loading Data

Reading CSV Files

df = pd.read_csv('data.csv')
print(df)

Viewing Data

#Display the first few rows of the DataFrame 
 print(df.head()) 

# Display the last few rows of the DataFrame 
print(df.tail) 

Data Visualization

Introduction

  • Data visualization is essential for understanding data and presenting insights.
  • We’ll explore two popular Python libraries for data visualization: Matplotlib and Seaborn.

Matplotlib

  • Powerful library for creating visualizations.
  • Supports static, animated, and interactive plots.
  • Wide range of customization options.

Installing Matplotlib

You can install Matplotlib using pip:

pip install matplotlib

Basic Matplotlib Example

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 7, 5]

# Create a line plot
plt.plot(x, y)

# Add labels and a title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')

# Display the plot
plt.show()

Seaborn

  • Built on top of Matplotlib.
  • Simplifies creating informative and attractive visualizations.
  • Ideal for statistical graphics.

Installing Seaborn

You can install Seaborn using pip:

pip install seaborn

Basic Seaborn Example

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 5, 12, 7]

# Create a bar plot
sns.barplot(x=categories, y=values)

# Add labels and a title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Simple Bar Plot')

# Display the plot
plt.show()