Master Python Basics: Variables, Control Flow, Data Structures & OOP
This comprehensive guide walks you through Python fundamentals, covering variable assignment, data types, conditional statements, loops, list and dictionary operations, as well as class definitions, object instantiation, encapsulation, and inheritance, all illustrated with clear code examples.
Introduction to Python
Python is a high‑level, readable language used for data science, web development, and machine learning. Its design emphasizes clear syntax and supports multiple programming paradigms.
Variables
Assign values to names using the = operator:
one = 1
two = 2
some_number = 10000Python supports booleans, strings, floats, and other types:
# booleans
true_boolean = True
false_boolean = False
# string
my_name = "Leandro Tk"
# float
book_price = 15.80Control Flow – Conditional Statements
Use if, elif, and else to execute code based on conditions:
if True:
print("Hello Python If")
if 2 > 1:
print("2 is greater than 1")
else:
print("1 is not greater than 2")
elif 1 > 2:
print("1 is greater than 2")
else:
print("1 is equal to 2")Loops
While loop repeats while a condition is true:
num = 1
while num <= 10:
print(num)
num += 1For loop iterates over a range or collection:
for i in range(1, 11):
print(i)
for book in bookshelf:
print(book)Lists (Arrays)
Create, index, and modify lists:
my_integers = [1, 2, 3, 4, 5]
print(my_integers[0]) # 1
bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective EngineerIterate over a list:
for book in bookshelf:
print(book)Dictionaries (Key‑Value)
Define and access key‑value pairs:
dictionary_example = {"key1": "value1", "key2": "value2", "key3": "value3"}
print(dictionary_example["key1"]) # value1
# add a new entry
dictionary_example["age"] = 24
print(dictionary_example)Iterate over keys and values:
for key, value in dictionary_example.items():
print(f"{key} --> {value}")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')
tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.make_noise() # VRUUUUUUUMUse @property for 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
# 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 = value
car = Vehicle(4, 'gas', 5, 180)
print(car.number_of_wheels) # 4
car.number_of_wheels = 2
print(car.number_of_wheels) # 2Encapsulation
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_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
Subclass a parent class to reuse its attributes and methods:
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 = ElectricCar(4, 5, 250)
print(my_electric.number_of_wheels) # 4
print(my_electric.seating_capacity) # 5
print(my_electric.maximum_velocity) # 250These examples provide a solid foundation for writing Python code in machine‑learning, data‑science, and web‑development projects.
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.
