杰瑞科技汇

Learn Python the Hard Way真的学得会吗?

Of course. "Learn Python the Hard Way" is a famous book by Zed A. Shaw. The title is a bit of a misnomer; it's not about making things difficult for you. It's about learning by doing, repetition, and building a strong foundation through disciplined practice.

The core philosophy is:

  1. Don't Copy-Paste: Type every single character out yourself. This builds muscle memory.
  2. Read the Code: After typing it, read it carefully to understand what each part does.
  3. Find the Mistakes: If it doesn't work, you have to find the error. This is the most critical skill for a programmer.
  4. Break the Code: Once it works, intentionally break it to see what happens. This solidifies your understanding.

Let's go through the core concepts from the book, structured as a practical guide. We'll use Python 3, as it's the modern standard.

Learn Python the Hard Way真的学得会吗?-图1


The "Hard Way" Mindset: Your First Rule

Before you write a single line of code, you must accept this rule:

You must type every single exercise out. Do not copy and paste.

Your fingers need to learn the syntax, and your brain needs to engage with the code as you type it. This is non-negotiable for the "Hard Way" method.


Part 1: The Setup (Exercise 0)

You can't learn to code without a code editor and a way to run your code.

  1. Get a Code Editor: Don't use Notepad or TextEdit. They are terrible for coding. Get a real editor.

    • VS Code (Visual Studio Code): Free, powerful, and the industry standard. It has excellent built-in support for Python.
    • PyCharm: A fantastic IDE (Integrated Development Environment) specifically for Python. The Community Edition is free.
    • Sublime Text: A lightweight, fast, and beautiful editor.
  2. Install Python: If you're on Windows or macOS, download Python from the official website: python.org. Make sure to check the box that says "Add Python to PATH" during installation on Windows.

  3. Verify Your Installation: Open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and type:

    Learn Python the Hard Way真的学得会吗?-图2

    python3 --version

    You should see the version number you installed (e.g., Python 3.11.4). If python3 doesn't work, try just python.


Part 2: The First Steps (Exercises 1-4)

This is about getting comfortable with the basics.

Exercise 1: A First Program

The goal is to get your program to print something to the screen.

# ex1.py
print("Hello World!")

Your Task:

  1. Open your code editor.
  2. Type the code above exactly.
  3. Save the file as ex1.py in a new folder for your exercises.
  4. Open your terminal, navigate to that folder, and run the file with:
    python3 ex1.py
  5. You should see Hello World! printed in your terminal.

Exercise 2: Comments and Pound Characters

Comments are notes for humans. Python ignores them. The starts a comment.

# ex2.py
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print("This won't run.")
print("This will run.")

Your Task: Type this out, run it, and observe how the comments are ignored.

Exercise 3: Numbers and Math

Python can do basic math. Pay attention to the symbols.

Learn Python the Hard Way真的学得会吗?-图3

Operator Name Example
Addition 2 + 2
Subtraction 5 - 3
Multiplication 3 * 4
Division 10 / 2
Modulo (Remainder) 10 % 3
< Less Than 5 < 10
> Greater Than 5 > 10
<= Less Than or Equal 5 <= 5
>= Greater Than or Equal 5 >= 5
Equal To 5 == 5
Not Equal To 5 != 5
# ex3.py
print("I will now count my chickens:")
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)

Your Task: Type this out. Before running it, try to predict the output for each print statement. Then run it and see if you were right. If not, figure out why.


Part 3: Variables and Code Structure (Exercises 5-10)

This is where you start storing information.

Exercise 5: Variables and Names

A variable is like a labeled box where you can store data. You give it a name and assign it a value using the sign.

# ex5.py
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on the coffee.")
# This line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

Key Concept: The f before the string (f"...") is an f-string. It's a modern and easy way to embed variables directly inside a string. Just put the variable name in curly braces .

Exercise 6: Strings and Text

Strings are just sequences of text. You can put them in single () or double () quotes.

# ex6.py
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
w = "This is the left side of..."
e = "a string with a right side."
print(w + e)

Key Concept: The .format() method is another way to put variables in a string (older than f-strings, but good to know). Also, notice that you can "add" strings together with to concatenate them.


Part 4: Logic and Flow Control (Exercises 27-33)

This is where your code starts making decisions.

if, elif, else Statements

This is the core of logic. It lets your program run different code based on whether a condition is True or False.

# ex27.py
people = 20
cats = 30
dogs = 15
if people < cats:
    print("Too many cats! The world is doomed.")
if people > cats:
    print("Not many cats! The world is saved.")
if people < dogs:
    print("The world is drooled on!")
if people > dogs:
    print("The world is dry!")
dogs += 5 # This is shorthand for dogs = dogs + 5
if

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