杰瑞科技汇

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

Of course! Here is a comprehensive Python cheatsheet covering the most essential topics, from basic syntax to advanced features. It's designed to be a quick reference for developers of all levels.

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

Python Cheatsheet

Basics & Syntax

# This is a single-line comment
"""
This is a multi-line comment.
Also known as a docstring.
"""
# Variables (No declaration needed, just assignment)
name = "Alice"
age = 30
is_student = True
height = 5.6
grades = [88, 92, 76] # A list
# Print to console
print("Hello, World!")
print(name, "is", age, "years old.")
print(f"{name} is {age} years old.") # f-string (recommended)
print("Name: {}, Age: {}".format(name, age)) # .format() method

Data Types

Type Description Example
int Integer 10, -5, 0
float Floating-point number 14, -0.001, 0
str String "hello", 'world'
bool Boolean True, False
list Mutable, ordered sequence [1, "a", 3.14]
tuple Immutable, ordered sequence (1, "a", 3.14)
dict Key-value pairs (hash map) {"key": "value", "name": "Bob"}
set Unordered collection of unique items {1, 2, 3}
NoneType Represents "no value" None

Operators

Arithmetic

+  # Addition
-  # Subtraction
*  # Multiplication
/  # Division (float result)
// # Floor Division (int result)
%  # Modulo (remainder)
** # Exponentiation

Comparison

== # Equal to
!= # Not equal to
>  # Greater than
<  # Less than
>= # Greater than or equal to
<= # Less than or equal to

Logical

and # Logical AND
or  # Logical OR
not # Logical NOT

Membership

Python速查表有哪些核心要点?-图2
(图片来源网络,侵删)
in      # Checks if a value is in a sequence (e.g., list, string)
not in  # Checks if a value is not in a sequence

Assignment

=   # a = 5
+=  # a += 5  (a = a + 5)
-=  # a -= 5  (a = a - 5)
*=  # a *= 5  (a = a * 5)
/=  # a /= 5  (a = a / 5)

Data Structures

Lists (Mutable)

my_list = [1, 2, "three", 4.0]
# Access elements
print(my_list[0])       # 1 (first element)
print(my_list[-1])      # 4.0 (last element)
print(my_list[1:3])     # [2, 'three'] (slicing)
# Modify elements
my_list[0] = 10
my_list.append(5)       # Add to the end
my_list.insert(1, 99)   # Insert at index 1
my_list.remove("three") # Remove first occurrence of value
popped_item = my_list.pop() # Remove and return last item
# Other methods
my_list.sort()          # Sorts in-place (modifies list)
new_list = sorted(my_list) # Returns a new sorted list
len(my_list)            # Get length

Tuples (Immutable)

my_tuple = (1, 2, "three")
another_tuple = 1, 2, 3 # Parentheses are optional
# Access elements (same as lists)
print(my_tuple[0]) # 1
# Cannot modify (will cause an error)
# my_tuple[0] = 10 # TypeError
# Useful for returning multiple values from a function
def get_coords():
    return 10, 20
x, y = get_coords()

Dictionaries (Key-Value Pairs)

Python速查表有哪些核心要点?-图3
(图片来源网络,侵删)
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
# Access values
print(my_dict["name"])        # "Alice"
print(my_dict.get("age"))     # 30 (safer, returns None if key doesn't exist)
print(my_dict.get("job", "N/A")) # "N/A" (default value)
# Modify and add key-value pairs
my_dict["age"] = 31
my_dict["job"] = "Engineer"
# Other methods
my_dict.keys()      # Returns a view of keys: dict_keys(['name', 'age', ...])
my_dict.values()    # Returns a view of values: dict_values(['Alice', 31, ...])
my_dict.items()     # Returns a view of items: dict_items([('name', 'Alice'), ('age', 31), ...])
len(my_dict)        # Get number of items

Sets (Unique, Unordered)

my_set = {1, 2, 3, 2, 1} # Duplicates are automatically removed
print(my_set) # {1, 2, 3}
# Add and remove elements
my_set.add(4)
my_set.remove(2) # Raises KeyError if element not present
my_set.discard(5) # Does nothing if element not present
# Set operations
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union = set_a | set_b        # {1, 2, 3, 4, 5}
intersection = set_a & set_b # {3}
difference = set_a - set_b   # {1, 2}

Control Flow

If/Elif/Else

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

For Loops

# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# Iterate with index using enumerate
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
# Iterate over a range
for i in range(5):      # 0, 1, 2, 3, 4
    print(i)
