Python Basics: Variables, Control Flow, Data Structures, and Object‑Oriented Programming
This tutorial introduces Python fundamentals, covering why to learn the language, variable assignment, conditional statements, loops, lists, dictionaries, iteration techniques, and core object‑oriented concepts such as classes, getters/setters, encapsulation, and inheritance, all illustrated with clear code examples.
Python is a high‑level programming language designed for readability and concise syntax, making it ideal for rapid development across domains such as data science, web development, and machine learning.
Key reasons to start learning Python include its elegant syntax and versatility in handling many programming tasks.
Basics
1. Variables
A variable is simply a name that stores a value. Assignment is straightforward:
one = 1You can assign additional values similarly:
two = 2
some_number = 10000Python also supports booleans, strings, and floats:
# booleans
true_boolean = True
false_boolean = False
# string
my_name = "Leandro Tk"
# float
book_price = 15.802. Control Flow: Conditional Statements
The if statement evaluates a logical expression; if it is True , the indented block runs:
if True:
print("Hello Python If")
if 2 > 1:
print("2 is greater than 1")If the condition is False , the else block executes:
if 1 > 2:
print("1 is greater than 2")
else:
print("1 is not greater than 2")You can also use elif (else‑if) for multiple branches.
if 1 > 2:
print("1 is greater than 2")
elif 2 > 1:
print("1 is not greater than 2")
else:
print("1 is equal to 2")3. Loops / Iterators
While loop repeats while a condition remains True :
num = 1
while num <= 10:
print(num)
num += 1Another example demonstrates an explicit loop condition:
loop_condition = True
while loop_condition:
print("Loop Condition keeps: %s" % loop_condition)
loop_condition = FalseFor loop iterates over a sequence, commonly using range :
for i in range(1, 11):
print(i)Lists: Collections / Arrays
Lists store ordered collections of values:
my_integers = [1, 2, 3, 4, 5]
print(my_integers[0]) # 1You can retrieve elements by index (starting at 0). Adding items uses append :
bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective EngineerDictionaries: Key‑Value Data Structure
Dictionaries map keys to values, allowing any immutable type as a key:
dictionary_example = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
print(dictionary_example["key1"]) # value1Accessing values uses the key directly:
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}
print("My name is %s" % dictionary_tk["name"]) # My name is LeandroYou can add new key‑value pairs by assignment:
dictionary_tk["age"] = 24
print(dictionary_tk)
# {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}Iterating Over Data Structures
Iterate over a list with for :
bookshelf = ["The Effective Engineer", "The 4 hours work week", "Zero to One", "Lean Startup", "Hooked"]
for book in bookshelf:
print(book)Iterate over a dictionary’s keys:
dictionary = {"some_key": "some_value"}
for key in dictionary:
print("%s --> %s" % (key, dictionary[key]))Or iterate over both keys and values:
for key, value in dictionary.items():
print("%s --> %s" % (key, value))Object‑Oriented Programming (OOP)
Classes define blueprints; objects are instances. Example class:
class Vehicle:
pass
car = Vehicle()
print(car) # <__main__.Vehicle object at ...>Initialize attributes via __init__ :
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)Getter and setter methods can be created manually or with the @property decorator:
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
@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 = valueMethods define behavior, e.g., making noise:
class Vehicle:
def make_noise(self):
print('VRUUUUUUUM')
tesla_model_s.make_noise() # VRUUUUUUUMEncapsulation hides internal state. Public attributes are accessed directly, while “private” (conventionally prefixed with an underscore) are accessed via methods:
class Person:
def __init__(self, first_name, email):
self.first_name = first_name
self._email = email
def email(self):
return self._email
def update_email(self, new_email):
self._email = new_emailInheritance allows a subclass to reuse and extend 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
class ElectricCar(Car):
def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
super().__init__(number_of_wheels, seating_capacity, maximum_velocity)Instances of ElectricCar inherit all attributes from Car without additional code.
Conclusion
The tutorial covered Python fundamentals: variables, conditional statements, loops, lists, dictionaries, iteration patterns, classes, attributes, methods, getters/setters with @property , encapsulation, and inheritance. Mastery of these concepts provides a solid foundation for further Python development.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.