杰瑞科技汇

Python速查表有哪些核心要点?

Of course! Here is a comprehensive Python cheat sheet, designed to be a quick reference for beginners and intermediate developers. It's structured to cover the most common concepts you'll use daily.

Python速查表有哪些核心要点?-图1
(图片来源网络,侵删)

Python Cheat Sheet

Basic Syntax & Comments

# This is a single-line comment
"""
This is a multi-line comment.
It's often used for docstrings.
"""
# Print to the console
print("Hello, World!")
# Assign variables
message = "Hello, World!"
count = 10
pi = 3.14
is_learning = True

Data Types

Type Description Example
int Integer (whole numbers) 10, -5, 0
float Floating-point number (decimal) 14, -0.001, 0
str String (text) "Hello", 'Python'
bool Boolean (True/False) True, False
list Mutable ordered sequence [1, "a", 3.14]
tuple Immutable ordered sequence (1, "a", 3.14)
dict Mutable key-value pairs {"name": "Alice", "age": 30}
set Unordered collection of unique items {1, 2, 3}

Variables & Operators

# Assignment
x = 5
y = "text"
# Arithmetic
result = 10 + 5   # Addition (15)
result = 10 - 5   # Subtraction (5)
result = 10 * 5   # Multiplication (50)
result = 10 / 3   # Division (3.333...)
result = 10 // 3  # Floor division (3)
result = 10 % 3   # Modulus (remainder, 1)
result = 10 ** 2  # Exponentiation (100)
# Comparison (return True/False)
is_equal = (5 == 5)    # True
is_not_equal = (5 != 3) # True
is_greater = (10 > 5)  # True
is_less_or_equal = (5 <= 5) # True
# Logical
and_result = True and False  # False
or_result = True or False   # True
not_result = not True       # False
# Membership (checks if item is in sequence)
'in_list = "a" in ["a", "b", "c"]  # True
not_in_list = "z" not in [1, 2, 3] # True

Strings

# String creation
s1 = "Hello"
s2 = 'World'
s3 = """This is a
multi-line string."""
# Accessing characters (indexing, 0-based)
first_char = s1[0]  # 'H'
last_char = s1[-1]  # 'o'
# Slicing [start:stop:step]
substring = s1[1:4]   # 'ell' (from index 1 up to, but not including, 4)
reverse_str = s1[::-1] # 'olleH' (step backwards)
# Common methods
new_s = s1.lower()          # 'hello'
new_s = s1.upper()          # 'HELLO'
new_s = s1.replace("l", "p") # 'Heppo'
length = len(s1)            # 5
# Formatting (f-strings are modern and preferred)
name = "Alice"
age = 30
formatted_str = f"My name is {name} and I am {age} years old."
# Output: "My name is Alice and I am 30 years old."

Lists (Mutable Sequences)

