Fundamentals 20 min read

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

This tutorial introduces Python by explaining what it is, why to learn it, and then walks through core fundamentals such as variables, conditional statements, loops, lists, dictionaries, iteration techniques, and object‑oriented concepts like classes, encapsulation, and inheritance, all illustrated with clear code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Basics: Variables, Control Flow, Data Structures & OOP Explained

Python Basics

Python is a high‑level programming language designed for readability and concise syntax, allowing developers to express ideas with minimal code. It is widely used in artificial intelligence, data science, web development, and many other fields.

Variables

Variables act as named containers for values. Assigning a value is straightforward:

one = 1
two = 2
some_number = 10000

Python supports integers, booleans, strings, floats, and other data types.

Control Flow: Conditional Statements

The if statement evaluates an expression and executes the block when the condition is true. An else block runs when the condition is false, and elif adds additional 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")
elif 2 > 1:
    print("2 is greater than 1")
else:
    print("1 is equal to 2")

Loops and Iteration

Python provides while and for loops. A while loop repeats while a condition remains true:

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

An equivalent for loop uses range:

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

Lists: Collections | Arrays | Data Structures

Lists store ordered collections of items and support indexing:

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

Lists can also hold strings:

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

Appending elements adds them to the end of the list:

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

Dictionary: Key‑Value Data Structure

Dictionaries map keys to values. Example:

dictionary_example = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
print(dictionary_example["key1"])  # value1

Accessing and updating values is done via the key:

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

Iteration: Looping Through Data Structures

Iterating over a list:

bookshelf = ["The Effective Engineer", "The 4 hours work week", "Zero to One", "Lean Startup", "Hooked"]
for book in bookshelf:
    print(book)

Iterating over a dictionary prints each key‑value pair:

for key, value in dictionary_tk.items():
    print(f"{key} --> {value}")

Classes & Objects

Classes define blueprints for objects. Example of a simple class:

class Vehicle:
    pass

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

Attributes are set in the __init__ method, and methods provide behavior:

class Vehicle:
    def __init__(self, wheels, tank, seats, max_speed):
        self.wheels = wheels
        self.tank = tank
        self.seats = seats
        self.max_speed = max_speed

    def make_noise(self):
        print("VRUUUUUUUM")

tesla = Vehicle(4, 'electric', 5, 250)
print(tesla.wheels)  # 4
tesla.make_noise()   # VRUUUUUUUM

Python supports property decorators for getters and setters:

class Vehicle:
    def __init__(self, wheels):
        self._wheels = wheels

    @property
    def wheels(self):
        return self._wheels

    @wheels.setter
    def wheels(self, value):
        self._wheels = value

v = Vehicle(4)
print(v.wheels)  # 4
v.wheels = 2
print(v.wheels)  # 2

Encapsulation: Hiding Information

Encapsulation restricts direct access to an object's data. Public attributes are defined normally, while non‑public (conventionally private) attributes start with an underscore:

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

    def email(self):
        return self._email

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

p = Person('TK', '[email protected]')
print(p.email())          # [email protected]
p.update_email('[email protected]')
print(p.email())          # [email protected]

Inheritance: Behavior and Features

Classes can inherit attributes and methods from a parent class:

class Car:
    def __init__(self, wheels, seats, max_speed):
        self.wheels = wheels
        self.seats = seats
        self.max_speed = max_speed

class ElectricCar(Car):
    pass

my_electric = ElectricCar(4, 5, 250)
print(my_electric.wheels)      # 4
print(my_electric.seats)      # 5
print(my_electric.max_speed)  # 250

Summary

The article covered essential Python concepts: variable assignment, conditional statements, while and for loops, list and dictionary data structures, iteration techniques, and core object‑oriented programming principles such as classes, objects, getters/setters, encapsulation, and inheritance.

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.

PythonData Structuresobject‑oriented programming
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.