πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English | πŸ‡ͺπŸ‡Έ EspaΓ±ol | πŸ‡΅πŸ‡Ή PortuguΓͺs | πŸ‡ΉπŸ‡­ ΰΉ„ΰΈ—ΰΈ’ | πŸ‡¨πŸ‡³ δΈ­ζ–‡

What is Python? A Beginner-Friendly Guide [Copy & Paste to Run]

"I want to start programming, but I don't know where to begin..."
"I hear a lot about Python, but what's so great about it?"

If this sounds like you, a budding web creator, you're in the right place. This article breaks down one of the most popular programming languages today, Python, from its basics to practical examples, all in a beginner-friendly way.

The main goal of this article is for you to experience the joy of running code. We'll set aside complex theories for later. For now, just copy, paste, and run the code snippets provided. Each piece of code is designed to work perfectly on its own. Let's take your first step into the world of Python!

Three Major Features of Python

There are clear reasons why developers worldwide love Python. Let's look at three of the most important features.

1. Simple and Readable Syntax

Python was designed with human readability in mind. Compared to other languages (like C++ or Java), it requires less code and can be understood intuitively, much like reading English. This lowers the learning curve, allowing beginners to master the basics in a relatively short time.

2. Extensive Libraries for a Wide Range of Tasks

Python's greatest strength is its vast collection of extensions called "libraries" and "frameworks." These are like toolboxes full of convenient functions created by developers around the globe.

Using these toolboxes, you can easily implement complex processes without having to write everything from scratch.

3. High Versatility, from Web Services to AI Development

Python is not a language specialized for one specific field. It's used on the backend (server-side) of global web services like YouTube, Instagram, and Dropbox, while also being the de facto standard in the fields of AI (Artificial Intelligence) and data science, from research to practical application. For web creators, it's incredibly useful for automating daily repetitive tasks and gathering information from websites.

Try It with Copy & Paste! Concrete Examples of What Python Can Do

Now, let's get our hands on some actual Python code!
All the following code snippets can be copied and run as-is. Your first goal is to experience the feeling of "it works."

The First Step: Displaying "Hello, World!"

As the first step in programming, let's display the text "Hello, World!" on the screen. The print() command is used to output whatever is inside the parentheses.

# Use print() to display a string
print("Hello, World!")

Get a Website's Title (Web Scraping)

As a web creator, you're likely interested in gathering information from websites. With Python, you can automatically retrieve information from a web page at a specified URL. Here, let's get the title of Google's homepage using only Python's standard features.

*Please run this code in an environment connected to the internet.

# Import necessary libraries
import urllib.request
import re

# URL for Google
url = "https://www.google.com"

try:
    # Open the URL and get the HTML
    with urllib.request.urlopen(url) as response:
        html = response.read().decode('utf-8')

        # Use regular expressions to extract the content of the title tag
        title_match = re.search(r'<title>(.*?)</title>', html)
        if title_match:
            print(f"Retrieved Title: {title_match.group(1)}")
        else:
            print("Title not found.")

except Exception as e:
    print(f"An error occurred: {e}")

Automate Simple Tasks (File Operations)

Manually creating sequentially numbered folders like "project-01," "project-02," etc., for managing website assets can be tedious. With Python, you can finish such simple tasks in an instant.

Running this code will automatically create 10 folders, from "image_01" to "image_10," in the same directory where the code is saved.

# Import the library for file and folder operations
import os

# Specify the location to create folders ('.' means the current folder)
base_path = '.'

# Loop through numbers 1 to 10
for i in range(1, 11):
    # Generate the folder name (e.g., image_01, image_02, ...)
    folder_name = f"image_{i:02d}"
    
    # Create the full path for the folder
    full_path = os.path.join(base_path, folder_name)
    
    # If the folder does not already exist, create it
    if not os.path.exists(full_path):
        os.makedirs(full_path)
        print(f"Created folder: '{full_path}'")
    else:
        print(f"Folder '{full_path}' already exists.")

Launch a Simple Web Server

When web creators check the display of HTML and CSS files they've created, JavaScript might not work correctly if they open the local files directly in the browser. With Python, you can launch a simple web server on your PC with just a few lines of code.

