File Handling
# Basic file reading
file = open("data.txt", "r")
content = file.read() # Read entire file
lines = file.readlines() # Read as list of lines
file.close()
# Reading line by line
file = open("data.txt", "r")
for line in file:
print(line.strip()) # strip() removes \n
file.close()
# Write to file (overwrites)
file = open("output.txt", "w")
file.write("Hello World\n")
file.close()
# Append to file (adds to end)
file = open("output.txt", "a")
file.write("New line\n")
file.close()
Working with Lists
# Creating lists
numbers = [1, 2, 3, 4, 5]
names = ["John", "Maria", "Carlos"]
# Accessing elements
first = numbers[0] # First element
last = numbers[-1] # Last element
slice = numbers[1:4] # Elements 1 to 3
# List methods
numbers.append(6) # Add to end
numbers.remove(3) # Remove value
length = len(numbers) # Get length
Loops
# For loop through list
for number in numbers:
print(number)
# For loop with index
for i in range(len(numbers)):
print(f"Index {i}: {numbers[i]}")
# While loop
count = 0
while count < 5:
print(count)
count += 1
String Operations
text = " Hello World "
text.strip() # "Hello World" - remove spaces
text.lower() # " hello world " - lowercase
text.upper() # " HELLO WORLD " - uppercase
text.split() # ["Hello", "World"] - split by space
text.split(",") # Split by comma
text.replace("H", "J") # " Jello World "
Conditionals and Comparisons
if temperature > 30: # Basic conditions if/else
print("Hot")
elif temperature > 20:
print("Warm")
else:
print("Cold")
# Common comparisons
x == y # Equal to
x != y # Not equal to
x > y # Greater than
x < y # Less than
x >= y # Greater or equal
Math and Statistics
max_value = max([10, 5, 8, 20]) # Returns 20 - Finding max/min
min_value = min([10, 5, 8, 20]) # Returns 5
# Average calculation
numbers = [10, 20, 30]
total = sum(numbers) # Or use loop:
total = 0
for num in numbers:
total += num
average = total / len(numbers)
Data Processing
# Read CSV (name,grade format)
file = open("data.csv", "r")
for line in file:
parts = line.strip().split(",")
name = parts[0]
grade = float(parts[1])
# Process data...
file.close()
Dictionaries
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1