Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Python Concepts and Practical Examples

Tech May 19 5

Basic Output and String Handling

The print() function outputs data to the console. Special characters like quotes can be escaped with a backslash:

print('Let\'s go!')
print("He said, \"Hello!\"")

Use \t for tabs and triple quotes for multi-line strings:

print('''Line one
Line two''')

Variables and Naming

Python 3 supports Unicode identifiers, allowing varialbe names in Chinese or other languages:

姓名 = "张三"
print(姓名)

String Manipulation

Common string methods include case conversion and whitespace trimming:

text = "  Hello World  "
print(text.strip().title())  # "Hello World"

F-strings enable embedded expressions:

name = "Alice"
greeting = f"Hi, {name.upper()}!"
print(greeting)  # "Hi, ALICE!"

Numeric Operations

The math module provides advanced functions:

import math
print(math.sqrt(16))   # 4.0
print(math.log(100, 10))  # 2.0

Data Types

Key types include:

  • str: Text sequences (e.g., "abc")
  • bool: True or False
  • NoneType: Represents absence of value (None)

Type inspection and length:

value = 42.0
print(type(value))  # <class 'float'>
print(len("Python"))  # 6

List Operations

Create and modify lists:

items = ["apple", "banana"]
items.append("cherry")
items.insert(1, "blueberry")
items.remove("banana")

Sorting and iteration:

numbers = [3, 1, 4]
for num in sorted(numbers):
    print(num)

Dictionaries

Store key-value pairs with immutable keys:

inventory = {
    ("widget", "A"): 150,
    ("gadget", "B"): 89
}
print(inventory[("widget", "A")])  # 150

Iterate through entries:

for product, stock in inventory.items():
    if stock < 100:
        print(f"Low stock: {product}")

Control Flow

for loops iterate over known sequences; while loops continue until a conditoin fails:

count = 0
while count < 3:
    print(count)
    count += 1

Functions

Define reusable blocks of code:

def calculate_area(radius):
    return 3.14159 * radius ** 2

area = calculate_area(5)

Object-Oreinted Programming

Classes encapsulate data and behavior:

class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model
    
    def describe(self):
        return f"{self.make} {self.model}"

car = Vehicle("Toyota", "Camry")
print(car.describe())

Inheritance extends functionality:

class ElectricCar(Vehicle):
    def __init__(self, make, model, battery_size):
        super().__init__(make, model)
        self.battery_size = battery_size

File Handling

Read and write files using pathlib:

from pathlib import Path

data_file = Path("data.txt")
content = data_file.read_text()
lines = content.splitlines()

output_file = Path("output.txt")
output_file.write_text("Processed data")

Error Handling

Manage exceptions gracefully:

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input")
else:
    print(f"Square: {number ** 2}")

Data Visualization

Install packages efficiently using mirrors:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib

Process structured data formats:

import csv
import json

# Read CSV
with open("data.csv") as f:
    reader = csv.reader(f)
    headers = next(reader)

# Format JSON
data = {"key": "value"}
print(json.dumps(data, indent=2))

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.