After running this code, try accessing http://localhost:8000 in your web browser. You will see a list of files in the folder where you ran the code. Clicking on an HTML file will display it correctly. (To stop the server, press Ctrl + C in the running terminal or command prompt).

# Import libraries for web server functionality
import http.server
import socketserver

# Specify the port number to run the server on
PORT = 8000

# Server configuration
Handler = http.server.SimpleHTTPRequestHandler

# Start the server
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Server started at port {PORT}")
    print(f"Open http://localhost:{PORT} in your browser.")
    # Run the server indefinitely
    httpd.serve_forever()

A Glimpse into Basic Python Syntax

Now that you've run some code by copying and pasting, have you started to feel the power of Python?
Here, we'll introduce some of the basic "rules" of Python that were used in the previous examples.

Variables: Boxes for Naming Data

A "variable" is a "named box" for storing data like numbers or strings. You can put data into a box (assign it) using the = sign.

# Assign a string to a variable named "message"
message = "Python is fun!"

# Display the content of the variable
print(message)

if Statements: Changing Actions Based on Conditions

The if statement allows you to implement conditional logic, like "if X is true, do action A; otherwise, do action B." This is the mechanism behind features like "display username for logged-in users, but show a login button for others" on a website.

age = 20

# If age is 20 or greater
if age >= 20:
    print("You are an adult.")
# Otherwise
else:
    print("You are a minor.")

for Loops: Performing Repetitive Tasks

Use a for loop when you want to repeat a task a set number of times or for each item in a collection of data. It was used in the folder creation example to repeat the action 10 times. Here, we'll display each item from a list (a collection of multiple data items).

# A list of web technologies
web_skills = ["HTML", "CSS", "JavaScript", "Python"]

# Iterate through the list, putting each item into the "skill" variable
for skill in web_skills:
    print(f"A skill I'm studying: {skill}")

Functions: Bundling and Naming a Block of Code

With "functions," you can group a series of operations and give them a name. If you need to perform the same task multiple times, you can define the function once and then just call its name. This is a crucial feature for organizing code and making it reusable.

# Define a function that greets someone
def greet(name):
    # Use an f-string to embed a variable within a string
    message = f"Hello, {name}!"
    return message

# Call the function and assign the result to "greeting_message"
greeting_message = greet("Yamada")

# Display the result
print(greeting_message)

# Call it again with a different name
print(greet("Suzuki"))

Two Important Points for Beginners to Watch Out For

When starting to learn Python, there are a few common stumbling blocks. Knowing these in advance will make your learning journey much smoother.

1. Indentation is Crucial!

In Python, indentation (the spaces at the beginning of a line) is part of the syntax. It's used to define blocks of code in structures like if statements and for loops. Unlike other languages that use symbols like {}, incorrect indentation will cause an error in Python.

This reflects Python's philosophy that code should look clean and be readable, no matter who writes it. The standard is to use four spaces for indentation.

Correct Indentation Example

# Correct example
name = "Taro"
if name == "Taro":
    # This line is indented with four spaces
    print("Hello, Taro!")

Incorrect Indentation Example

The following code will result in an IndentationError because the print line is not indented.

# Incorrect example (this will cause an error)
name = "Taro"
if name == "Taro":
# No indentation!
print("Hello, Taro!")

2. Don't Fear Error Messages! They Are Hints for a Solution

Errors are a part of programming. As a beginner, you might panic when you see a red error message, but there's no need to be afraid. An error message is your biggest hint, telling you "where" and "what" went wrong.

When you get an error, first try to read the message. If you don't understand it, copy the entire error message and search for it on Google. You'll often find a solution. Gaining experience by solving errors is the fastest way to improve.

Conclusion: Python Can Be Your Powerful Weapon

In this article, we've taken a quick tour of what kind of language Python is, what it can do, and how to write it.

By learning Python, you will undoubtedly expand your capabilities as a web creator. Automate tedious tasks to focus on creative work, add new features to your websites, or incorporate data analysis to improve your designs... the possibilities are endless.

Let today be your "Python Anniversary." Why not start by setting up a Python environment on your computer?

To the Next Step

If this article sparked your interest in Python, read the next article to get your computer ready to run Python!

Read the Article: Python Installation and Development Environment Setup