Python syntax is renowned for its simplicity and readability, making it ideal for programming beginners. Below, I will systematically outline its core fundamental syntax.
🎯 Variables and Data Types
In Python, a variable can be understood as a label for data, and there is no need to declare its type before use; the interpreter will infer it automatically. The rules for naming variables are: typically use lowercase letters and underscores (e.g., user_name), cannot start with a number, and should avoid using Python keywords.
Basic Data Types: The common types are as follows:
| Type | Representation | Characteristics | Example |
|---|---|---|---|
| Integer (int) | Whole number | No size limit | age = 25 |
| Float (float) | Decimal number | Can use scientific notation | height = 1.75 |
| String (str) | Text | Enclosed in single or double quotes | name = “Alice” |
| Boolean (bool) | Logical value | Only True or False | is_student = True |
Composite Data Types: Used to organize more data.
List: An ordered mutable collection, represented by square brackets [], e.g., fruits = [“apple”, “banana”], elements can be added or removed.
Tuple: An ordered immutable collection, represented by parentheses (), e.g., dimensions = (1920, 1080), cannot be modified after creation.
Dictionary: An unordered collection of key-value pairs, represented by curly braces {}, e.g., person = {“name”: “Alice”, “age”: 25}, accessed by keys.
Set: An unordered collection of unique elements, also represented by curly braces {}, e.g., colors = {“red”, “green”, “blue”}, automatically removes duplicates.
⚙️ Operators
Operators are used to perform operations on variables and values.
Arithmetic Operators: + (addition), – (subtraction), * (multiplication), / (division), // (floor division), % (modulus), ** (exponentiation).
Comparison Operators: == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to), used for comparisons and return boolean values.
Logical Operators: and (and), or (or), not (not), used to combine multiple condition checks.
Assignment Operators: The basic =, and compound operators like +=, -=, etc., for example, a += 1 is equivalent to a = a + 1.
🚦 Control Flow
Control flow determines the order of code execution.
Conditional Statements (if…elif…else): Execute different code blocks based on the truth of conditions.
age = 18
if age < 18:
print(“Minor”)
elif age == 18:
print(“Just an adult”)
else:
print(“Adult”)
Loop Statements:
For Loop: Commonly used to iterate over sequences (like lists, strings) or iterable objects.
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
While Loop: Repeats the code block as long as the condition is True.
i = 0
while i < 5:
print(i)
i += 1 # Note to include a statement that changes the condition to avoid infinite loops
📝 Functions
A function is a reusable block of code, defined using the def keyword.
def greet(name):
“””This is a greeting function (docstring)”””
return f”Hello, {name}!”
message = greet(“Bob”)
print(message) # Output: Hello, Bob!
🧱 Code Blocks and Indentation
A notable feature of Python is the use of indentation (typically 4 spaces) to define code blocks, such as function bodies, conditionals, loops, etc. This is a syntactical requirement, and statements at the same indentation level form a code block. Maintaining good indentation practices is key to writing correct and readable Python code.
💡 How to Start Practicing?
Set Up Environment: You can download the latest version from the official Python website, and remember to check “Add Python to PATH” during installation. Using editors like VS Code, PyCharm, or Jupyter Notebook can enhance your coding experience.
Start Small: Begin with simple programs, such as a calculator or a to-do list.
Utilize Resources: When encountering problems, make good use of official documentation and online practice platforms like Codecademy and LeetCode.