I. What Is Hello World
Hello World is the most classic beginner program in programming study. It is usually used to verify that the development environment is working properly and to become familiar with the most basic way of writing and executing code in a programming language.
In Python, the simplest Hello World program is just one line of code:
print("Hello, World!")
Output:
Hello, World!
Simple as this code is, it contains several foundational concepts in Python programming:
print(): Python's built-in output function."Hello, World!": a string literal.(): the parentheses used for a function call.": the quotation marks that delimit a string.!: an ordinary character inside the string.- The line break: one of the ways statements are separated in Python source code.
Through this program, you can build a complete picture of the path from writing source code to seeing the result of running it.
II. Writing Your First Python Program
1. Confirm the Python Environment
Before writing a program, you need to make sure the Python interpreter is installed on your computer.
Open a terminal or command line and run:
python --version
If your system uses the python3 command, run:
python3 --version
Windows users can also use:
py --version
If the output looks something like:
Python 3.14.0
that means the current command can find the Python interpreter.
If you get a message saying the command does not exist, you need to check whether Python is installed and whether the interpreter's path has been added to the PATH environment variable.
2. Create a Python File
Python programs are usually saved in files with the .py extension.
For example, create a file:
hello.py
You can write the code in VS Code, PyCharm, Notepad, or another text editor.
Enter the following in hello.py:
print("Hello, World!")
Save the file.
Things to note:
- The file extension should be
.py. - The file contents should be saved as plain-text source code.
- UTF-8 encoding is recommended.
- Try to avoid file names that clash with Python standard library modules, such as
string.py,json.py, orrandom.py.
3. Run the Python File
Change into the directory where hello.py is located and run the following in the terminal:
python hello.py
If your system uses the python3 command:
python3 hello.py
On Windows you can also use:
py hello.py
After the program runs, the terminal displays:
Hello, World!
At this point, your first Python program has run successfully.
4. The Complete Execution Process
Going from creating the file to seeing the output involves several steps:
flowchart TD
A["Create hello.py file"] --> B["Write Python source code"]
B --> C["Save file"]
C --> D["Start Python interpreter"]
D --> E["Read and parse source code"]
E --> F["Execute program"]
F --> G["Call the print function"]
G --> H["Write content to standard output"]
H --> I["Terminal displays Hello, World!"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
A key point to understand here: print() is not special syntax that directly controls the terminal interface; it is a built-in function provided by Python. It typically writes content to the standard output stream, and the terminal or another runtime environment then displays it.
III. Understanding the Hello World Code Line by Line
Although the program is only one line, it can be understood from multiple angles.
print("Hello, World!")
1. print: Built-in Output Function
print() is a Python built-in function used to convert a specified object into a text representation and write it to the output stream.
Its most common use is to output information to the terminal.
For example:
print("Hello")
print("Python")
print(123)
Output:
Hello
Python
123
Here you can output strings as well as numbers.
print() does not need to be imported in advance because it is a Python built-in function.
You can inspect it with the following code:
print(print)
You can also use:
help(print)
to view the function's help documentation.
2. String: Hello, World!
A string is a text data type composed of characters.
Python uses single quotes, double quotes, or triple quotes to represent strings.
For example:
print("Hello, World!")
print('Hello, Python!')
print("""Hello,
Python!""")
Output:
Hello, World!
Hello, Python!
Hello,
Python!
Both single quotes and double quotes can create ordinary strings.
Triple quotes are suitable for representing multiline strings and are also often used to write docstrings.
3. Function Calls: The Role of Parentheses
In Python, function calls usually use parentheses.
print("Hello, World!")
It can be broken down as follows:
print: the function name.(): the syntax for calling a function."Hello, World!": the argument passed to the function.
The basic form of a function call:
函数名(参数)
For example:
len("Python")
len() is used to obtain the length of an object, and the result is:
6
Another example:
abs(-10)
Returns:
10
These are all basic forms of calling Python built-in functions.
4. The Role of String Quotes
Python uses quotes to mark the start and end positions of a string.
For example:
print("Hello")
Quotation marks are part of string syntax and are not output as string content.
If you want a string to contain quotation marks, you can use different types of quotation marks:
print("I'm learning Python")
print('He said "Hello"')
You can also use escape characters:
print("He said \"Hello\"")
Output:
I'm learning Python
He said "Hello"
He said "Hello"
5. Punctuation Is Also String Content
In the following code:
print("Hello, World!")
The comma and exclamation mark are both ordinary characters in the string.
They do not change the execution logic of the Python program.
For example:
print("Hello")
print("Hello!")
print("Hello, Python.")
The outputs are, respectively:
Hello
Hello!
Hello, Python.
This shows that the content in a string is determined by the programmer; Python does not automatically modify the text.
IV. Basic Usage of the print() Function
Understanding print() is an important step in writing your first program.
In addition to outputting fixed strings, it can also output variables, multiple objects, and calculation results.
1. Outputting Strings
print("Hello, World!")
print("Welcome to Python")
Output:
Hello, World!
Welcome to Python
2. Outputting Numbers
print(100)
print(3.14)
print(-20)
Output:
100
3.14
-20
Numbers do not require quotation marks.
If you write:
print("100")
Although the output is also:
100
However, the data types of the two are different:
print(type(100))
print(type("100"))
Output:
<class 'int'>
<class 'str'>
The former is an integer, and the latter is a string.
3. Outputting Variables
Variables can store data, and the corresponding value can later be accessed through the variable name.
name = "Python"
version = 3
print(name)
print(version)
Output:
Python
3
Here:
namestores the string"Python".versionstores the integer3.print()reads the object currently bound to the variable and outputs it.
4. Outputting Multiple Items at Once
print() can accept multiple positional arguments, separated by spaces by default.
print("Hello", "Python")
print("My age is", 18)
Output:
Hello Python
My age is 18
For example:
name = "Alice"
age = 20
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 20
5. Using sep to Change the Separator
The sep parameter specifies the separator between multiple output objects.
Its default value is a single space.
print("2026", "11", "26")
Output:
2026 11 26
Changing the separator:
print("2026", "11", "26", sep="-")
Output:
2026-11-26
You can also use other separators:
print("Python", "Java", "Go", sep=" | ")
Output:
Python | Java | Go
6. Using end to Change the Ending
The end parameter specifies what is output when a single print() call ends.
The default value is the newline character \n.
print("Hello")
print("Python")
Output:
Hello
Python
If you change end:
print("Hello", end=" ")
print("Python")
Output:
Hello Python
You can also avoid a line break:
print("1", end="")
print("2", end="")
print("3")
Output:
123
7. Common Parameters of print()
The common function signature of print() is as follows:
print(*objects, sep=' ', end='\n', file=None, flush=False)
The meaning of each parameter:
| Parameter | Purpose | Default Value |
|---|---|---|
*objects |
One or more objects to output | None |
sep |
Separator between multiple objects | Space |
end |
Content appended after output ends | Newline character |
file |
Specifies the output target | None, indicating standard output |
flush |
Whether to flush the output stream immediately | False |
For example, to specify output to a file:
with open("hello.txt", "w", encoding="utf-8") as file:
print("Hello, World!", file=file)
After execution, the content will be written to hello.txt.
flush=True can request immediate flushing of the output stream, which is suitable for some scenarios that require timely display of progress information.
V. Several Ways to Run a Python Program
Hello World can be run not only through a .py file, but also in different environments.
1. Run via a Python Script
This is the most common way.
Create a file:
hello.py
Write the code:
print("Hello, World!")
Run:
python hello.py
This is suitable for formally writing programs, saving code, and running tasks repeatedly.
2. Run via the Python REPL
Enter the following in the terminal:
python
After entering the interactive environment, enter the following directly:
>>> print("Hello, World!")
Hello, World!
This method does not require creating a file and is suitable for quickly verifying code.
3. Run via Python -c
Python supports using the -c parameter to directly execute a command string.
python -c "print('Hello, World!')"
Output:
Hello, World!
This method is suitable for:
- Quickly execute a single line of code.
- Write simple automation commands.
- Call Python from a shell script.
- Verify that the interpreter is working properly.
4. Running via an IDE
In VS Code or PyCharm, you can open hello.py and start the program with the Run button.
The IDE usually invokes the currently configured Python interpreter to execute the code.
Note that the interpreter selected in the IDE may differ from the default interpreter in the system terminal.
Therefore, when a program behaves differently in the terminal and in the IDE, you should check the interpreter paths used on both sides.
5. Running via Jupyter Notebook
Enter the following in a Notebook code cell:
print("Hello, World!")
Run the current cell, and you will see the output.
Jupyter is suitable for interactive learning, data analysis, and experimentation, but its execution mechanism differs from that of a regular .py script.
VI. The Internal Process of a Python Program from Writing to Execution
Running Hello World appears to require only one command, but internally the interpreter actually completes several steps.
1. Reading Source Code
When you execute:
python hello.py
The Python interpreter locates and reads the source code file according to the specified path.
Source code is usually saved in UTF-8 encoding.
2. Lexical Analysis and Syntax Analysis
The interpreter parses the source code.
For example:
print("Hello, World!")
it is recognized as a function call expression.
During parsing, the interpreter needs to identify:
- The function name.
- The left and right parentheses.
- The string literal.
- The expression structure.
If the code does not conform to the grammar rules, a syntax error will occur.
3. Generating an Internal Representation
Taking CPython as an example, source code is usually first parsed into an abstract syntax tree (AST) and then compiled into bytecode.
You can use the ast module in the standard library to view the syntax tree:
import ast
source = 'print("Hello, World!")'
tree = ast.parse(source)
print(ast.dump(tree, indent=4))
This helps you understand how Python code is represented internally.
4. Executing Bytecode
CPython executes the compiled bytecode through the Python virtual machine.
You can use the dis module to view the bytecode:
import dis
def hello():
print("Hello, World!")
dis.dis(hello)
The output will show the bytecode instructions corresponding to the function.
The specific instructions vary with the Python version, so you should not treat the bytecode result from one version as a fixed rule for all Python implementations.
5. Calling print and Outputting Content
When the program reaches print(), it calls Python's built-in output function.
By default, print() writes text to the standard output stream sys.stdout.
You can inspect the standard output object:
import sys
print(sys.stdout)
When running a regular script in the terminal, standard output is usually connected to the current terminal.