title: Python basics: command line mode and interactive mode description: Python basic introductory tutorial: command line mode and interactive mode

Python basics: command line mode and interactive mode

Welcome to your first stop for getting started with Python! Before writing complex programs, we need to be familiar with Python's two basic running modes: command line mode and interactive mode. Master them, and your subsequent learning path will be more stable and confident.

Command line mode (terminal)

The command line mode is like a direct phone call between us and the operating system - you enter the command and the system executes it immediately. Whether you are managing files, running programs, or executing Python scripts, you can't do without it.

Enter command line mode (Windows)

On Windows systems, there are several ways to quickly enter the command line environment:

  • Windows Terminal (recommended): PressWin + R,enterwtPress Enter to experience the modern terminal interface.
  • Quick Menu: UseWin + XShortcut key, select "Terminal" or "Command Prompt".

After opening, you will see a prompt similar to this:

PS C:\Users\yourname>

This line represents the directory you are currently in, and the blinking cursor is waiting for your command.

Python interactive mode

Interactive mode is an instant feedback environment provided by Python, which is very suitable for testing a piece of code and verifying an idea. When you enter a line of statements, Python will immediately give the result. This "question and answer" approach is very helpful for learning grammar and quick experiments.

Enter interactive mode

At the command line, enterpythonorpython3(Varies according to system configuration):

PS C:\Users\yourname> python
Python 3.11.4 (main, Jun  6 2023, 10:49:05) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

when you see>>>prompt, congratulations, you have entered Python's interactive mode!

Exit interactive mode

When you want to leave interactive mode, there are two common ways:

  • inputexit()and press Enter.
  • Use shortcut keys: Windows pressCtrl + ZThen press Enter; macOS/Linux pressCtrl + D

##Write your first Python program

Now let us use the simplest code to experience the fun of Python.

Perform operations in interactive mode

In interactive mode, Python is your advanced calculator. Enter an expression and get the answer instantly:

>>> 100 + 200
300
>>> 2 ** 10  # 计算 2 的 10 次方
1024
TIP

#What follows are comments and Python will ignore them. Comments are "narration" written for humans to help understand the code.

Use print() to output content

Want to display text on the screen? useprint()function:

>>> print('hello, world')  # 单引号
hello, world
>>> print("hello, world")  # 双引号
hello, world
WARNING

Strings must use pairs of quotes, not single quotes and double quotes. For example'hello"It will confuse Python.

Run Python script file

Interactive mode is great for exploration and testing, but when your program gets longer, you definitely want to save the code. At this time it’s time for script mode to appear: write the code.pyfile and run it all at once.

Create Python file

  1. Open your favorite text editor (VS Code, Notepad++, etc.) and create a new file.
  2. Input content:
print('Hello, World!')
  1. Save the file ashello.py

Run script file

Switch to the directory where the file is located on the command line and execute:

PS C:\path\to\file> python hello.py
Hello, World!

You have successfully run your first Python script!

FAQ: File not found

If an error is reported:

python: can't open file 'hello.py': [Errno 2] No such file or directory

Explanation Python cannot find your file. Usually it's because the current directory is incorrect.

Solution:

  • usecdCommand to switch to the correct directory:
PS C:\> cd Users\yourname\projects
PS C:\Users\yourname\projects> python hello.py
  • When you need to switch the drive letter (Windows only), directly enter the drive letter and colon:
PS C:\> D:
PS D:\> cd work
PS D:\work> python hello.py

The difference between interactive mode and script mode

These two modes are like different tools, which are most efficient when used in the scene:

FeaturesInteractive ModeScript Mode
Execution methodEnter line by line and execute immediatelyRun all codes at once
OutputAutomatically display expression resultsRequiredprint()to see the output
Applicable scenariosDebugging, learning grammar, quick testingOfficially running the program, saving the code

A simple comparison can tell the difference:

Interactive mode: Enter the expression and see the result directly.

>>> 100 + 200 + 300
600

Script Mode (assuming filecalc.pyOnly one line was written in100 + 200 + 300):

# 这样运行后不会有任何输出!
100 + 200 + 300

# 必须显式使用 print()
print(100 + 200 + 300)

Common errors and solutions

It is normal to encounter errors when you first learn. Don't worry, understanding error messages is half the battle.

1. SyntaxError (SyntaxError)

Usually it's because you typed a symbol that Python doesn't recognize.

Typical error: Mixing in Chinese punctuation

>>> print'hello'# 使用了中文括号
  File "<stdin>", line 1
    print'hello'
          ^
SyntaxError: invalid character '(' (U+FF08)

Workaround: Make sure all punctuation (parentheses, quotes, commas, etc.) use English half-width symbols.

2. IndentationError (IndentationError)

Python uses indentation to distinguish code blocks, so it is very sensitive to spaces and tabs.

>>> if True:
... print('hello')  # 缺少缩进
  File "<stdin>", line 2
    print('hello')
    ^
IndentationError: expected an indented block

Solution:

  • Consistently use 4 spaces for indentation (strongly recommended).
  • Don't mix space and tab keys.

3. NameError (NameError)

A name that has not been defined is used, or it is spelled incorrectly.

>>> prnt('hello')  # 函数名拼错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'prnt' is not defined

Workaround: Check your spelling carefully and make sure the variable or function exists before using it.

Best practice recommendations

Let good habits accompany you from the first day:

  1. Type code by hand: Although copying and pasting is fast, typing it yourself can help you remember the grammar faster and avoid hidden formatting problems.
  2. Pay attention to coding standards:
  • Always use English punctuation.
  • Maintain a consistent indentation style (4 spaces).
  • Use UTF-8 encoding when saving files to avoid Chinese garbled characters.
  1. Learn to read error messages: Error reporting is not scary. It usually tells you clearly "what went wrong". You can start troubleshooting from the first line.
  2. Choose the right tool: It is recommended to use professional editors such as VS Code and PyCharm, and install Python extensions to enjoy functions such as syntax highlighting and automatic completion.

Summary

Today we took the first step in learning Python and gained:

  • Command line mode: The basic environment for executing system commands and running Python scripts.
  • Interactive Mode: An instant feedback environment suitable for quickly experimenting with code, the prompt is>>>
  • Script Mode: Save code as.pyFile, suitable for formal development.
  • Differences in output between the two modes: interactive mode automatically displays results, script mode requiresprint()
  • Good coding habits and error troubleshooting methods will allow you to calmly deal with problems when you encounter them.

Once you have mastered these basic knowledge, you can confidently build your own Python experimental environment. Next, let’s move towards more interesting Python features! 🚀