for i in range(2, 6):   # 2, 3, 4, 5
    print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (start, stop, step)
    print(i)

While Loops

count = 0
while count < 5:
    print(count)
    count += 1

Break and Continue

# Break: Exits the loop immediately
for i in range(10):
    if i == 5:
        break
    print(i) # Prints 0, 1, 2, 3, 4
# Continue: Skips the rest of the current iteration and goes to the next
for i in range(10):
    if i % 2 == 0:
        continue
    print(i) # Prints 1, 3, 5, 7, 9

Functions

# Basic function definition
def greet(name):
    """This function greets the person passed in as a parameter."""
    return f"Hello, {name}!"
# Call the function
message = greet("Charlie")
print(message)
# Function with default arguments
def power(base, exponent=2):
    return base ** exponent
print(power(3))      # 9 (3^2)
print(power(3, 3))   # 27 (3^3)
# Function with variable number of arguments (*args, **kwargs)
def sum_all(*args):      # *args collects positional arguments into a tuple
    return sum(args)
def print_info(**kwargs): # **kwargs collects keyword arguments into a dictionary
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print(sum_all(1, 2, 3, 4)) # 10
print_info(name="Dave", age=40, city="London")

Object-Oriented Programming (OOP)

class Dog:
    # Class attribute (shared by all instances)
    species = "Canis familiaris"
    # Constructor / Initializer
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age
    # Instance method
    def bark(self):
        return f"{self.name} says Woof!"
    # Another instance method
    def description(self):
        return f"{self.name} is {self.age} years old."
# Create an instance (object) of the Dog class
my_dog = Dog("Rex", 5)
# Access attributes
print(my_dog.name)          # Rex
print(my_dog.age)           # 5
print(my_dog.species)       # Canis familiaris
# Call methods
print(my_dog.bark())        # Rex says Woof!
print(my_dog.description()) # Rex is 5 years old.

File I/O

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

Common Built-in Functions

Function Description Example
len() Length of an object len([1, 2, 3]) -> 3
type() Type of an object type("hello") -> <class 'str'>
isinstance() Check if an object is an instance of a class isinstance(5, int) -> True
range() Generates a sequence of numbers list(range(5)) -> [0, 1, 2, 3, 4]
enumerate() Returns an enumerate object (index, value) list(enumerate(['a', 'b'])) -> [(0, 'a'), (1, 'b')]
zip() Aggregates elements from iterables list(zip([1, 2], ['a', 'b'])) -> [(1, 'a'), (2, 'b')]
sum() Sum of numbers in an iterable sum([1, 2, 3]) -> 6
max() / min() Maximum / Minimum value max([1, 5, 2]) -> 5
sorted() Returns a new sorted list sorted([3, 1, 2]) -> [1, 2, 3]
open() Opens a file open("file.txt", "r")
input() Reads a line from user input name = input("Enter your name: ")

Useful Modules & Libraries

# Importing a module
import math
import random
import datetime
import os
# Using functions from a module
print(math.pi)          # 3.14159...
print(math.sqrt(16))    # 4.0
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(['apple', 'banana', 'cherry'])) # Random element from a list
now = datetime.datetime.now()
print(now)             # Current date and time
print(now.strftime("%Y-%m-%d")) # Format date as YYYY-MM-DD
# Get current working directory
print(os.getcwd())
# List files in a directory
print(os.listdir('.'))
# Create a directory
# os.makedirs("new_folder")

List & Dictionary Comprehensions (Pythonic Way)

List Comprehension - Create a new list by iterating over an existing one.

# Standard way
squares = []
for i in range(10):
    squares.append(i**2)
# List comprehension
squares_comp = [i**2 for i in range(10)]
# With a condition
even_squares = [i**2 for i in range(10) if i % 2 == 0]

Dictionary Comprehension - Create a new dictionary.

# Standard way
word_lengths = {}
for word in ["apple", "banana", "cherry"]:
    word_lengths[word] = len(word)
# Dictionary comprehension
word_lengths_comp = {word: len(word) for word in ["apple", "banana", "cherry"]}

Error Handling

try:
    # Code that might cause an error
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except ValueError:
    # Handle errors where the input is not a valid integer
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    # Handle errors where division by zero occurs
    print("Cannot divide by zero.")
except Exception as e:
    # Handle any other unexpected errors
    print(f"An unexpected error occurred: {e}")
finally:
    # This block always executes, regardless of an error
    print("This block always runs.")
分享:
扫描分享到社交APP
上一篇
下一篇