# Creation
my_list = [1, "a", 3.14, True]
empty_list = []
# Accessing & Slicing
first_item = my_list[0]      # 1
last_item = my_list[-1]      # True
sub_list = my_list[1:3]      # ['a', 3.14]
# Modifying (Lists are mutable)
my_list.append(99)          # Add to the end: [1, 'a', 3.14, True, 99]
my_list.insert(0, "start")   # Insert at index 0: ['start', 1, 'a', ...]
my_list.remove("a")          # Remove the first occurrence of "a"
popped_item = my_list.pop()   # Remove and return last item (99)
del my_list[0]               # Delete item at index 0
# Common methods
length = len(my_list)        # Get number of items
my_list.sort()               # Sorts the list (in-place for numbers/strings)
my_list.reverse()            # Reverses the list (in-place)
my_list.clear()              # Removes all items
# List Comprehensions (a powerful way to create lists)
# Create a list of squares for numbers 0 to 9
squares = [x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Dictionaries (Key-Value Pairs)

# Creation
my_dict = {"name": "Bob", "age": 25, "city": "New York"}
# Alternative creation
my_dict2 = dict(name="Bob", age=25)
# Accessing values
name = my_dict["name"]      # 'Bob' (raises KeyError if key doesn't exist)
name_safe = my_dict.get("name") # 'Bob' (returns None if key doesn't exist)
age_safe = my_dict.get("job", "Unemployed") # 'Unemployed' (default value)
# Modifying
my_dict["age"] = 26         # Update value
my_dict["email"] = "bob@email.com" # Add new key-value pair
# Common methods
keys = my_dict.keys()       # dict_keys(['name', 'age', 'city', 'email'])
values = my_dict.values()   # dict_values(['Bob', 26, 'New York', ...])
items = my_dict.items()     # dict_items([('name', 'Bob'), ('age', 26), ...])
# Check for a key
has_name = "name" in my_dict # True

Control Flow

Conditionals (if/elif/else)

age = 18
if age < 13:
    print("Child")
elif age < 18:
    print("Teenager")
else:
    print("Adult")

Loops

# --- For Loop ---
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# Using range()
for i in range(5):          # Prints 0, 1, 2, 3, 4
    print(i)
for i in range(2, 10, 2):   # Prints 2, 4, 6, 8 (start, stop, step)
    print(i)
# --- While Loop ---
count = 0
while count < 5:
    print(count)
    count += 1  # Don't forget to increment!
# Looping through a dictionary
for key, value in my_dict.items():
    print(f"{key}: {value}")

Functions

# Basic function definition
def greet(name):
    """This is a docstring. It explains the function."""
    return f"Hello, {name}!"
# Calling a function
message = greet("Charlie")
print(message) # Output: Hello, Charlie!
# Function with default arguments
def power(base, exponent=2):
    return base ** exponent
print(power(3))      # 9 (uses default exponent=2)
print(power(3, 3))   # 27
# Function with multiple return values
def get_stats(numbers):
    return sum(numbers), len(numbers)
total, count = get_stats([1, 2, 3, 4, 5])
print(f"Total: {total}, Count: {count}")

File I/O

# --- Writing to a file ---
# 'w' mode creates the file or overwrites it if it exists.
with open("my_file.txt", "w") as f:
    f.write("Hello, this is the first line.\n")
    f.write("This is the second line.")
# --- Reading from a file ---
# 'r' is the default mode for reading.
with open("my_file.txt", "r") as f:
    # Read the whole file as a string
    content = f.read()
    print(content)
    # Read the file line by line
    f.seek(0) # Go back to the beginning of the file
    for line in f:
        print(line.strip()) # .strip() removes leading/trailing whitespace

Error Handling (Exceptions)

try:
    # Code that might cause an error
    result = 10 / 0
    value = my_dict["non_existent_key"]
except ZeroDivisionError:
    # Handle the specific error
    print("Cannot divide by zero!")
except KeyError:
    print("That key does not exist in the dictionary.")
except Exception as e:
    # Handle any other unexpected error
    print(f"An unexpected error occurred: {e}")
else:
    # This block runs ONLY if the 'try' block did NOT raise an error
    print("Everything went smoothly!")
finally:
    # This block ALWAYS runs, regardless of an error or not
    print("This cleanup code always runs.")

Modules & Imports

# Import an entire module
import math
print(math.sqrt(16)) # 4.0
# Import a specific function from a module
from math import pi, factorial
print(pi)          # 3.141592653589793
print(factorial(5)) # 120
# Import a module with an alias (convention for 'numpy')
import numpy as np
# Now you can use np instead of numpy

Useful Built-in Functions

Function Description Example
len() Returns the length of an object len([1, 2, 3]) -> 3
type() Returns the type of an object type("hello") -> <class 'str'>
range() Generates a sequence of numbers list(range(5)) -> [0, 1, 2, 3, 4]
input() Reads a line from user input name = input("Enter your name: ")
print() Prints objects to the console print("Hello")
isinstance() Checks if an object is an instance of a class isinstance(5, int) -> True
enumerate() Returns an enumerate object (index, value pairs) for i, v in enumerate(['a', 'b']): ...
zip() Aggregates elements from iterables list(zip([1, 2], ['a', 'b'])) -> [(1, 'a'), (2, 'b')]
Python速查表有哪些核心要点?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