1
Data Types
| Type | Example | Description |
|---|---|---|
int | 25 | Whole numbers |
float | 3.14 | Decimal numbers |
str | "Hello" | Text / String |
bool | True | True or False |
list | [1, 2, 3] | Ordered collection |
tuple | (1, 2, 3) | Ordered (immutable) |
set | {1, 2, 3} | Unordered, unique |
dict | {'a': 1} | Key-value pairs |
2
Operators
Arithmetic
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor Division
% Modulus
** Exponent
Comparison
== Equal
!= Not equal
> Greater than
< Less than
>= Greater/equal
<= Less/equal
Logical
and Logical AND
or Logical OR
not Logical NOT
Assignment
= Assign
+= Add & assign
-= Sub & assign
*= Mul & assign
3
Variable & Constant
Variable: Name given to a value.
x = 10
name = "Alice"
price = 19.99
Constant: Value that should not change (UPPER_CASE).
PI = 3.14159
MAX_SIZE = 100
4
If – Elif – Else
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
5
For Loop
for i in range(1, 6):
print(i)
# Output: 1 2 3 4 5
# Loop through list:
for item in ["a", "b", "c"]:
print(item)
6
While Loop
i = 1
while i <= 5:
print(i)
i += 1
# Output: 1 2 3 4 5
7
Counting
Count how many times an item appears in a list:
lst = [1, 2, 2, 3, 2, 4]
count = lst.count(2)
print(count) # Output: 3
8
Totaling (Sum)
Sum of numbers in a list:
nums = [10, 20, 30, 40]
total = sum(nums)
print(total) # 100
9
Maximum
Find maximum value:
nums = [12, 5, 33, 7]
m = max(nums)
print(m) # 33
10
Minimum
Find minimum value:
nums = [12, 5, 33, 7]
m = min(nums)
print(m) # 5
11
List
Create and access list:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
fruits.append("orange")
print(fruits)
12
1D Array (List)
1D array is just a list:
arr = [5, 10, 15, 20, 25]
print(arr[2]) # 15
13
2D Array (List of Lists)
Matrix / Table (Rows × Cols):
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6
14
Upper & Lower
String case conversion:
text = "Hello Python"
print(text.upper()) # HELLO PYTHON
print(text.lower()) # hello python
15
File Handling
Read a file:
with open("data.txt", "r") as f:
content = f.read()
print(content)
Write / Append to a file:
# Write (overwrite)
with open("out.txt", "w") as f:
f.write("Hello Python!\n")
# Append
with open("out.txt", "a") as f:
f.write("Append this line.")