Algorithms and Programming Python 2
Data Types
In programming languages, a data type is a category that represents every piece of data. Each data item has a different data type, such as numeric data, character data, and other types. The common data types in programming are known as basic data types (which means they are the most frequently encountered data types and also the oldest types available today). Python is a programming language that supports basic data types. Here are the basic data types that can be used in Python:
- Boolean: A logical data type that contains Boolean expressions (True/1 and False/0).
- Integer: A data type that contains whole numbers.
- Floating Point: A data type that contains decimal numbers.
- String: A data type that contains characters or letters.
- List/Array: A data type that contains a list of data with multiple entries.
In addition, Python also supports new data types used for data processing, such as List, Tuple, Set, Dictionary, etc.
- List/Array: In Python, a List is a modern Array that has new features compared to older data type arrays. In old data type arrays, arrays could only hold a list of data of the same type, whereas in Python, Arrays can store lists of data with different types.
- Tuple: Similar to List/Array data types, the main difference is that a variable with a Tuple data type is immutable/constant and cannot be changed. This can be seen as a constant type for Lists/Arrays in Python.
- Set: Similar to List/Array data types, the main difference is that a variable with a Set data type is an unordered list, with unique data entries where no duplicates are allowed. Additionally, Sets are iterable and mutable, meaning their data can be changed.
- Dictionary: Unlike the three data types above that only store one attribute (value/content) for each item in the data list, in a Dictionary, each item in the data list has two attributes: key and value. The key attribute is used as an identifier, while the value is the actual content of the data.
Numbers & Numeric Data
Python recognizes several types of numbers, including integers, floating-point numbers, and complex numbers. Complex numbers can be written in the format (real + imaginaryj) or using the complex(real, imaginary) function. The other numeric data types can be understood from the following example:
1 | variable_integer = 10 |
1 | 10 |
Casting
Casting is the process of explicitly converting a value from one data type to another. This is important because Python doesn’t automatically know how to combine data of different types — for example, you cannot directly add a number to text, and data from input() always comes in as a string, even if the user typed a number. Python provides built-in constructor functions for this:
int()— converts a value to an integerfloat()— converts a value to a floating-point numberstr()— converts a value to a string (text)bool()— converts a value to a Boolean (True/False)
1 | # input() always returns a string, even for numbers |
bool() casting follows a simple rule: 0, 0.0, "" (empty string), and empty collections ([], {}) are treated as False; nearly everything else is treated as True:
1 | print(bool(0)) # False |
Casting is used constantly in real programs, especially right after taking user input with input(), since every value from input() starts out as a string.
Boolean Expressions
A Boolean expression is an expression that returns a value of True or False, using relational/comparison operators and logical operators. Additionally, Boolean expressions can also utilize membership operators and identity operators in certain cases.
List/Array
A List/Array is a collection that contains multiple data entries. Generally, lists have indices (a sequence within the list of data) starting from 0. In Python, lists are quite modern as they support an index of -1, which represents the last item in the list. Moreover, lists in Python can accommodate multiple data types. To declare a list, you can use square brackets “[]” and separate each data item with a comma “,”.
Basic Example of List Usage:
1 | thisList = [1, "This 2", True, 3.0] |
Common List Methods
Beyond slicing, real-world Python code constantly uses these built-in list methods to add, remove, and manipulate data. These are essential and commonly asked about in interviews and coursework alike:
1 | fruits = ["apple", "banana", "cherry"] |
Sorting Lists
Sorting is a fundamental and frequently used operation. Python provides two main ways to sort:
1 | numbers = [5, 2, 9, 1, 7] |
Use sorted() when you need to keep the original list untouched (e.g., displaying a sorted view while preserving the original order elsewhere); use .sort() when you no longer need the original order.
Tuple, Set, and Dictionary in Practice
These three data types were introduced by name earlier, but let’s see them actually used, since they appear constantly in real Python code:
1 | # Tuple: ordered, immutable (cannot be changed after creation) |
String
A string in Python is essentially a list/array of characters. If you try to execute list commands on a variable of string data type, the results will be the same as those produced with a list, as shown in the example below:
1 | thisDate = "19-02-2024" |
Variable
A variable is a place for storing data. If we liken it to something, a variable is like a box. This box has attributes: the name of the box, a label indicating the type of contents inside, and the contents themselves. Therefore, we can conclude that a variable also has a name, a data type for its contents, and the contents themselves.
Variables in Python are very dynamic. This means:
- Variables do not need to be declared with a specific data type.
- The data type of a variable can change while the program is running (except for immutable/constant variables, whose values cannot be changed).
In Python, variables generally fall into two categories: immutable/constant variables and mutable variables.
Creating a variable in Python is very simple. To declare a mutable variable, you just need to assign a value to a variable with the desired data type. The assignment operator is the equal sign (=).
Here’s an example of declaring a mutable variable in Python:
1 | int_thisFive = 5 |
To declare an immutable variable, you need to name the variable using all uppercase letters.
Here’s an example of declaring an immutable/constant variable in Python:
1 | WRONG = False |
In addition to the two common types mentioned above, there are also types based on their usage. Variable usage is generally divided into two categories: local variables and global variables.
Global variables are accessible from any block of the program, while local variables are only accessible within specific blocks, such as in functions or classes. We will discuss examples of global and local variables in the next session.
Operator
Arithmetic Operators
Arithmetic operations are part of number processing in a computer for performing calculations. In addition to performing calculations, arithmetic operations can also be used for logical operations. The foundation of performing calculations in computer arithmetic is addition, also known as the adder.
Here are the Arithmetic Operators in the Python Programming Language.
| Operator | Symbol |
|---|---|
| Addition | + |
| Subtraction | - |
| Multiplication | * |
| Division | / |
| Remainder of Share | % |
| Power of | ** |
Here is an example of the Arithmetic Operation:
1 | 3 + 2 |
Mathematical operators work normally in Python, just like in other programming languages. There are several notes to keep in mind:
- Multiple variables can be assigned the same value in one statement.
- Parentheses () are used to group operations that should be performed first.
- Division of an integer by an integer will round down.
- An integer will be converted to a floating-point number in operations involving both integers and floating-point numbers.
- We cannot convert a complex number to a real number (floating-point or integer); only its absolute value can be obtained.
Assignment Operators
As the name suggests, this operator is used to assign values to variables. For example: age = 18 This means the variable age has been assigned the value of 18. In addition to storing or assigning values, you can also perform addition, subtraction, multiplication, division, etc. More details can be found in the following table.
| Operator | Symbol |
|---|---|
| Simple Assignment | = |
| Addition | += |
| Subtraction | -= |
| Multiplication | *= |
| Division | /= |
| Remainder of Share | %= |
| Power of | **= |
Because in Python there are no increment & decrement operators, these operators are replaced by assignment operators by entering like this i += 1 (same with i++).
Comparison Operators
Comparison operators are operators that compare two values. These are also known as relational operators and are often used to create logic or conditions. Below is a list of Comparison Operators in Python:
| Operator | Symbol |
|---|---|
| Greater than | > |
| Smaller than | < |
| Equal to | == |
| Not Equal to | != |
| Greater than or Equal to | >= |
| Smaller than or Equal to | <= |
Logical Operators
Logical operators are operators used to create logic in the programs we write. Logical operators are often referred to as Boolean algebra operators and are typically used to create branching operations in a program. The logical operators include AND, OR, and NOT.
The logical operators consist of:
| Operator | Symbol |
|---|---|
| AND Logic | and |
| OR Logic | or |
| Negation Logic | not |
Bitwise Operators
As the name suggests, bitwise operators are used to perform bit-level operations on values in a computer. Here are the bitwise operators available in Python:
| Operator | Symbol |
|---|---|
| Bitwise AND | & |
| Bitwise OR | | |
| Bitwise NOT | ~ |
| Bitwise XOR | ^ |
| Bitwise Right Shift | >> |
| Bitwise Left Shift | << |
Special Operators
Special operators are operators that are unique to the Python programming language and may not be present in other programming languages. Here are some examples of special operators:
| Operator | Symbol |
|---|---|
| Is (same object identity) | is |
| Is Not (different object identity) | is not |
| Inside | in |
| Not Inside | not in |
Important clarification on
is/is not: these operators are still fully valid and current in Python (they have not been removed or deprecated). However, they are commonly misused by beginners.is/is notcheck whether two variables point to the exact same object in memory (identity), not whether their values are equal. Use==/!=to compare values (e.g.,age == 18), and reserveis/is notmainly for comparing againstNone(e.g.,if value is None:), which is the standard, recommended use case in real Python code.
1 | a = [1, 2, 3] |
Input and Output Functions
Output
The Output function is used to display something, often for showing a value that can be read and seen by the user. Generally, the Output function uses the command print(). Its usage can be seen in the code below:
Code:1
print("this function is used for output")
Output:1
this function is used for output
If we look at the example above, print will output what we have entered into the print function. What if we want to print multiple lines? That’s very easy; to print multiple lines, you can add a special character or use multi-line comments inserted into the print function, as shown in the example below:
Code:1
2
3
4
5
6
7
8
9# Using Special Character \n
print("This is\nfunction used for output\nwith multiline")
# Using Multiline Comment
print("""
This is
function used for output
with multiline
""")
Output:1
2
3
4
5
6This is
function used for output
with multiline
This is
function used for output
with multiline
What if we want to include a variable in the print output function? To insert a variable, you can simply print it directly, or if you want to add it and concatenate it with a string, you can use a comma (,) or a plus sign (+) as a separator between the string and the variable. Be careful when using the plus sign (+); it only works for data types that are the same as strings. If you want to use the plus sign (+) and combine different data types (like a string and an integer), you must first convert the data type to a string using the str() function.
Here is an example:
Code:1
2
3
4
5
6
7
8
9
10
11
12
13
14x = 5
y = "example"
# Just variable, without string
print(x)
# Combining Strings with Variables
print("This is", x)
# Combine Strings with Variables with the + symbol
print("This is " + y)
# Combining Strings with Variables with the + symbol with a variable data type that is different from String
print("This is " + str(x))
Output:1
2
3
45
This is 5
This is example
This is 5
The print function has other parameters such as “end” and “sep”. The end parameter is used when you want to terminate a print result with something specific, while sep is the separator.
F-Strings (Modern Standard for Output)
Since Python 3.6, the industry standard way to combine text and variables is the f-string (formatted string literal), not string concatenation with + or ,. F-strings are faster, more readable, and let you embed expressions directly inside the string.
Code:1
2
3
4
5
6
7
8
9
10
11name = "Azhar"
age = 24
# Old style (still valid, but not preferred in modern code)
print("My name is " + name + " and I am " + str(age) + " years old")
# Modern style: f-string
print(f"My name is {name} and I am {age} years old")
# You can even do calculations inside an f-string
print(f"Next year I will be {age + 1} years old")
Output:1
2
3My name is Azhar and I am 24 years old
My name is Azhar and I am 24 years old
Next year I will be 25 years old
From this point forward in the course, f-strings are the preferred way to format output.
Input
The Input function is used to take a request from the user for a value to be entered into a program. Generally, the Input function uses the command input(). Below is an example of how to use the input function in Python:
Code:1
2
3
4
5
6
7
8
9
10
11
12
13# Input String
str_name = input("Enter Name: ")
# Input Integer
int_number = int(input("Enter Random Integer Number: "))
# Input Floating Point
flt_number = float(input("Enter Random Float Number: "))
print(str_name)
print(int_number)
print(flt_number)
Output:1
2
3
4
5
6
7Enter Name: Azhar (User Input)
Enter Random Integer Number: 5 (User Input)
Enter Random Float Number: 5.1 (User Input)
Azhar
5
5.1
Python Package & Library
Packages and Libraries are bundles or groups of many functions and classes (source code) combined into a single unit in the library that can be used and called in the source code you are developing, allowing you to obtain a function without having to repeatedly type the source code. Python provides packages/libraries for standard operations. For more specific operations, you may need to use functions from other packages. In this practical session, we will learn about arithmetic operations and how to use a package to call trigonometric operation functions, which are provided in Python’s Math package.
Example of using a Library/Package:
1 | import math |
Exercise
List & Sorting Exercise
Create a program that accepts 5 numbers from the user, stores them in a list, then displays: the list sorted in ascending order, the list sorted in descending order, the largest number, and the smallest number. (estimated 10 minutes)
INPUT:
5 numbers (one at a time)
PROCESS:
Store the numbers in a list, then sort it ascending and descending.
OUTPUT:
- Ascending sorted list
- Descending sorted list
- Largest number
- Smallest number
Arithmetic Operator Exercise 1
Create a program to calculate the Volume of a Cuboid (Rectangular Box). The length, width, and height are entered by the user. Convert the volume formula using arithmetic operators. (estimated 5 minutes)
INPUT:
- Length
- Width
- Height
PROCESS:
Calculate the volume of the cuboid based on each side.
OUTPUT:
Display the volume of the cuboid in cubic meters.
Arithmetic Operator Exercise 2
Create a program to calculate the Volume of a Sphere. The radius is entered by the user. Convert the volume formula using arithmetic operators. (estimated 10 minutes)
INPUT:
Radius
PROCESS:
Calculate the volume of the sphere based on the radius.
OUTPUT:
Display the volume of the sphere in cubic meters.
Arithmetic Operator Exercise 3
Create a program to calculate the Volume of a Cylinder. The radius and height are entered by the user. Convert the volume formula using arithmetic operators. (estimated 10 minutes)
INPUT:
- Radius
- Height
PROCESS:
Calculate the volume of the cylinder based on the radius and height.
OUTPUT:
Display the volume of the cylinder in cubic meters.
Arithmetic Operator Exercise 4
Create a program to calculate the discriminant of a quadratic equation. (estimated 10 minutes)
INPUT:
- Value A
- Value B
- Value C
PROCESS:
Calculate the discriminant.
OUTPUT:
Display the discriminant calculation result.
Arithmetic Operator Exercise 5
Create a program to calculate the distance between two points on the surface of the earth. (estimated 20 minutes)
INPUT:
- Longitude of Point A
- Latitude of Point A
- Longitude of Point B
- Latitude of Point B
PROCESS:
Calculate the distance between the two points (Haversine formula).
OUTPUT:
Display the calculated distance between the 2 points.


