Mark As Completed Discussion

Working with Objects

In programming, objects are a powerful way to organize and manipulate data. An object is a collection of properties that are related to each other. Each property consists of a key-value pair, where the key is a string and the value can be of any data type.

Creating an Object

To create an object in Python, you can use curly braces {} and define the properties inside it. For example:

PYTHON
1# Create an empty object
2person = {}
3
4# Add properties to the object
5person['name'] = 'John'
6person['age'] = 30
7
8print(person)  # Output: {'name': 'John', 'age': 30}

Accessing Object Properties

You can access the value of a property in an object using dot notation . or bracket notation []. For example:

PYTHON
1# Using dot notation
2print(person.name)  # Output: 'John'
3
4# Using bracket notation
5print(person['name'])  # Output: 'John'

Modifying Object Properties

You can modify the value of a property in an object by assigning a new value to it. For example:

PYTHON
1person['age'] = 40
2print(person)  # Output: {'name': 'John', 'age': 40}

Iterating Over Object Properties

You can iterate over the properties of an object using a for loop. For example:

PYTHON
1for key in person:
2  print(key, person[key])

This will output each property key-value pair on a separate line.

Objects are a fundamental concept in programming and are used extensively in various applications. They provide a way to represent real-world entities and their characteristics. By understanding how to work with objects and access their properties, you can effectively organize and manipulate data in your programs.

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment