杰瑞科技汇

Python核心知识点有哪些?

Of course! Here is a comprehensive guide to Python essentials, structured from the absolute basics to the core concepts you need to write effective and efficient Python code.

Python核心知识点有哪些?-图1
(图片来源网络,侵删)

Part 1: The Absolute Basics

What is Python?

Python is a high-level, interpreted, general-purpose programming language. It's famous for its simple, readable syntax, which makes it a fantastic language for beginners and a powerful tool for experts.

  • High-level: It abstracts away complex details of the computer (like memory management).
  • Interpreted: Code is executed line by line by an interpreter, making it easy to test and debug.
  • General-purpose: You can use it for web development, data science, automation, artificial intelligence, and more.

Your First Program: "Hello, World!"

The tradition is to start with a program that prints "Hello, World!" to the console.

# This is a comment. The interpreter ignores it.
print("Hello, World!")

To run this, save it in a file named hello.py and run it from your terminal: python hello.py

Variables and Data Types

Variables are containers for storing data values. In Python, you don't need to declare the type of a variable; it's inferred automatically.

Python核心知识点有哪些?-图2
(图片来源网络,侵删)

Basic Data Types:

Type Name Example Description
int Integer age = 25 Whole numbers
float Floating-point price = 19.99 Numbers with a decimal point
str String name = "Alice" Sequence of characters. Can use single or double quotes.
bool Boolean is_student = True Represents one of two values: True or False
# Variable assignment
name = "Bob"
age = 30
height = 5.9
is_learning = True
# You can see the type of a variable with the type() function
print(type(name))      # <class 'str'>
print(type(age))       # <class 'int'>

Basic Operators

Operators are used to perform operations on variables and values.

  • Arithmetic: , , , , (modulo, gives the remainder), (exponent)
  • Comparison: (equal to), (not equal to), >, <, >=, <=
  • Logical: and, or, not
x = 10
y = 3
print(x + y)   # 13
print(x / y)   # 3.333...
print(x % y)   # 1 (remainder of 10 / 3)
print(x == y)  # False
print(x > 5 and y < 5) # True

Part 2: Core Data Structures

These are the fundamental building blocks for organizing your data.

Lists

A list is an ordered, mutable (changeable) collection of items. It's defined using square brackets [].

# Create a list
fruits = ["apple", "banana", "cherry"]
# Access items by index (starts at 0)
print(fruits[0])  # "apple"
print(fruits[-1]) # "cherry" (negative index counts from the end)
# Change an item
fruits[1] = "blueberry"
# Add an item to the end
fruits.append("orange")
# Remove an item
fruits.remove("apple")
# Get the number of items
print(len(fruits)) # 3

Dictionaries

A dictionary is an unordered, mutable collection of key-value pairs. It's defined using curly braces .

# Create a dictionary
person = {
    "name": "Charlie",
    "age": 35,
    "city": "New York"
}
# Access a value by its key
print(person["name"]) # "Charlie"
# Add or change a key-value pair
person["job"] = "Engineer"
person["age"] = 36
# Remove a key-value pair
del person["city"]
# Check if a key exists
if "name" in person:
    print("Name is:", person["name"])

Tuples

A tuple is an ordered, immutable (unchangeable) collection. It's defined using parentheses .

# Create a tuple
coordinates = (10.0, 20.0)
# Access items by index
print(coordinates[0]) # 10.0
# You cannot change a tuple
# coordinates[0] = 5.0 # This will cause an error!
# Tuples are useful for data that should not change, like coordinates or RGB colors.

Sets

A set is an unordered, mutable collection of unique items. It's defined using curly braces or the set() function.

# Create a set
unique_numbers = {1, 2, 3, 2, 1, 4}
print(unique_numbers) # {1, 2, 3, 4} (duplicates are removed)
# Add an item
unique_numbers.add(5)
# Remove an item
unique_numbers.remove(2)
# Check for membership
print(3 in unique_numbers) # True

Part 3: Control Flow

Control flow allows you to run code conditionally and repeatedly.

Conditional Statements (if, elif, else)

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

Loops

for loop: Used to iterate over a sequence (like a list, tuple, dictionary, or string).

# Iterate over a list
colors = ["red", "green", "blue"]
for color in colors:
    print(color)
