Fundamentals 14 min read

Comprehensive Python Basics: Variables, Data Types, Control Structures, Functions, OOP, Standard Library, and More

This article provides a comprehensive Python tutorial covering variables, data types, control structures, functions, classes, standard library modules, file I/O, exception handling, comprehensions, generators, decorators, modules, virtual environments, coding style, and Git version control, complete with example code snippets.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Comprehensive Python Basics: Variables, Data Types, Control Structures, Functions, OOP, Standard Library, and More

This guide introduces Python programming fundamentals in a structured manner.

1. Variables and Data Types – Variables store data, and assignment uses the = operator. Example definitions include integers, floats, strings, booleans, lists, tuples, dictionaries, and sets:

变量:用于存储数据的标识符。
赋值:使用 = 运算符将值赋给变量。
x = 10  # 整数
y = 3.14  # 浮点数
name = "Alice"  # 字符串
is_student = True  # 布尔值

Additional examples for each type:

x = 10
y = -5
z = 0
pi = 3.14159
temperature = 23.5
name = "Alice"
message = 'Hello, world!'
greeting = f"Hello, {name}!"  # f-string
is_student = True
is_teacher = False
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "two", 3.0, True]
coordinates = (10, 20)
colors = ("red", "green", "blue")
person = {"name": "Bob", "age": 30, "city": "New York"}
settings = {"theme": "dark", "language": "en"}
unique_numbers = {1, 2, 3, 4, 5}
vowels = {'a', 'e', 'i', 'o', 'u'}

2. Control Structures – Conditional statements and loops control program flow.

x = 10
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
for i in range(5):  # 0, 1, 2, 3, 4
    print(i)
count = 0
while count < 5:
    print(count)
    count += 1

3. Functions – Define reusable blocks with def, accept parameters, and return values.

def greet(name):
    return f"Hello, {name}!"
print(greet("Alice"))  # 输出: Hello, Alice!
def add(a, b):
    return a + b

def greet_with_message(name, message="Hello"):
    return f"{message}, {name}!"

def multiply(*args):
    result = 1
    for num in args:
        result *= num
    return result

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print(add(3, 5))  # 输出: 8
print(greet_with_message("Alice"))  # 输出: Hello, Alice!
print(greet_with_message("Bob", "Hi"))  # 输出: Hi, Bob!
print(multiply(2, 3, 4))  # 输出: 24
print_info(name="Alice", age=30, city="New York")

4. Classes and Objects – Object‑oriented programming with classes, inheritance, methods, and attributes.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")

person = Person("Alice", 30)
person.display()  # 输出: Name: Alice, Age: 30
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    def study(self):
        print(f"{self.name} is studying.")

student = Student("Bob", 20, "Sophomore")
student.display()  # 输出: Name: Bob, Age: 20
student.study()  # 输出: Bob is studying.

5. Standard Library – Common modules for OS interaction, system info, dates, math, and randomness.

import os
current_directory = os.getcwd()
print(f"Current directory: {current_directory}")
files = os.listdir(current_directory)
print(f"Files in the directory: {files}")
import sys
print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")
print(f"Command-line arguments: {sys.argv}")
from datetime import datetime
now = datetime.now()
print(f"Current date and time: {now}")
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")
import math
sqrt_value = math.sqrt(16)
print(f"Square root of 16: {sqrt_value}")
pi_value = math.pi
print(f"Value of pi: {pi_value}")
import random
random_number = random.randint(1, 100)
print(f"Random number between 1 and 100: {random_number}")
random_float = random.random()
print(f"Random float between 0 and 1: {random_float}")

6. File Operations – Reading, writing, and appending files using open.

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)
with open('file.txt', 'r') as file:
    for line in file:
        print(line.strip())
with open('output.txt', 'w') as file:
    file.write("Hello, World!
")
    file.write("This is a new line.
")
with open('output.txt', 'a') as file:
    file.write("This is an appended line.
")

7. Exception Handling – Managing errors with try, except, finally, and raise.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
try:
    x = int(input("Enter a number: "))
    y = 10 / x
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
try:
    file = open('file.txt', 'r')
    content = file.read()
    print(content)
except FileNotFoundError:
    print("File not found.")
finally:
    file.close()
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    age = validate_age(-5)
except ValueError as e:
    print(e)

8. List Comprehensions – Concise list creation.

squares = [x**2 for x in range(10)]
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # 输出: [0, 4, 16, 36, 64]

9. Dictionary Comprehensions – Concise dictionary creation.

squares_dict = {x: x**2 for x in range(10)}
print(squares_dict)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
even_squares_dict = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares_dict)  # 输出: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

10. Generator Expressions – Lazy evaluation of sequences.

squares_gen = (x**2 for x in range(10))
for square in squares_gen:
    print(square)

11. Decorators – Modify or extend function behavior.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
def repeat(num_times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

12. Modules and Packages – Organize code into reusable units.

# my_module.py

def greet(name):
    return f"Hello, {name}!"

# main.py
import my_module
print(my_module.greet("Alice"))
# my_package/
# ├── __init__.py
# ├── module1.py
# └── module2.py

# module1.py

def add(a, b):
    return a + b

# module2.py

def subtract(a, b):
    return a - b

# main.py
from my_package.module1 import add
from my_package.module2 import subtract
print(add(3, 5))  # 输出: 8
print(subtract(10, 5))  # 输出: 5

13. Virtual Environments – Isolate project dependencies.

python -m venv myenv
source myenv/bin/activate  # macOS/Linux
myenv\Scripts\activate     # Windows
pip install requests
pip freeze > requirements.txt  # 生成依赖文件
pip install -r requirements.txt  # 安装依赖

14. Code Style (PEP 8) – Follow Python’s official style guide.

def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
    """
    return length * width

15. Version Control (Git) – Track changes and collaborate.

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/yourrepo.git
git push -u origin master
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.

Pythonfunctionsobject‑oriented programmingVariablesStandard Libraryprogramming basicsControl structures
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

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.