Python 基础语法¶
这篇简单到不好评价,纯属水文,凑文字罢了
Comments¶
Python uses # for single-line comments.
For multi-line comments, you can use triple quotes (""" or ''').
| Python | |
|---|---|
1 2 3 4 5 6 | |
Variables¶
In Python, variables are dynamically typed, meaning you don't need to declare their type. Variable names can include letters, numbers, and underscores, but cannot start with a number.
| Python | |
|---|---|
1 2 3 | |
Data Types¶
Python offers several basic data types:
- Integer (
int): Represents whole numbers. - Float (
float): Represents decimal numbers. - String (
str): Represents text data. - Boolean (
bool): RepresentsTrueorFalse.
| Python | |
|---|---|
1 2 3 4 | |
Operators¶
Python supports various operators, including arithmetic, comparison, and logical operators.
- Arithmetic Operators:
+,-,*,/,//,%,** - Comparison Operators:
==,!=,>,<,>=,<= - Logical Operators:
and,or,not
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Conditional Statements¶
Use if-elif-else to write conditional statements:
| Python | |
|---|---|
1 2 3 4 5 6 7 8 | |
Loops¶
Python supports for and while loops.
forloop: Iterates over a sequence (like a list, tuple, or string).Python 1 2
for i in range(5): print(i) # Outputs 0, 1, 2, 3, 4whileloop: Repeats as long as a condition is true.Python 1 2 3 4 5
x = 5 while x > 0: print(x) x -= 1 # Decreases x by 1 each iteration
Lists¶
A list is an ordered, mutable collection, defined with square brackets.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Dictionaries¶
A dictionary is an unordered, mutable collection that stores key-value pairs, defined with curly braces.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 | |
Functions¶
Functions are defined using the def keyword, and they can take parameters and return results.
| Python | |
|---|---|
1 2 3 4 5 | |
Classes¶
Python is an object-oriented programming language, so you can create classes and objects. A class is defined using the class keyword.
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
File Operations¶
Python can read from and write to files.
- Writing to a file:
| Python | |
|---|---|
1 2 | |
- Reading from a file:
| Python | |
|---|---|
1 2 3 | |
Exception Handling¶
Exception handling uses the try-except statement to catch and handle errors.
| Python | |
|---|---|
1 2 3 4 5 6 | |
Understanding these fundamentals will help you proceed to more advanced topics in Python development.