Master Python Basics: Variables, Loops, Data Structures, and OOP Explained
This comprehensive guide walks you through Python fundamentals, covering variables, conditional statements, loops, lists, dictionaries, and object‑oriented programming concepts with clear explanations and runnable code examples, providing a solid foundation for anyone learning Python for data science, web development, or automation.
Python is a high‑level, readable programming language created by Guido van Rossum. It combines interpreted, compiled, interactive, and object‑oriented features, making it suitable for data science, web development, and machine learning.
Variables
Assign values to variables using the = operator:
one = 1
two = 2
some_number = 10000Variables can hold booleans, strings, floats, and other data types:
# booleans
true_boolean = True
false_boolean = False
# string
my_name = "Leandro Tk"
# float
book_price = 15.80Conditional Statements
Use if, elif, and else to control flow based on conditions:
if True:
print("Hello Python If")
if 2 > 1:
print("2 is greater than 1")
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
While loop repeats while a condition is true:
num = 1
while num <= 10:
print(num)
num += 1Infinite loop example with a boolean flag:
loop_condition = True
while loop_condition:
print("Loop Condition keeps: %s" % (loop_condition))
loop_condition = FalseFor loop iterates over a range or a collection:
for i in range(1, 11):
print(i)
bookshelf = ["The Effective Engineer", "The 4 Hour Work Week", "Zero to One", "Lean Startup", "Hooked"]
for book in bookshelf:
print(book)Lists (Arrays)
Create and access list elements by index (starting at 0):
my_integers = [1, 2, 3, 4, 5]
print(my_integers[0]) # 1
print(my_integers[1]) # 2
my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5
print(my_integers[1]) # 7
print(my_integers[4]) # 4Append elements to a 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 WeekDictionaries (Key‑Value Mapping)
Define a dictionary with key‑value pairs:
dictionary_example = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
print(dictionary_example["key1"]) # value1Access and modify entries:
dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}
print("My name is %s" % (dictionary_tk["name"]))
print("But you can call me %s" % (dictionary_tk["nickname"]))
# Add a new key
dictionary_tk["age"] = 24
print(dictionary_tk) # {'name': 'Leandro', 'nickname': 'Tk', 'nationality': 'Brazilian', 'age': 24}Classes and Objects
Define a class with an initializer and methods:
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
def make_noise(self):
print('VRUUUUUUUM')
# Create an instance
tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.make_noise() # VRUUUUUUUMUse @property to create getters and setters:
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, number):
self._number_of_wheels = number
car = Vehicle(4, 'electric', 5, 250)
print(car.number_of_wheels) # 4
car.number_of_wheels = 2
print(car.number_of_wheels) # 2Encapsulation
Public attributes are accessed directly, while private attributes (prefixed with an underscore) are accessed via methods:
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.update_email('[email protected]')
print(p.email()) # [email protected]Inheritance
Define a base class Car and a subclass ElectricCar that inherits its attributes:
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)
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) # 250Source: Machine Heart (机器之心) Original article: Learning Python from Zero to Hero
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.
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.
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.
