Strings (str)
Definition: A string is a sequence of characters used to represent text. Strings are created using single quotes, double quotes, or triple quotes.
Creating a String
name = "Alice"
message = 'Hello World'
print(name)
print(message)
Strings can contain letters, numbers, spaces, symbols, and special characters.
.strip()
Definition: Removes whitespace from the beginning and end of a string.
Syntax:
string.strip()
Example:
text = " Hello Python "
clean_text = text.strip()
print(clean_text)
# Output:
# Hello Python
.split()
Definition: Splits a string into a list using a separator. If no separator is provided, whitespace is used.
Syntax:
string.split(separator)
Example:
data = "apple,banana,cherry"
fruits = data.split(",")
print(fruits)
# Output:
# ['apple', 'banana', 'cherry']
.lower() and .upper()
Definition:
lower() converts text to lowercase, while
upper() converts text to uppercase.
text = "Python Programming"
print(text.lower())
print(text.upper())
# Output:
# python programming
# PYTHON PROGRAMMING
.replace()
Definition: Replaces one piece of text with another.
message = "I like Java"
new_message = message.replace("Java", "Python")
print(new_message)
# Output:
# I like Python
f-strings
Definition: F-strings allow variables and expressions to be inserted directly into strings.
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
# Output:
# My name is Alice and I am 25 years old.
Lists (list)
Definition: A list is an ordered and mutable collection of values. Lists can contain strings, numbers, objects, or even other lists.
Creating a List
fruits = ["apple", "banana", "orange"]
print(fruits)
# Output:
# ['apple', 'banana', 'orange']
.append()
Definition: Adds one item to the end of a list.
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)
# Output:
# ['apple', 'banana', 'orange']
.insert()
Definition: Inserts an item at a specific position.
numbers = [1, 3, 4]
numbers.insert(1, 2)
print(numbers)
# Output:
# [1, 2, 3, 4]
.remove()
Definition: Removes the first occurrence of a specified value.
fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits)
# Output:
# ['apple', 'orange']
.pop()
Definition: Removes and returns an item from a list. By default, it removes the last item.
numbers = [10, 20, 30]
last_number = numbers.pop()
print(last_number)
print(numbers)
# Output:
# 30
# [10, 20]
List Indexing
Definition: Indexing allows you to access individual elements in a list. Python indexes start at 0.
fruits = ["apple", "banana", "orange"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
# Output:
# apple
# banana
# orange
Dictionaries (dict)
Definition: A dictionary stores data as key-value pairs. Each key is used to access its corresponding value.
Creating a Dictionary
user = {
"name": "Alice",
"age": 25,
"city": "London"
}
print(user)
.get()
Definition: Returns the value associated with a key. It can return a default value if the key does not exist.
user = {
"name": "Alice",
"age": 25
}
print(user.get("name"))
print(user.get("country", "Unknown"))
# Output:
# Alice
# Unknown
Accessing Dictionary Values
person = {
"name": "John",
"age": 30
}
print(person["name"])
print(person["age"])
# Output:
# John
# 30
Adding and Updating Values
Dictionaries can be changed after they are created.
user = {
"name": "Alice",
"age": 25
}
user["age"] = 26
user["city"] = "Cape Town"
print(user)
# Output:
# {'name': 'Alice', 'age': 26, 'city': 'Cape Town'}
.keys(), .values(), and .items()
These methods allow you to work with dictionary keys, values, and key-value pairs.
user = {
"name": "Alice",
"age": 25
}
print(user.keys())
print(user.values())
print(user.items())
Loops & Conditionals
Definition: Control flow determines which instructions Python executes and how many times they are executed.
if Statement
Definition:
An if statement executes code only when
a condition is true.
age = 20
if age >= 18:
print("You are an adult.")
# Output:
# You are an adult.
if / else
Definition:
else provides an alternative when the
if condition is false.
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")
# Output:
# Minor
if / elif / else
Definition:
elif allows Python to test multiple conditions.
score = 75
if score >= 90:
print("A")
elif score >= 70:
print("B")
elif score >= 50:
print("C")
else:
print("Fail")
# Output:
# B
for Loop
Definition:
A for loop repeats code for each item in
an iterable such as a list, string, or range.
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# orange
while Loop
Definition:
A while loop repeatedly executes code while
a condition remains true.
count = 1
while count <= 5:
print(count)
count += 1
# Output:
# 1
# 2
# 3
# 4
# 5
enumerate()
Definition:
enumerate() gives you both the index and
value while looping through an iterable.
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 orange
break
Definition: Stops a loop immediately.
for number in range(10):
if number == 5:
break
print(number)
# Output:
# 0
# 1
# 2
# 3
# 4
continue
Definition: Skips the current iteration and continues with the next one.
for number in range(5):
if number == 2:
continue
print(number)
# Output:
# 0
# 1
# 3
# 4
Comprehensions
Definition: Comprehensions provide a short and readable way to create collections from existing iterables.
List Comprehension
Definition: Creates a new list using an expression and a loop.
Syntax:
[expression for item in iterable]
Example:
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
# Output:
# [1, 4, 9, 16, 25]
List Comprehension with a Condition
You can use an if condition to filter values.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [
number for number in numbers
if number % 2 == 0
]
print(even_numbers)
# Output:
# [2, 4, 6]
Dictionary Comprehension
Definition: Creates a dictionary using a compact expression.
numbers = [1, 2, 3, 4]
squares = {
number: number ** 2
for number in numbers
}
print(squares)
# Output:
# {1: 1, 2: 4, 3: 9, 4: 16}
File Input/Output
Definition: File I/O allows Python programs to read information from files and write information to files.
open()
Definition: Opens a file so that your program can read or write data.
Common modes:
"r"— read"w"— write"a"— append"x"— create a new file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Reading a File with with
Definition:
A with statement automatically closes the
file when the block finishes.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing to a File
The "w" mode creates a file or replaces
its existing contents.
with open("notes.txt", "w") as file:
file.write("Python is easy to learn.")
Appending to a File
The "a" mode adds new content to the end
of an existing file.
with open("notes.txt", "a") as file:
file.write("\nPython is powerful.")
Exception Handling
Definition: Exception handling allows a program to deal with errors without unexpectedly stopping the entire program.
try / except
Definition:
Code that might cause an error is placed inside
try. If an exception occurs,
except handles it.
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
else
Definition:
The else block runs when no exception occurs.
try:
number = int("10")
except ValueError:
print("Invalid number.")
else:
print("Conversion successful.")
# Output:
# Conversion successful.
finally
Definition:
The finally block runs whether an exception
occurs or not.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")
# Output:
# Execution completed.
Raising an Exception
Definition:
The raise statement allows you to create
an exception intentionally.
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")