跳转至

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
# This is a single-line comment

"""
This is a 
multi-line comment
"""

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
x = 5       # Integer
y = "Hello" # String
z = 3.14    # Float

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): Represents True or False.
Python
1
2
3
4
a = 10          # int
b = 3.14        # float
c = "Python"    # str
d = True        # bool

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
x = 5
y = 2

# Arithmetic operations
print(x + y)  # 7
print(x - y)  # 3
print(x * y)  # 10
print(x / y)  # 2.5
print(x // y) # 2
print(x % y)  # 1
print(x ** y) # 25

# Comparison operations
print(x > y)  # True
print(x == y) # False

# Logical operations
print(x > 3 and y < 3) # True
print(not (x > 3))     # False

Conditional Statements

Use if-elif-else to write conditional statements:

Python
1
2
3
4
5
6
7
8
x = 10

if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

Loops

Python supports for and while loops.

  • for loop: 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, 4
    
  • while loop: 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
my_list = [1, 2, 3, 4, 5]

# Access elements
print(my_list[0])  # Outputs 1

# Add elements
my_list.append(6)

# Remove elements
my_list.remove(2)

# Slicing
print(my_list[1:4])  # Outputs [3, 4, 5]

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
my_dict = {"name": "Alice", "age": 25}

# Access value by key
print(my_dict["name"])  # Outputs "Alice"

# Add key-value pair
my_dict["city"] = "New York"

# Remove key-value pair
del my_dict["age"]

Functions

Functions are defined using the def keyword, and they can take parameters and return results.

Python
1
2
3
4
5
def add(a, b):
    return a + b

result = add(3, 5)  # result = 8
print(result)

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
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name}.")

# Create an object
p = Person("Alice", 30)
p.greet()  # Outputs "Hello, my name is Alice."

File Operations

Python can read from and write to files.

  • Writing to a file:
Python
1
2
with open('example.txt', 'w') as file:
    file.write("Hello, World!")
  • Reading from a file:
Python
1
2
3
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)  # Outputs "Hello, World!"

Exception Handling

Exception handling uses the try-except statement to catch and handle errors.

Python
1
2
3
4
5
6
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This will always execute")

Understanding these fundamentals will help you proceed to more advanced topics in Python development.