1. Introduction & Setup
Python is a high-level, interpreted, object-oriented programming language developed by Guido van Rossum. It's highly popular in Data Science, Web Development, and Automation due to its design, which emphasizes code readability and a clean syntax. Anaconda is the recommended Python distribution for Data Science.
The basic Python command to display text on the screen is `print()`.
print("Hello, Nitedemy!")You can install libraries using the pip package manager.
pip install pandas
pip install numpy2. Data Types & Variables
Variables are names used to refer to memory locations where values are stored. In Python, the data type is determined automatically when you assign a value. Variable naming rules are that they must start with a letter or underscore (_), and cannot be a Python keyword.
The main primitive data types include: String (str) for text, Integer (int) for whole numbers, Float (float) for decimal numbers, and Boolean (bool) for truth values (True/False).
name = "Budi" # str
age = 25 # int
height = 175.5 # float
is_active = True # bool
print(type(height)) # Output: <class 'float'>3. Operators & Expressions
Operators are special symbols to perform operations. An expression is a combination of operators and operands that results in a value.
Arithmetic Operators include: `+` (Addition), `-` (Subtraction), `*` (Multiplication), `/` (Float Division), `//` (Integer Division), `%` (Modulus/Remainder), and `` (Exponent).
Comparison (Relational) Operators like `==`, `!=`, `>`, `<`, `>=`, `<=` produce a Boolean value (True/False).
Logical Operators (`and`, `or`, `not`) are used to combine or invert Boolean conditions.
result = 11 // 4 # Result: 2
status = (5 > 3) and (10 == 10) # Result: True4. Conditionals (If-Else)
Conditionals allow a program to execute a specific block of code only if a given condition is True. The structure must end with a colon (:) and the code block must be indented.
Common structures are Single If, If-Else (runs an alternative code), and If-Elif-Else (tests many conditions sequentially).
score = 85
if score > 90:
print("Excellent")
elif score > 80:
print("Good")
else:
print("Sufficient")5. Looping (For & While)
Looping is used to repeat a block of code. `For` is used to iterate over items in a sequence (iterable), often using the `range()` function. `While` repeats code as long as a condition is True.
You can control loops using `break` (stops the loop entirely) and `continue` (skips the current iteration).
# For Loop Example
for i in range(3):
print(i)
# While Loop Example with break
num = 0
while True:
if num == 2: break
print(num)
num += 16. List, Tuple, Set
These are collection data structures for storing multiple values:
1. List []: Ordered, changeable (Mutable), allows duplicates. Accessed by numeric index.
2. Tuple (): Ordered, NOT changeable (Immutable), allows duplicates.
3. Set {}: Unordered, changeable (Mutable), does NOT allow duplicates (unique).
my_list = [10, 20]
my_list.append(30)
my_tuple = (1, 2)
my_set = {1, 2, 2}
print(my_set) # Output: {1, 2}7. Dictionary
A Dictionary is a data structure that stores data in Key-Value pairs. Dictionaries are unordered, changeable (Mutable), and Keys must be unique and Immutable.
Values are accessed using the Key inside square brackets `[]`. Common methods include `.keys()`, `.values()`, and `.items()`.
profile = {"name": "Rudi", "age": 30}
print(profile["age"]) # Access value
profile["age"] = 31 # Change value8. Functions
A function is an organized block of code that performs a specific task, improving modularity and reusability. Functions are defined using the `def` keyword.
Functions can accept parameters (inputs) and return values using the `return` keyword. Variables inside functions are Local.
def add(a, b):
return a + b
result = add(5, 3) # result = 89. Basic OOP
OOP focuses on Objects, which are instances of a Class (Blueprint). A Class contains data (Attributes) and code (Methods). The special `__init__(self)` method is used for object initialization.
The main pillars of OOP include Encapsulation, Abstraction, Inheritance, and Polymorphism.
class Car:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
my_car = Car("Red")
print(my_car.get_color()) # Output: Red10. NumPy Library
NumPy (Numerical Python) is the fundamental library that provides the N-dimensional Array (`ndarray`) object for numerical computing. NumPy arrays are faster than Python Lists due to Vectorization and homogeneity (uniform data type).
Mathematical operations in NumPy are performed element-wise (vectorization).
import numpy as np
a = np.array([10, 20, 30])
result = a * 2 # Result: [20 40 60]
print(a.shape) # Dimensions11. Pandas Library
Pandas is the most important library for data analysis and manipulation of structured data. Its key data structures are the Series (1D/column) and DataFrame (2D/table). Pandas is used for reading data (e.g., `pd.read_csv()`), filtering, and grouping.
Important functions for Data Cleaning include `df.info()` (view data summary) and `df.fillna()` (fill missing values).
import pandas as pd
data = {'Age': [25, 30, 22]}
df = pd.DataFrame(data)
age_filter = df[df['Age'] > 25]Practice Set
Reinforce basic Python programming and Data Science library concepts with interactive questions.
Question #1 - Python Introduction
Which Python library is fundamental and provides N-Dimensional Arrays for numerical computing?
Question #2 - Data Types
What data type will result from the expression `5 / 2` in Python?
Question #3 - Operators
What is the result of the expression `2 ** 3`?
Question #4 - Conditionals
What keyword is used to test a second or alternative condition after a primary `if` condition in Python?
Question #5 - Looping
Which statement will cause a loop to immediately stop its current iteration and proceed to the next iteration?
Question #6 - Data Structures
Which collection data structure is mutable (changeable) and ensures all its elements are unique?
Question #7 - Dictionary
What is used to access a value in a Python Dictionary?
Question #8 - Functions
The Python keyword used to return a value from a function to its caller is?
Question #9 - OOP
What is the special method that is automatically executed when a new object is created (instantiated) from a Class?
Question #10 - NumPy
The primary data object provided by the NumPy library for efficient computation is?
Question #11 - Pandas
The most commonly used 2-Dimensional Pandas data structure for storing tabular data (like an Excel table) is?
Final Exam
Test your Python knowledge comprehensively. Time is limited!
Question #1 - Python Introduction
Which Python library is fundamental and provides N-Dimensional Arrays for numerical computing?
Question #2 - Data Types
What data type will result from the expression `5 / 2` in Python?
Question #3 - Operators
What is the result of the expression `2 ** 3`?
Question #4 - Conditionals
What keyword is used to test a second or alternative condition after a primary `if` condition in Python?
Question #5 - Looping
Which statement will cause a loop to immediately stop its current iteration and proceed to the next iteration?
Question #6 - Data Structures
Which collection data structure is mutable (changeable) and ensures all its elements are unique?
Question #7 - Dictionary
What is used to access a value in a Python Dictionary?
Question #8 - Functions
The Python keyword used to return a value from a function to its caller is?
Question #9 - OOP
What is the special method that is automatically executed when a new object is created (instantiated) from a Class?
Question #10 - NumPy
The primary data object provided by the NumPy library for efficient computation is?
Question #11 - Pandas
The most commonly used 2-Dimensional Pandas data structure for storing tabular data (like an Excel table) is?
Question #12 - Data Types
Which of the following is a correct Boolean data type in Python?
Question #13 - Operators
What is the output of the expression `not (10 > 5 and 4 < 2)`?
Question #14 - Functions
What happens if a variable is defined inside a function and you try to access it outside the function?
Question #15 - Data Structures
Keys in a Python Dictionary must be: