Python : Lists, Dictionaries, Classes and Exceptions

Lists

In Python, a list is an ordered collection of values that can be of any data type. You can create a list using square brackets (`[]`) and separating the values with commas. For example:

# create a list of integers
numbers = [1, 2, 3, 4, 5]

# create a list of strings
words = ["apple", "banana", "cherry"]

# create a list of mixed data types
items = [1, "apple", True, 3.14]

 

You can access the elements of a list using their index, which starts at 0 for the first element. For example:

# access the first element of the list
print(numbers[0])

# access the third element of the list
print(words[2])

# access the last element of the list
print(items[-1])

 

You can also modify the elements of a list using their index:

# change the value of the second element
numbers[1] = 10
print(numbers)

# add a new element to the end of the list
words.append("date")
print(words)

# insert a new element at a specific position
words.insert(1, "orange")
print(words)

Dictionaries

A dictionary in Python is a collection of key-value pairs. You can create a dictionary using curly braces (`{}`) and separating the key-value pairs with commas. The keys and values can be of any data type. For example:

# create a dictionary
person = {
    "name": "Alice",
    "age": 25,
    "is_student": True
}

# access a value using its key
print(person["name"])

# add a new key-value pair to the dictionary
person["height"] = 1.65
print(person)

# update the value of an existing key
person["age"] = 26
print(person)

 

Classes and Objects

In Python, you can use classes to define custom data types. A class is like a blueprint for an object, which is an instance of the class. You can define the attributes and behaviors of a class using methods.

# define a class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")

# create an object of the class
alice = Person("Alice", 25)

# access the attributes of the object
print(alice.name)
print(alice.age)

# call the method of the object
alice.greet()

 

Exceptions

In Python, you can use exceptions to handle runtime errors. For example, you might want to handle a `ZeroDivisionError` exception when trying to divide a number by zero.

try:
    x = 10 / 0
except ZeroDivisionError:
    print