Common Python Syntax

Whether you are a beginner in Python programming or an experienced developer looking to quickly review syntax, today we will organize common Python syntax, covering basic syntax, data structures, control flow, functions, and classes. Python has a large number of third-party dependency packages and a very active community.

Common Python Syntax

1. Basic Rules and Environment Setup
(1) Indentation and Comments
• Indentation: Python does not use curly braces {} to distinguish code blocks; it strictly uses indentation to organize logic! Generally, 4 spaces or 1 tab is used, and inconsistent indentation will result in an error, so be careful while writing code!
• Comments:
• Single-line comments use #, for example, # This is a comment, which is very convenient for adding explanations to the code;
• Multi-line comments use “”” comment content “””, suitable for writing large explanations (commonly used for function documentation and module introductions).
(2) Module Import and Output
• Module Import: Want to use someone else’s functionality? Use import modulename to import it with one click! For example, to process data, commonly use import pandas to directly reuse module code, greatly improving development efficiency!
• Output Debugging: print(“Hello, World!”) is a must-learn for beginners, and in actual development, it is used to print variables and debug logic.

If you prefer a graphical IDE operation style, in addition to using PyCharm, you can also install the Jupyter dependency and then program through Jupyter Notebook.

2. Summary of Data Structures
In Python, lists, tuples, and dictionaries are known as the “Three Musketeers” for data processing, each with unique uses. Let’s look at examples:
(1) Lists – Flexible and mutable “containers”
Definition: scores = [‘A’, ‘C’, 90, 75, ‘C’], which can store different types of data such as strings and numbers, supporting addition, deletion, modification, and querying:
• Accessing Values:
• Indexing: scores[0] retrieves the first element ‘A’, scores[-1] retrieves the last element ‘C’;
• Slicing: scores[1:3] retrieves elements from index 1 to 2 (left closed, right open) [‘C’, 90], super convenient!
• Adding, Deleting, Modifying:
• scores.append(100): appends the element 100 to the end;
• scores.remove(‘A’): deletes the first ‘A’;
• scores[2] = 85: directly modifies the element at index 2 to 85;
• scores.pop(): deletes and returns the last element, scores.pop(2) deletes the element at index 2.
• Other Operations:
• len(scores): gets the length of the list (number of elements);
• scores.count(‘C’): counts the occurrences of ‘C’;
• scores.sort(): sorts the list elements (default ascending order, can sort both numbers and strings).
(2) Tuples – Immutable “safe boxes”
Definition: tuple1 = (1, 2, 3, “a”, “z”), similar to lists, but cannot be modified after creation (immutable type), suitable for storing fixed data (such as coordinates, configuration parameters), ensuring program safety!
• Accessing Values: use indexing like lists, tuple1[3] retrieves “a”;
• Characteristics: because they are immutable, they save more memory, and in multi-threaded scenarios, you don’t have to worry about data being accidentally modified!
(3) Dictionaries – Key-value “mapping tables”
Definition: votes = {‘red’: 3, ‘blue’: 5}, stores data using key-value pairs, allowing quick lookup of values by key, super suitable for statistics and configurations:
• Adding, Deleting, Modifying:
• Accessing Values: votes[‘red’] retrieves 3, votes.get(‘green’) returns None if not found (safer than direct access);
• Adding/Modifying: votes[‘gold’] = 4 adds a key-value pair, votes[‘blue’] = 6 modifies the value of ‘blue’;
• Deleting: del votes[‘gold’] deletes the key-value pair;
• Iteration Operations:
• votes.keys(): gets all keys (e.g., [‘blue’, ‘red’]);
• votes.values(): gets all values (e.g., [6, 3]);
• votes.items(): iterates through key-value pairs, for color, count in votes.items(): print(color, count) super convenient!

3. Control Flow: Making Programs “Smart” Decisions
(1) Conditional Statements (if/elif/else) Execute code based on different conditions, such as checking the weather or user permissions:
isSunny = True
temp = 95
bath = 85
job = ‘dev’
if isSunny:
print(“It’s sunny!”)
elif 90 <= temp < 100 and bath > 80:
print(“Bath is hot and full!”)
elif not (job == ‘qa’ or user == ‘adm’):
print(“Match if not qa or adm”)
else:
print(“No match. Job is ” + job)
• Supports multi-condition nesting and logical operators (and/or/not), making complex judgments easy to handle!
(2) Loops: Batch Processing Data
1. For Loop – Iterate through sequences/dictionaries
• Iterating through lists: grades = [‘A’, ‘C’, ‘B’, ‘F’]
for grade in grades:
print(grade) # Print grades one by one
• Iterating through dictionaries: inv = {‘apples’: 7, ‘peaches’: 4}
for fruit, count in inv.items():
print(f”We have {count} {fruit}”) # Print “We have 7 apples…”
• Using range to generate sequences:
• for i in range(10): iterates from 0 to 9;
• for i in range(5, 10): iterates from 5 to 9;
• for i in range(9, 2, -1): iterates from 9 to 3 (in reverse).
2. While Loop – Executes as long as the condition is met
i = 0
while True:
i += 1
if i == 3:
continue # Skip the current loop, continue to the next
if i == 7:
break # Terminate the loop
print(i) # Outputs 1 2 4 5 6
• Combine break (terminate loop) and continue (skip current iteration) to flexibly control flow, which can be used for handling “retry logic” or “listening tasks”.

4. Functions and Classes: Building Complex Programs
(1) Functions – Encapsulating Repetitive Logic
Use def to define functions, supporting default parameters, packaging repetitive code, and calling it directly:
def sumNums(numOne, numTwo=0):
“””Calculate the sum of two numbers, numTwo defaults to 0″””
return numOne + numTwo
print(sumNums(3, 4)) # Pass two parameters, output 7
print(sumNums(3)) # Use default parameter, output 3
• Benefits: Code is more concise, and next time you need to calculate, you can call it directly without rewriting logic!
(2) Classes – Object-Oriented Programming
Define class to encapsulate attributes (data) and methods (functions), making code more modular:
class Person:
def __init__(self, name, age):
“””Initialization method, assigning attributes to the object”””
self.name = name
self.age = age
def birthYear(self, current_year):
“””Calculate birth year”””
return current_year – self.age
# Create object
user = Person(‘Jimmy’, 27)
print(user.name) # Access attribute, output ‘Jimmy’
print(user.birthYear(2025)) # Call method, output 1998 (2025-27)
• init is the constructor method, automatically executed when creating an object;
• Each method’s first parameter is self, representing the object itself, used to access attributes/call other methods.

5. String Operations: Essential for Text Processing
Strings also have many practical operations, let’s look at examples:
title = “Us and them”
# Get the first character
print(title[0]) # Output ‘U’
# Capitalize the first letter
print(title.title()) # Output ‘Us And Them’
# Split by space
print(title.split(‘ ‘)) # Output [‘Us’, ‘and’, ‘them’]
# Join characters
print(‘:’.join([‘A’, ‘B’, ‘C’])) # Output ‘A:B:C’
# Replace content
print(title.replace(‘them’, ‘us’)) # Output ‘Us and us’
# Convert to integer (note: string content must be a number)
nine = int(“9”) + 1 # Output 10
• Splitting, joining, replacing, type conversion… Text processing scenarios (such as parsing logs, handling user input) rely on these operations.

No matter if you are writing scripts for automation, doing data analysis, or developing web applications, mastering these Python syntax is essential, and practice in real scenarios is key.

Leave a Comment