Beginner’s Guide to Learning Python (Detailed Version)
Hello everyone, I am Cat Brother, a Python enthusiast who loves coding and teaching coding. This article is specially written for complete beginners who want to get started with Python. Don’t be afraid, I was once a newbie who couldn’t even pronounce the word “variable” correctly. Follow Cat Brother’s pace, set up the environment in an hour, write your first program, and run your first game, and feel the sense of achievement! This article is conversational, with copyable code, relatable metaphors, and common pitfalls highlighted, making it easy for you to take your first step into Python.
1. Let’s first describe Python: What can it do?
Python = Universal Glue:
- • Build websites (used in the backend of Douyin)
- • Perform data analysis (pandas, Excel killer)
- • Artificial intelligence (default language for TensorFlow, PyTorch)
- • Automation scripts (batch rename files, scrape tables)
In a nutshell: Learning Python is like installing a “Chinese voice assistant” on your computer, letting it help you work!
2. Installing Python: Done in 3 minutes, as easy as installing WeChat
- 1. Open the official website https://www.python.org
- 2. Click Download Python 3.x.x (≥3.8 is fine, don’t download 2.x!)
- 3. On the installation page, be sure to check Add Python to PATH, otherwise subsequent commands won’t be found.
- 4. Done! Open the command line (Win key + R → type cmd):
python --version
# If you see Python 3.x.x, you are successful!
Cat Brother’s Tip: For 64-bit systems, choose “Windows x86-64 executable installer”, don’t choose zip, to avoid configuring environment variables yourself.
3. Writing Your First Line of Code: Say hi to the world
Open the built-in Notepad, type:
print("Hello, Python!")
Save it as <span>first.py</span>, make sure to change the suffix to .py, then in the command line:
cd folder_where_file_is
python first.py
Screen output:
Hello, Python!
Congratulations, your first Python code has run successfully!🎉
4. Understanding Variables: Labeling Data
A variable is like a labeled box, you put things in before taking them out:
name = "Cat Brother" # String type str
age = 18 # Integer type int
height = 1.75 # Float type float
print(name, age, height)
Output:
Cat Brother 18 1.75
Tips:
- • Variable names can only contain letters/numbers/underscores, cannot start with a number (
<span>2b</span>is not allowed) - • Case sensitivity,
<span>Age ≠ age</span>
5. The Three Musketeers of Data Types: str, int, float + bool
Use <span>type()</span> to check types:
print(type("666")) # <class 'str'>
print(type(666)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(5 > 3)) # <class 'bool'> Result True
Conversion:
a = int("123") # String → Integer
b = str(123) # Integer → String
Cat Brother’s Analogy: Types are like cups, bowls, and wine glasses, using a wine glass for cola is not impossible, but it can spill— try to use the right container.
6. Input and Output: Programs Need Interaction Too
name = input("Please enter your nickname:")
print("Welcome,", name)
Running example:
Please enter your nickname: Little White
Welcome, Little White
Note: <span>input</span> always returns a string, if you want to do mathematical operations, you need to convert the type:
num = int(input("Please enter an integer:"))
print("Square is", num ** 2)
7. Conditional Statements: Letting Programs “Turn”
Syntax:
if condition:
action1
else:
action2
Example—Guess the Age:
age = int(input("Guess Cat Brother's age:"))
if age == 18:
print("Correct! Here’s a red envelope~")
else:
print("Wrong guess, Cat Brother is always 18!")
Indentation is the soul of Python, use 4 spaces consistently, don’t mix with Tab!
8. Loops: Letting Machines Handle Repetition
1. while Loop
count = 1
while count <= 5:
print("Check-in number", count)
count += 1
2. for Loop (with range)
for i in range(1, 6): # 1~5
print("Check-in number", i)
Range Tips:
- •
<span>range(5)</span>→ 0~4 - •
<span>range(1,6)</span>→ 1~5 - •
<span>range(1,10,2)</span>→ step 2, results in 1 3 5 7 9
9. Lists: The “Universal Shopping Cart” in Python
cart = ["Apple", "Milk", "Coffee"]
cart.append("Bread") # Append
cart.insert(1, "Banana") # Insert
print(cart[2]) # Get index 2
print("Length:", len(cart))
Negative Indexing:
print(cart[-1]) # Last element
Iteration:
for item in cart:
print("Buy", item)
10. Functions: Encapsulating Code for Reuse
def add(a, b):
"""Returns the sum of two numbers"""
return a + b
result = add(3, 5)
print("3+5=", result)
Cat Brother’s Mnemonic: Define before calling, <span>def</span> don’t forget the colon, return is not mandatory, if there’s no return, it defaults to <span>None</span>.
11. The Three Musketeers of Strings: Concatenation, Formatting, Slicing
name = "Python"
print("Hello " + name) # Concatenation
print(f"Hello {name}") # f-string formatting (3.6+)
print(name[0:3]) # Slicing, half-open interval → Pyt
Exercise: Write a function <span>say_hi(name)</span><span>, returning "</span><code><span>Hello, {name}!</span>“, and print it.
12. Dictionaries: Giving Data a “Chinese Name”
score = {"Chinese": 90, "Math": 95, "English": 88}
print(score["Math"]) # 95
score["Math"] = 100 # Modify
score["Physics"] = 92 # Add
for k, v in score.items():
print(k, v)
13. Exception Handling: Preventing Program “Crashes”
try:
x = int(input("Please enter the divisor:"))
print("10/x=", 10 / x)
except ZeroDivisionError:
print("Divisor cannot be 0!")
except ValueError:
print("Must enter an integer!")
Cat Brother’s Experience: First, let the program run, then let it fail gracefully— exception handling is like a fuse.
14. File Operations: Permanently Saving Data
# Write file
with open("poem.txt", "w", encoding="utf-8") as f:
f.write("Hello Python\nHello World")
# Read file
with open("poem.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
The with statement will automatically close the file, never forget to close after using <span>f=open()</span>, or the file will be locked and Cat Brother won’t be responsible~
15. Modules: The Philosophy of Borrowing, Standing on the Shoulders of Giants
The Python standard library is a “treasure chest”:
import random
num = random.randint(1, 10) # Random integer from 1 to 10
print("Lucky number:", num)
Exercise: Write a number guessing game—program randomly selects a number from 1 to 100, user inputs a guess, and the program hints if it’s too high/low until guessed correctly.
16. List Comprehensions: Generating Lists in One Line
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Equivalent to:
squares = []
for x in range(1, 6):
squares.append(x ** 2)
Cat Brother’s Reminder: Comprehensions are cool, but don’t write them too long, as it affects readability.
17. Common Learning Paths & Resources
- 1. Learn by doing: 30 minutes a day, is more effective than cramming 5 hours in a week
- 2. Practice websites:
- • LeetCode—Algorithms
- • Niuke.com—Interviews
- • Hackerrank—Syntax
18. Top 5 Common Errors (Cat Brother helps you avoid pitfalls)
| Error Message | Cause | Quick Fix |
|---|---|---|
<span>SyntaxError: invalid syntax</span> |
Missing colon/using Chinese punctuation | Check<span>if</span> and <span>def</span> lines for English colons |
<span>IndentationError</span> |
Inconsistent indentation | Use 4 spaces consistently, don’t mix with Tab |
<span>TypeError: can only concatenate str</span> |
Trying to concatenate str + int | First<span>str(num)</span> |
<span>NameError: name 'x' is not defined</span> |
Variable not defined | Check spelling/whether it was assigned first |
<span>ModuleNotFoundError: No module named 'xxx'</span> |
Third-party library not installed | <span>pip install xxx</span> |
19. Summary: What did you gain today?
- • ✅ Installed Python and ran the first line of code
- • ✅ Variables, data types, input and output
- • ✅ Conditions, loops, lists, dictionaries, functions, exceptions, files
- • ✅ Know what to learn next and where the pitfalls are
Cat Brother’s Mnemonic: First imitate → then modify → finally write yourself, don’t rush to be original, copying code is also a way to learn!

Friends, today’s Python learning journey ends here! Remember to code, and feel free to ask Cat Brother in the comments if you have any questions. Wishing everyone a happy learning experience, and may your Python skills improve steadily!