Master Python Loops, Dictionaries, and OOP Basics with Practical Examples
This tutorial walks you through Python's for loops, iterating over lists and dictionaries, demonstrates key-value access, explores class definitions, constructors, getters, setters, and property decorators, and shows how to create and manipulate objects with clear code examples.
Welcome back to our Python learning series. In the previous article we covered lists and dictionaries; now we continue with iteration and object‑oriented programming.
For Loops and Iterators
Python makes iterating over a list straightforward with a for loop:
bookshelf = [
"传习录",
"禅与摩托车修理技术",
"Python 从Zero到Hero",
"从零到一",
""
]
for book in bookshelf:
print(book)The code prints each book title in order.
Iterating over a dictionary requires accessing its keys:
dictionary = { "some_key": "some_value" }
for key in dictionary:
print("%s --> %s" % (key, dictionary[key]))Output: #some_key --> some_value You can also iterate over key‑value pairs directly:
dictionary = { "some_key": "some_value" }
for key, value in dictionary.items():
print("%s --> %s" % (key, value))The result is the same. The variable names are arbitrary, as shown here:
dictionary_ex = {
"name": "Raymond",
"nickname": "Luoyi",
"nationality": "China",
"age": 38
}
for attribute, value in dictionary_ex.items():
print("My %s is %s" % (attribute, value))Output:
# My name is Raymond
# My nickname is Luoyi
# My nationality is China
# My age is 38Classes and Objects
Objects model real‑world entities such as cars, cats, or washing machines, encapsulating data (attributes) and behavior (methods). In Python, a class serves as a blueprint:
class Vehicle:
passCreate an instance:
car = Vehicle()
print(car) # <__main__.Vehicle object at 0x...>Define a constructor to initialise attributes:
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocityInstantiate a specific vehicle: tesla_model_s = Vehicle(4, 'electric', 5, 250) Implement getters and setters (traditional methods):
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
# other attributes omitted for brevity
def number_of_wheels(self):
return self.number_of_wheels
def set_number_of_wheels(self, number):
self.number_of_wheels = numberPython’s @property decorator provides a cleaner approach:
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self._number_of_wheels = number_of_wheels
# other attributes omitted
@property
def number_of_wheels(self):
return self._number_of_wheels
@number_of_wheels.setter
def number_of_wheels(self, number):
self._number_of_wheels = numberUsing the property:
tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2
print(tesla_model_s.number_of_wheels) # 2Another example method demonstrates custom behavior:
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
# other attributes omitted
def make_noise(self):
print('VRUUUUUUUM')Calling the method:
tesla_model_s = Vehicle(4, 'electric', 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUMFuture topics will cover encapsulation (hiding data and methods) and inheritance.
Author: 21CTO Community – This article is part of a Python development series.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
