Object-oriented programming language
Object-oriented programming language
Level III
1
Table of Contents
Acronym
OO------------------------------------------------------------------Object-Oriented
VS-------------------------------------------------------------------Visual Studio
2
Unit One - Identification of Content Needs
Objects & Classes: Objects represent real-world entities, and classes define their structure.
Data Abstraction: Essential features are exposed while implementation details remain hidden.
Encapsulation: Data and methods are bundled within a single unit, ensuring controlled access.
Inheritance: New classes (subclasses) derive attributes and behaviors from existing classes
(superclass), promoting reusability.
Polymorphism: Allows a single interface for different data types, facilitating flexibility and code
reusability.
Use meaningful and descriptive names for classes, methods, and variables.
Follow naming standards such as CamelCase for classes and camelCase for methods and
variables.
Example (Java):
class ShoppingCart {
void addItem(String item) {
// Code logic
}
}
B. Encapsulation
Encapsulation restricts access to object components using access modifiers like private,
protected, and public.
Example (Python):
class BankAccount:
def __init__(self):
self.__balance = 0 # Private attribute
def get_balance(self):
return self.__balance
3
C. Inheritance
Inheritance allows a new class to use attributes and methods from an existing class.
Example (Python):
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Bark"
D. Polymorphism
Example (Java):
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
class PaymentProcessor:
def process_payment(self, amount):
print("Processing payment of", amount)
Following these OOP principles ensures modular, reusable, and maintainable code structures.
4
1.3 Data Types, Operators, and Expressions
A. Java
B. C++
C. JavaScript
Before coding in Python, it’s essential to understand fundamental programming concepts such
as:
5
Variables
Data Types
Conditionals
Loops
Functions
Setting Up Python
1. Install Python: Download the latest version from the official Python website.
2. Choose an IDE: Use an Integrated Development Environment (IDE) like:
o PyCharm
o Visual Studio Code (VS Code)
o Jupyter Notebook
o IDLE (comes with Python)
3. Configure Python: Ensure Python is properly installed and running on your system.
1. Numbers
Integers (int): Whole numbers without decimals.
o Example: x = 10
Floating Point (float): Numbers with decimals.
6
o Example: y = 3.14
Complex Numbers (complex): Written in the form x + yj.
o Example: z = 2 + 3j
2. Strings (str)
Strings are sequences of characters enclosed in single (' ') or double (" ") quotes.
Multiline strings use triple quotes (''' or """).
Strings support indexing and slicing.
Example:
python
text = "Hello, Python!"
print(text[0]) # Access first character
print(text[0:5]) # Slice first 5 characters
1. Lists (list)
Ordered, mutable collection.
Items can be of different data types.
Created using square brackets [].
Example:
python
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adds new item
print(fruits)
2. Tuples (tuple)
Ordered, immutable collection.
Created using parentheses ().
Example:
python
colors = ("red", "green", "blue")
print(colors[1]) # Access second element
3. Dictionaries (dict)
Unordered collection of key-value pairs.
Created using curly braces {}.
Example:
python
student = {"name": "John", "age": 21, "course": "CS"}
print(student["name"]) # Output: John
7
4. Sets (set)
Unordered collection of unique elements.
Created using curly braces {}.
Example:
python
CopyEdit
numbers = {1, 2, 3, 4, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5} (removes duplicate)
B. Operators in Python
Operators perform operations on variables and values.
1. Arithmetic Operators
Used for mathematical operations:
Operator Description Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
// Floor Division x // y (Removes decimal)
% Modulus x % y (Remainder)
** Exponentiation x ** y (Power)
3. Logical Operators
Used to combine boolean expressions:
Operato Description Example
r
and True if both conditions are true x > 5 and y < 10
or True if at least one condition is true x > 5 or y < 10
not Inverts boolean value not x
C. Type Conversion
Type conversion (type casting) is converting one data type into another.
1. Implicit Type Conversion (Done automatically by Python)
python
x = 10
8
y = 2.5
z = x + y # Converts 'x' to float automatically
print(type(z)) # Output: <class 'float'>
Conclusion
Python offers various data types to store and manipulate data efficiently.
Operators help perform mathematical, logical, and comparison operations.
Expressions combine variables and operators to produce a result.
Type conversion is crucial when handling different data types in operations
B. Operators
Operators are symbols used to perform operations on variables and values. Python supports
different types of operators categorized as follows:
Arithmetic Operators
Comparison (Relational) Operators
Bitwise Operators
Logical Operators
Assignment Operators
Membership Operators
Identity Operators
Understanding operators is crucial for performing computations, comparisons, and logical
evaluations in Python programs.
9
1. Arithmetic Operators
Used for mathematical operations:
Operator Description Example (x = 10, y = 3) Output
+ Addition x + y 13
- Subtraction x - y 7
* Multiplication x * y 30
/ Division x / y 3.33
// Floor Division x // y 3
% Modulus (Remainder) x % y 1
** Exponentiation x ** y 1000
3. Bitwise Operators
Operate at the binary level on numbers:
Operato Description Example (x = 2 (10), y = 7 (111)) Output
r
& AND x & y 2 (10)
` ` OR `x
^ XOR x ^ y 5 (101)
~ NOT ~x -3
<< Left Shift x << 1 4
>> Right Shift y >> 1 3
4. Logical Operators
Used for boolean logic:
Operator Description Example (x = 5, y = 10) Output
and Returns True if both conditions are True x > 0 and y > 5 True
or Returns True if at least one condition is True x > 10 or y > 5 True
not Reverses boolean value not (x > y) True
5. Assignment Operators
Used to assign values to variables:
Operato Example (x = 5) Equivalent To Result
r
= x = 5 x = 5 5
+= x += 3 x = x + 3 8
-= x -= 2 x = x - 2 6
*= x *= 4 x = x * 4 20
10
/= x /= 5 x = x / 5 4.0
//= x //= 3 x = x // 3 1
%= x %= 2 x = x % 2 1
**= x **= 2 x = x ** 2 25
6. Membership Operators
Used to check if a value exists in a sequence (list, string, set, dictionary).
Operato Description Example (x = [1, 2, 3]) Output
r
in Returns True if value exists 2 in x True
not in Returns True if value does not exist 5 not in x True
7. Identity Operators
Used to compare memory locations of objects.
Operator Description Example (a = 10, b = 10) Output
is Returns True if both refer to the same object a is b True
is not Returns True if they refer to different objects a is not b False
C. Expressions
An expression is a combination of values, variables, operators, and functions that evaluates to a
single value.
1. Arithmetic Expressions
Involves mathematical operations:
Example:
python
result = (2 + 3) * 5 # Output: 25
2. String Expressions
Used for string concatenation and manipulation.
Example:
python
3. Logical Expressions
Evaluate boolean conditions.
11
Example:
python
is_valid = (5 > 3) and (10 < 20) # Output: True
Example:
python
def square(num):
return num ** 2
5. Compound Expressions
Combine multiple expressions.
Example:
python
a, b = 5, 10
result = (a * 2) + (b / 2) # Output: 15.0
Conclusion
12
B. Selection (Conditional Statements)
Selection constructs allow decision-making using if, elif, and else statements.
C. Iteration (Loops)
Loops enable repetition of a block of code.
For Loop:
o Iterates over a sequence (list, tuple, range, etc.).
o Syntax: for variable in sequence:
o The range() function is commonly used to define numeric sequences.
While Loop:
o Executes as long as a condition remains True.
o Syntax: while condition:
Else in Loops:
o The else clause executes after the loop completes unless terminated by break.
Jump Statements:
o break: Exits the loop prematurely.
o continue: Skips the current iteration and proceeds to the next.
Importing a Module:
import math
Importing Specific Functions:
from math import sin, pi
Importing Multiple Modules:
import math, random
Importing All Names from a Module:
from math import *
13
def fibonacci(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
1. Introduction to Arrays
In Python, arrays are fundamental data structures used to store collections of items. The key
distinction between arrays and lists in Python is that arrays store elements of the same data type,
while lists can store elements of different data types.
Arrays: Typically use the array module and require a specific data type declaration such as
integers (i), floats (f), or characters (c).
Lists: More flexible and can store mixed data types.
Arrays are more efficient in terms of memory usage and performance, as they store items of a
single type and are optimized for such use cases.
2. Array Syntax
Elements: The items stored in the array.
Index: The position where an element is stored in the array (starts at 0).
Length: The total number of elements in the array.
Indices: A map of indexes that indicate where each element is stored.
Example array:
csharp
[5, 6, 7, 2, 3, 5]
Index: 0 1 2 3 4 5
14
Example:
python
import array
myarray = array.array('i', [1, 2, 3, 4])
print(myarray)
o The append() method adds a single element at the end of the array.
python
5. Arrays of Objects
You can create arrays of custom objects using classes. Here's how to do that:
1. Define a Class to represent an object with attributes.
2. Create an Array of these objects using the array module.
Example:
python
import array
class Student:
def __init__(self, name, age):
15
self.name = name
self.age = age
# Create objects
student1 = Student('Alice', 20)
student2 = Student('Bob', 22)
6. Key Takeaways
Arrays in Python are optimized for performance and memory when storing items of the same
data type.
Use the array module for creating arrays and perform operations like traversing, inserting, and
appending.
Arrays of custom objects can be created using Python's object-oriented features, where each
element of the array is an instance of a class.
1. Extending Elements in Arrays
In Python, the extend() method is used to append multiple elements from another array, list, or
iterable at the end of an array.
extend() Method: Adds elements from an iterable (like a list or another array) to the end of
the array. This differs from append(), which adds only a single element.
Example:
python
import array
3. Key Points:
16
Difference with append(): While append() adds a single element to the array, extend()
adds all elements from an iterable to the array.
4. Use Cases:
17