=
sign to assign values to variables.x = 5 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_valid = True # Boolean
10
, -5
)3.14
, -2.5
)"Hello"
, 'Python'
)True
or False
#
to add a comment.# This is a single-line comment
""" ... """
or ''' ... '''
."""
This is a multi-line comment
Useful for documentation
"""
print("Hello, world!") # Outputs: Hello, world!
print(x) # Outputs the value of x
Operator | Description | Example |
---|---|---|
+ |
Addition | 3 + 2 → 5 |
- |
Subtraction | 3 - 2 → 1 |
* |
Multiplication | 3 * 2 → 6 |
/ |
Division | 3 / 2 → 1.5 |
// |
Floor Division | 3 // 2 → 1 |
% |
Modulus (remainder) | 3 % 2 → 1 |
** |
Exponentiation | 3 ** 2 → 9 |
+
to combine strings.full_name = "John" + " " + "Doe" # Outputs: John Doe
*
to repeat strings.greeting = "Hi! " * 3 # Outputs: Hi! Hi! Hi!
len()
to get the length of a string.length = len("Python") # Outputs: 6
word = "Python"
print(word[0]) # Outputs: 'P'
print(word[-1]) # Outputs: 'n' (last character)
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
print(numbers[0]) # Outputs: 1
print(names[2]) # Outputs: Charlie
numbers[0] = 10 # Changes first element to 10
numbers.append(6) # Adds 6 to the end
numbers.pop() # Removes and returns the last element
numbers.remove(10) # Removes the first occurrence of 10
length = len(numbers) # Returns the length of the list
age = 18
if age >= 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child")
Operator | Description |
---|---|
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal |
for i in range(5): # Outputs: 0, 1, 2, 3, 4
print(i)
count = 0
while count < 5:
print(count)
count += 1
Defining and Calling Functions:
def greet(name):
return "Hello, " + name
message = greet("Alice") # Outputs: Hello, Alice
print(message)
Function with Default Parameters:
def greet(name="Guest"):
print("Hello, " + name)
greet() # Outputs: Hello, Guest
greet("Alice") # Outputs: Hello, Alice
if x > 0:
print("Positive") # Correct
print("This line is outside the if block") # Correct
=
for comparison: Use ==
for equality comparison, =
is for assignment.if x == 5: # Correct
print("x is 5")
' '
or " "
).name = "Alice" # Correct
my_list = []
numbers = [1, 2, 3, 4]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.5, True] # Lists can hold different data types
[]
to access elements by their position (index) in the list. Indexing starts at 0
.fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: "apple"
print(fruits[2]) # Output: "cherry"
print(fruits[-1]) # Output: "cherry"
print(fruits[-2]) # Output: "banana"
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]
numbers[1:4]
includes elements at indices 1
to 3
, but not 4
.print(numbers[::2]) # Output: [1, 3, 5] (every second element)
len()
to find the number of elements in the list.print(len(fruits)) # Output: 3
+
operator.list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5, 6]
*
to repeat the elements in a list.repeated_list = [1, 2] * 3
print(repeated_list) # Output: [1, 2, 1, 2, 1, 2]
in
to check if an element is in the list.print("apple" in fruits) # Output: True
.append()
to add an element to the end of the list.fruits.append("orange")
print(fruits) # Output: ["apple", "banana", "cherry", "orange"]
.insert(index, element)
to add an element at a specific position.fruits.insert(1, "blueberry")
print(fruits) # Output: ["apple", "blueberry", "banana", "cherry"]
.extend()
to add multiple elements from another list.fruits.extend(["kiwi", "mango"])
print(fruits) # Output: ["apple", "banana", "cherry", "kiwi", "mango"]
fruits[0] = "grape"
print(fruits) # Output: ["grape", "banana", "cherry"]
.remove(value)
to delete the first occurrence of a value.fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry"]
.pop(index)
to remove and return the element at the specified index. If no index is given, it removes the last element.fruits.pop(1)
print(fruits) # Output: ["apple"] (removes "cherry")
.clear()
to remove all elements in the list.fruits.clear()
print(fruits) # Output: []
len(my_list)
returns the number of elements..count(value)
returns how many times a value appears in the list.numbers = [1, 2, 2, 3, 4, 2]
print(numbers.count(2)) # Output: 3
.index(value)
returns the first index of the value.print(fruits.index("cherry")) # Output: 1
.sort()
sorts the list in ascending order.numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
.reverse()
reverses the order of the list.numbers.reverse()
print(numbers) # Output: [4, 3, 2, 1]
for
loop to iterate over each element in the list.for fruit in fruits:
print(fruit)
apple
banana
cherry
enumerate
: Get both the index and the element.for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
.copy()
or slicing.new_list = fruits.copy()
another_list = fruits[:] # Both work the same way
squares = [x ** 2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
my_list[10]
if the list has fewer than 11 elements).=
for copying: new_list = old_list
copies the reference, not the actual list, so changes to new_list
affect old_list
. Use .copy()
or slicing for an actual copy.nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
nested_list
is a 2-dimensional list (matrix) containing three sublists.vector = [1, 2, 3]
print(vector[0]) # Output: 1
print(vector[2]) # Output: 3
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0][1]) # Output: 2 (1st row, 2nd column)
print(matrix[2][2]) # Output: 9 (3rd row, 3rd column)
matrix[1][1] = 10 # Changes the element in the 2nd row, 2nd column to 10
print(matrix) # Output: [[1, 2, 3], [4, 10, 6], [7, 8, 9]]
tensor = [
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
],
[
[9, 10],
[11, 12]
]
]
(3, 2, 2)
, which means it contains 3 blocks (or matrices), each with 2 rows and 2 columns.print(tensor[0][1][1]) # Output: 4 (1st block, 2nd row, 2nd column)
print(tensor[2][0][1]) # Output: 10 (3rd block, 1st row, 2nd column)
tensor[1][0][0] = 100
print(tensor) # Output: [[[1, 2], [3, 4]], [[100, 6], [7, 8]], [[9, 10], [11, 12]]]
Looping through Nested Lists:
for
loops to iterate over rows and elements within each row.for row in matrix:
for element in row:
print(element, end=' ')
# Output: 1 2 3 4 10 6 7 8 9
for block in tensor:
for row in block:
for element in row:
print(element, end=' ')
# Output: 1 2 3 4 100 6 7 8 9 10 11 12
List Comprehensions with Nested Lists:
matrix = [[0 for _ in range(3)] for _ in range(3)]
print(matrix) # Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print(transpose) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
print(matrix[3][0]) # Error! IndexError: list index out of range
jagged_list = [[1, 2], [3, 4, 5], [6]]
# Accessing jagged_list[1][2] is valid, but jagged_list[2][1] will raise an IndexError.
By understanding and effectively using nested lists, you can handle a variety of data structures and mathematical computations in Python, making it a valuable skill for both beginner and advanced programming tasks.
Operation | Mathematical Notation | Python Code |
---|---|---|
Addition | $a + b$ | a + b |
Subtraction | $a - b$ | a - b |
Multiplication | $a \times b$ | a * b |
Division | $\frac{a}{b}$ | a / b |
Floor Division | $\lfloor \frac{a}{b} \rfloor$ | a // b |
Modulus (Remainder) | $a \mod b$ | a % b |
Exponentiation | $a^b$ | a ** b |
To calculate the sum of elements in a list:
numbers = [1, 2, 3, 4, 5]
total_sum = 0
for num in numbers:
total_sum += num # Output: 15
numbers = [1, 2, 3, 4, 5]
total_sum = 0
for num in numbers:
total_sum += num
average = total_sum / len(numbers) # Output: 3.0
a = [1, 2, 3]
b = [4, 5, 6]
c = []
for i in range(len(a)):
c.append(a[i] + b[i]) # Output: [5, 7, 9]
a = [1, 2, 3]
scalar = 3
result = []
for x in a:
result.append(scalar * x) # Output: [3, 6, 9]
a = [1, 2, 3]
b = [4, 5, 6]
dot_product = 0
for i in range(len(a)):
dot_product += a[i] * b[i] # Output: 32
vector = [1, 2, 3, 4, 5]
vector_sum = 0
for num in vector:
vector_sum += num # Output: 15
Python Code:
import math
a = [3, 4]
norm = 0
for x in a:
norm += x ** 2
norm = math.sqrt(norm) # Output: 5.0
Python Code:
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j] + B[i][j])
C.append(row)
# Output: [[6, 8], [10, 12]]
Python Code:
A = [[1, 2], [3, 4], [5, 6]]
v = [7, 8]
result = []
for i in range(len(A)):
row_sum = 0
for j in range(len(v)):
row_sum += A[i][j] * v[j]
result.append(row_sum)
# Output: [23, 53, 83]
Python Code:
A = [[1, 2, 3], [4, 5, 6]]
transpose = []
for i in range(len(A[0])): # Number of columns in original matrix
new_row = []
for j in range(len(A)): # Number of rows in original matrix
new_row.append(A[j][i])
transpose.append(new_row)
# Output: [[1, 4], [2, 5], [3, 6]]
Dog
, you can create objects like dog1
and dog2
, each representing a different dog with its own unique attributes (e.g., name, age).class
keyword, followed by the class name. Class names are usually written in PascalCase (each word capitalized).Dog
Class¶class Dog:
# Constructor method: Initializes an object of the class
def __init__(self, name, age):
self.name = name # Attribute to store the dog's name
self.age = age # Attribute to store the dog's age
# Method to make the dog bark
def bark(self):
print(f"{self.name} says: Woof!")
# Creating an object (instance) of the Dog class
my_dog = Dog("Buddy", 3)
__init__
Method (Constructor)¶__init__
is a special method (also known as a constructor) that is automatically called when you create a new object.self
is a reference to the current instance of the class and is used to access attributes and methods within the class.__init__
to Initialize Attributes¶class Car:
def __init__(self, make, model, year):
self.make = make # Set the make of the car
self.model = model # Set the model of the car
self.year = year # Set the year of the car
# Creating an object of the Car class
my_car = Car("Toyota", "Corolla", 2020)
print(my_car.make) # Output: Toyota
self
within the __init__
method or other methods.Dog
class example, name
and age
are attributes of the class.self
as their first parameter, which refers to the current instance of the class.Dog
class example, bark
is a method.self
Keyword¶self
refers to the instance of the class itself. It allows you to access the class's attributes and methods from within the class.self
as the first parameter in all method definitions.class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says: Woof!")
# Create objects of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Access attributes
print(dog1.name) # Output: Buddy
print(dog2.age) # Output: 5
# Call methods
dog1.bark() # Output: Buddy says: Woof!
dog2.bark() # Output: Max says: Woof!
.
notation.dog1.age = 4 # Changing the age of dog1
print(dog1.age) # Output: 4
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says: Woof!")
def describe(self):
print(f"{self.name} is {self.age} years old.")
# Using the new method
dog1 = Dog("Buddy", 3)
dog1.describe() # Output: Buddy is 3 years old.
__init__
method that initializes an object’s attributes.Here’s a more comprehensive example that models a Bank Account:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # Account owner
self.balance = balance # Account balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
else:
print(f"Insufficient funds! Current balance: ${self.balance}")
# Creating an object of BankAccount
my_account = BankAccount("Alice", 100)
# Using methods of the BankAccount class
my_account.deposit(50) # Output: Deposited $50. New balance: $150
my_account.withdraw(30) # Output: Withdrew $30. New balance: $120
my_account.withdraw(200) # Output: Insufficient funds! Current balance: $120
__init__
to initialize an object's attributes.self
is essential to access attributes and methods within the class.class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # Account owner
self.balance = balance # Account balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
else:
print(f"Insufficient funds! Current balance: ${self.balance}")
# Creating an object of BankAccount
my_account = BankAccount("Alice", 100)
# Using methods of the BankAccount class
my_account.deposit(50) # Output: Deposited $50. New balance: $150
my_account.withdraw(30) # Output: Withdrew $30. New balance: $120
my_account.withdraw(200) # Output: Insufficient funds! Current balance: $120
Deposited $50. New balance: $150 Withdrew $30. New balance: $120 Insufficient funds! Current balance: $120