Master Python Basics: Variables, Control Flow, Loops, Data Structures & OOP

This comprehensive tutorial walks you through Python fundamentals—from defining variables, booleans, strings, and numbers to using conditional statements, while and for loops, manipulating lists and dictionaries, and building classes with objects, encapsulation, and inheritance—providing clear code examples for each concept.

21CTO
21CTO
21CTO
Master Python Basics: Variables, Control Flow, Loops, Data Structures & OOP

Python is a high‑level, interpreted, interactive, and object‑oriented scripting language designed for readability, using English‑like keywords and distinctive syntax. It is widely used in data science, web development, and machine learning, with companies such as Quora, Pinterest, and Spotify employing it for backend services.

Variables

Variables store values. Assignment is straightforward:

one = 1

two = 2

some_number = 10000

Variables can hold integers, booleans, strings, floats, and other data types:

# booleans
true_boolean = True
false_boolean = False

# string
my_name = "Leandro Tk"

# float
book_price = 15.80

Control Flow: Conditional Statements

Use if to execute a block when a condition is true, optionally adding elif and else branches:

if True:
    print("Hello Python If")

if 2 > 1:
    print("2 is greater than 1")
else:
    print("1 is not greater than 2")

if 1 > 2:
    print("1 is greater than 2")
else:
    print("1 is not greater than 2")

if 1 > 2:
    print("1 is greater than 2")
elif 2 > 1:
    print("2 is greater than 1")
else:
    print("1 is equal to 2")

Loops / Iterators

While loop repeats while a condition holds:

num = 1
while num <= 10:
    print(num)
    num += 1

Example with a manual loop condition:

loop_condition = True
while loop_condition:
    print("Loop Condition keeps: %s" % loop_condition)
    loop_condition = False

For loop iterates over a range or collection:

for i in range(1, 11):
    print(i)

my_integers = [1, 2, 3, 4, 5]
for item in my_integers:
    print(item)

dictionary = {"some_key": "some_value"}
for key in dictionary:
    print("%s --> %s" % (key, dictionary[key]))

for key, value in dictionary.items():
    print("%s --> %s" % (key, value))

for attribute, value in dictionary_tk.items():
    print("My %s is %s" % (attribute, value))

Lists: Array Data Structure

Create a list and access elements by index (starting at 0):

my_integers = [1, 2, 3, 4, 5]
print(my_integers[0])  # 1
print(my_integers[1])  # 2
print(my_integers[4])  # 5

Lists can hold strings as well:

relatives_names = ["Toshiaki", "Juliana", "Yuji", "Bruno", "Kaio"]
print(relatives_names[0])  # Toshiaki

Add elements with append:

bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0])  # The Effective Engineer
print(bookshelf[1])  # The 4 Hour Work Week

Dictionaries: Key‑Value Data Structure

Define a dictionary with key‑value pairs:

dictionary_example = {"key1": "value1", "key2": "value2", "key3": "value3"}

Access values by key:

dictionary_tk = {"name": "Leandro", "nickname": "Tk", "nationality": "Brazilian"}
print("My name is %s" % dictionary_tk["name"])  # My name is Leandro
print("But you can call me %s" % dictionary_tk["nickname"])  # But you can call me Tk
print("And by the way I'm %s" % dictionary_tk["nationality"])  # And by the way I'm Brazilian

Add or modify entries directly:

dictionary_tk["age"] = 24
print(dictionary_tk)  # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}

Classes & Objects

Objects represent real‑world entities with data (attributes) and behavior (methods). A class is a blueprint for creating objects.

class Vehicle:
    pass

car = Vehicle()
print(car)  # <__main__.Vehicle object at ...>

Define an initializer to set 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_velocity

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels)  # 4

Getter and setter methods (or @property decorators) allow controlled access:

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_velocity

    @property
    def number_of_wheels(self):
        return self._number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(self, value):
        self._number_of_wheels = value

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)  # 2

Define regular methods for behavior:

class Vehicle:
    def make_noise(self):
        print('VRUUUUUUUM')

tesla_model_s.make_noise()  # VRUUUUUUUM

Encapsulation: Hiding Information

Public attributes are accessible directly, while private attributes (prefixed with an underscore) are intended for internal use.

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name      # public
        self._email = email               # private

    def update_email(self, new_email):
        self._email = new_email

    def email(self):
        return self._email

p = Person('TK', '[email protected]')
print(p.first_name)   # TK
print(p.email())      # [email protected]
p._email = '[email protected]'   # discouraged direct access
print(p.email())      # still [email protected]
p.update_email('[email protected]')
print(p.email())      # [email protected]

Public methods can be called from outside; private methods (prefixed with an underscore) are meant for internal use only.

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._age

    def _show_age(self):
        return self._age

p = Person('TK', 25)
print(p.show_age())   # 25
print(p._show_age()) # 25 (still accessible but considered private)

Inheritance

Subclassing allows a child class to inherit attributes and methods from a parent class.

class Car:
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)      # 4
print(my_car.seating_capacity)      # 5
print(my_car.maximum_velocity)     # 250

class ElectricCar(Car):
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)

my_electric_car = ElectricCar(4, 5, 250)
print(my_electric_car.number_of_wheels)      # 4
print(my_electric_car.seating_capacity)      # 5
print(my_electric_car.maximum_velocity)     # 250

These concepts enable code reuse, clearer organization, and easier maintenance.

Original translator: 机器之心 – thanks for the contribution. Original article: https://medium.freecodecamp.org/learning-python-from-zero-to-hero-120ea540b567
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Data StructuresObject-Oriented ProgrammingVariablesLoopsprogramming basicsControl Flow
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.