PYTHON PROGRAMMING
OVERVIEW
By: SEK SOCHEAT
Lecture Artificial Intelligence
2023 – 2024
Mobile: 017 879 967 Y2S2 – DCS – NU
Email:
[email protected] TABLE OF CONTENTS
Python Programming Overview
• Setting up the Python Environment
• Basic Syntax
• Data Types
• Control Structures
• Functions
• Basic Libraries (NumPy, pandas)
2
SETTING UP PYTHON PROGRAMMING
SETTING UP THE PYTHON ENVIRONMENT
Step 1: Install Python
Download and Install: Download Python from the official Python
website (python.org) or another trusted source.
• During the installation on Windows, make sure to check the box
that says "Add Python to PATH" to make Python accessible
from the command line.
• On macOS and Linux, Python is often pre-installed, but you
might want to install or update it to the latest version using the
website or a package manager like Homebrew.
4
SETTING UP THE PYTHON ENVIRONMENT
Step 2: Choose an IDE or Code Editor
• Integrated Development Environment (IDE): Install an IDE such as
PyCharm or Spyder. These are particularly useful for AI development
because they offer integrated tools for debugging and package
management.
• PyCharm: Download from JetBrains.
• Spyder: Typically installed with Anaconda, which includes it by default.
• Text Editor: Visual Studio Code (VS Code) is a lightweight, powerful
editor that supports Python development via extensions.
• VS Code: Download from Visual Studio Code.
5
SETTING UP THE PYTHON ENVIRONMENT
Step 3: Install Anaconda (Optional but Recommended for AI)
• Anaconda: This is highly recommended for AI
programming because it includes a suite of scientific tools
and libraries pre-installed, such as NumPy, pandas, and
SciPy, which are essential for data science and AI.
• Download Anaconda from Anaconda.com.
• Follow the installation instructions on their website.
6
SETTING UP THE PYTHON ENVIRONMENT
Step 4: Set Up a Virtual Environment
• Creating a Virtual Environment: Use Anaconda or the
built-in venv module in Python to create isolated
environments for different projects.
• Using conda: Open the Anaconda Command Prompt
and type “conda create --name aienv python=3.x”,
replacing 3.x with the specific Python version you need.
• Using venv: In your system's command line, navigate to
your project directory and run “python -m venv aienv”.
7
SETTING UP THE PYTHON ENVIRONMENT
Step 5: Activate the Virtual Environment
• Activate Environment:
• Using conda: In the Anaconda Command Prompt,
type conda activate aienv.
• Using venv: On Windows, aienv\Scripts\activate;
on Unix or MacOS, source aienv/bin/activate.
8
SETTING UP THE PYTHON ENVIRONMENT
Step 6: Install Necessary AI Libraries
• Install AI Libraries: With your environment
activated, install Python libraries commonly used in
AI:
• pip install numpy pandas scipy matplotlib
scikit-learn tensorflow keras
• These libraries provide foundational tools for data
manipulation, machine learning, and deep learning.
9
REVIEWING OF PYTHON PROGRAMMING
Basic Syntax in Python Programming
1. Variables and Data Types 5. Control Structures (if statement)
x=5 # integer Learning the basic syntax of Python if a > b:
y = 3.14 # float is crucial for anyone beginning to print("a is greater than b")
name = "Alice" # string elif a < b:
code in this versatile and powerful print("a is less than b")
is_active = True # boolean
programming language. Python is else:
2. Comments renowned for its readability and print("a and b are equal")
# This is a single-line comment simplicity, making it an excellent 6. Loops (while and for loops)
"""This is multi-line comments""" choice for beginners and i=1 num = [1, 2, 3, 4, 5]
while i < 6: for n in num:
'''This is multi-line comments too''' professionals alike. print(i) print(n)
3. Indentation Mastering these fundamentals will i += 1
if x > 0: provide a solid foundation for 7. Functions
print("x is positive")
elif x < 0:
advancing in Python programming, def greet(name):
allowing you to tackle more complex print("Hello, " + name)
print("x is negative")
else: problems and projects effectively.
greet("Alice")
print("x is zero") Whether you're automating tasks,
4. Operators analyzing data, or building full-scale 8. Importing Modules
Equals: a == b applications, understanding these import math
Not Equals: a != b basic syntax rules is essential. print(math.sqrt(16)) # prints 4.0
Less than: a < b
Data Types in Python Programming
5. Tuples (tuple)
1. Numbers
Integers or int: (e.g., 5, -3, 42.)
In Python, data types are crucial coordinates = (10.0, 20.0)
Floating Point Numbers or (float): (e.g., because they dictate what kind of
3.14, -0.001, 2e2 (which is 200.0)) operations can be performed on the
Complex Numbers (complex): (e.g., 1 + 3j)
data stored in a variable. Python has
several built-in data types, and
2. Strings (str)
understanding these is fundamental 6. Dictionaries (dict)
string1 = 'Hello' person = {"name": "Alice", "age": 25,
for effectively programming in "city": "New York"}
string2 = "World"
Python.
paragraph = """This is a
multi-line string."""
Understanding these data types and
their properties (like mutability, 7. Sets (set)
3. Boolean (bool)
order, and how they handle colors = {"red", "green", "blue"}
is_active = True duplicates) is key to effective Python
has_errors = False programming. It enables you to
choose the right type for your data,
ensuring optimal performance and 8. NoneType (None)
4. Lists (list)
ease of development in your result = None
fruits = ["apple", "banana", "cherry"]
applications.
numbers = [1, 2, 3, 4.5, "five"]
Conditional Statements
else Statement Nested Conditional
elif Statement Statements
if Statement if temperature > 30: age = 45
if temperature > 30:
print("It's a hot day.") if age >= 18:
print("It's a hot day.")
if temperature > 30: elif temperature > 20: if age > 60:
elif temperature > 20:
print("It's a hot day.") print("It's a nice day.") print("Senior")
print("It's a nice day.")
else: else:
print("It's cold.") print("Adult")
The if statement is used elif (short for else if)
to test a condition and else:
allows you to check
execute a block of code multiple expressions for The else statement is print("Minor")
only if the condition is True and execute a used to execute a block
A complex decision
true. block of code as soon as of code if none of the
structures by placing an
one of the conditions specified conditions are
if statement inside
evaluates to True. true.
another if statement.
Loops Statements
for Loop while & break Loop continue & pass Loop Nested Loop
for num in [1, 2, 3, 4, 5, 6]: count = 0 for i in range(10):
for i in range(7):
while count < 5: if i % 2 == 0:
print(num) for j in range(7):
print(count) continue
print(i) print('*', end=' ')
A for loop is used for count += 1
iterating over the continue is used to skip the current print()
A while loop repeats as long block and return to the for or while
elements of a sequence. as a certain boolean statement for the next iteration.
condition is met. for i in range(10):
This nested loop
structure is a
for i in range(5): for i in range(10): if i % 2 == 0:
straightforward way to
if i == 5: pass
print(i) create a grid layout or
break # Exit the loop else:
perform any operation
You can use the range() print(i)
print(i) that requires a row-
function if you need a break is used to exit a for or
pass is a null statement for when a
column based
statement is required syntactically
sequence of numbers. while loop prematurely. but no code needs to be executed. processing.
Functions in Python Programming
1. Defining a Function 5. Return Values
def add_numbers(x, y):
def greet(name): return x + y
print(f"Hello, {name}!") Functions are fundamental building
blocks in Python programming, result = add_numbers(5, 3)
2. Calling a Function allowing you to create modular, print(result) # Outputs: 8
greet("SEK") # Outputs: Hello, SEK! reusable pieces of code. They help 6. Docstrings
you organize your code better, make def square(number):
3. Parameters and Arguments it more readable, and allow for better """Return the square of a number."""
def describe_pet(pet_type, pet_name): scalability. return number ** 2
print(f"I have a {pet_type} named print(square.__doc__)
{pet_name}.")
7. Variable Scope
Functions are a critical component of
def test_scope():
describe_pet("hamster", "Harry") Python and are used extensively in all inside_variable = "Inside the function"
describe_pet(pet_name="Daisy", types of applications. Mastering how
pet_type="dog") # Keyword arguments print(inside_variable)
to define and use functions is test_scope()
4. Default Parameter Values essential for any Python programmer #print(inside_variable) # Error occurred
def describe_pet(pet_name, pet_type="dog"): looking to write clean, effective, and
8. Lambda Functions
print(f"I have a {pet_type} named {pet_name}.") maintainable code.
multiply = lambda x, y: x * y
describe_pet("Kiki") # Kiki is assumed to be a dog print(multiply(5, 6)) # Outputs: 30
BASIC LIBRARY FOR AI IN PYTHON
BASIC LIBRARIES (NUMPY, PANDAS)
NumPy
NumPy, which stands for Numerical Python, is the foundational package
for scientific computing in Python. It provides support for large, multi- Example:
dimensional array and matrix data structures, along with a large collection import numpy as np
of high-level mathematical functions to operate on these arrays.
# Create a NumPy array
Key Features:
a = np.array([1, 2, 3, 4])
• Array Object: NumPy's main object is the homogeneous
multidimensional array. It is a table of elements (usually numbers), all # Perform operations
of the same type, indexed by a tuple of positive integers.
print(a + 2) # Outputs: [3 4 5 6]
• Broadcasting: A powerful mechanism that allows NumPy to work with print(a * 2) # Outputs: [2 4 6 8]
arrays of different shapes when performing arithmetic operations.
• Utilities: Tools for integrating C/C++ and Fortran code, useful linear # Multidimensional array
algebra, Fourier transform, and random number capabilities. b = np.array([[1, 2], [3, 4]])
17 print(np.transpose(b)) # Outputs: [[1 3] [2 4]]
BASIC LIBRARIES (NUMPY, PANDAS)
pandas Example:
import pandas as pd
pandas is an open-source, BSD-licensed library providing high-performance,
easy-to-use data structures and data analysis tools for Python. The name is # Create a DataFrame
derived from the term "panel data", an econometrics term for datasets that
data = {'Name': ['John', 'Anna', 'James'],
include observations over multiple time periods for the same individuals.
'Age': [28, 24, 35]}
Key Features: df = pd.DataFrame(data)
• DataFrame Object: A two-dimensional size-mutable, potentially
# Operations on DataFrame
heterogeneous tabular data structure with labeled axes (rows and columns).
print(df)
• Handling Time Series: Tools for working with date and time data,
including time-aware indexing, resampling, converting frequencies, and # Access data
more. print(df['Age'])
• Data Manipulation: Capabilities for easily reading and writing data # Read and write to CSV
between in-memory data structures and different formats: CSV, text files, df.to_csv('data.csv')
Microsoft Excel, SQL databases, and the fast HDF5 format.
new_df = pd.read_csv('data.csv')
18
BASIC LIBRARIES (NUMPY, PANDAS)
Using Together
• NumPy and pandas are often used together in data analysis
workflows. pandas relies on NumPy for the numerical
functionality underlying its DataFrame and Series data
structures. Their combination allows you to leverage the
structured data manipulation tools of pandas along with the Example:
numerical and vectorized computing capabilities of NumPy. # Use NumPy with pandas
• Both libraries are crucial for any data science or AI df['Age'] = np.sqrt(df['Age'])
application involving data manipulation, statistical analysis,
or mathematical computations in Python. They are print(df)
foundational for more complex operations and are frequently
used in conjunction with other libraries such as Matplotlib for
plotting or SciPy for more advanced scientific calculations.
19
Thank You!
If you have any questions, please reach me!