# Iterate using range() for a specific number of times
for i in range(5): # Prints 0, 1, 2, 3, 4
    print(i)

while loop: Repeats a block of code as long as a condition is true.

count = 0
while count < 5:
    print("Count is:", count)
    count += 1 # Don't forget to update the condition!

Part 4: Functions

Functions are reusable blocks of code that perform a specific task. They help you organize your code and avoid repetition.

# Define a function
def greet(name, greeting="Hello"): # 'greeting' is a default parameter
    """This function greets the person passed in as a parameter."""
    return f"{greeting}, {name}!"
# Call the function
message = greet("David")
print(message) # "Hello, David!"
message_custom = greet("Eve", greeting="Hi")
print(message_custom) # "Hi, Eve!"

Key Concepts:

  • def: Keyword to define a function.
  • Parameters: The variables listed inside the parentheses .
  • return: The keyword that sends a value back from the function. If you don't use return, the function returns None.

Part 5: Working with Files

Python makes it easy to read from and write to files. The standard way is using the with statement, which automatically closes the file for you.

Writing to a file:

# 'w' mode means "write". It will create the file or overwrite it.
with open("my_file.txt", "w") as f:
    f.write("Hello from Python!\n")
    f.write("This is the second line.")

Reading from a file:

# 'r' mode means "read" (this is the default mode).
with open("my_file.txt", "r") as f:
    content = f.read() # Reads the entire file into a single string
    print(content)
    # Or read line by line
    f.seek(0) # Go back to the beginning of the file
    first_line = f.readline()
    print(f"First line: {first_line.strip()}") # .strip() removes whitespace

Part 6: Essential Modules and Libraries

Python's power comes from its vast ecosystem of libraries. You import them using the import keyword.

  • os: For interacting with the operating system (e.g., file paths, environment variables).
  • math: For mathematical functions.
  • datetime: For working with dates and times.
  • json: For working with JSON data.
import math
import datetime
# Use functions from the math module
print(math.sqrt(16)) # 4.0
print(math.pi)
# Use functions from the datetime module
now = datetime.datetime.now()
print(f"Current time: {now}")

Part 7: Pythonic Style (PEP 8)

Writing "Pythonic" code means writing code that is not just functional, but also clean, readable, and elegant. The style guide for this is PEP 8.

  • Indentation: Use 4 spaces for indentation. Never use tabs.
  • Naming Conventions:
    • snake_case for variables, functions, and method names (my_variable, calculate_sum).
    • PascalCase for class names (MyClass).
    • UPPER_CASE for constants (MAX_SIZE).
  • Whitespace: Use a single space around operators and after commas.
  • Comments: Use comments to explain why you are doing something, not what you are doing. The code itself should explain the "what".

Putting It All Together: A Mini-Project

Let's create a simple program that manages a to-do list.

# A simple To-Do List Manager
todo_list = []
def add_task(task):
    """Adds a new task to the to-do list."""
    todo_list.append(task)
    print(f"Task '{task}' added.")
def view_tasks():
    """Displays all tasks in the to-do list."""
    if not todo_list:
        print("Your to-do list is empty.")
    else:
        print("\n--- To-Do List ---")
        for i, task in enumerate(todo_list): # enumerate gives us index and item
            print(f"{i + 1}. {task}")
        print("------------------")
def remove_task(index):
    """Removes a task by its index."""
    if 1 <= index <= len(todo_list):
        removed_task = todo_list.pop(index - 1)
        print(f"Task '{removed_task}' removed.")
    else:
        print("Invalid task number.")
# Main program loop
while True:
    print("\nWhat would you like to do?")
    print("1. Add a task")
    print("2. View tasks")
    print("3. Remove a task")
    print("4. Exit")
    choice = input("Enter your choice (1-4): ")
    if choice == '1':
        task = input("Enter the task: ")
        add_task(task)
    elif choice == '2':
        view_tasks()
    elif choice == '3':
        view_tasks()
        try:
            task_num = int(input("Enter the number of the task to remove: "))
            remove_task(task_num)
        except ValueError:
            print("Please enter a valid number.")
    elif choice == '4':
        print("Goodbye!")
        break
    else:
        print("Invalid choice. Please try again.")

This mini-project uses lists, functions, loops, conditionals, and user input (input()), tying together many of the essential concepts discussed.

分享:
扫描分享到社交APP
上一篇
下一篇