打印 Hello Python

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

本挑战的重点是创建一个简单的 Python 脚本,该脚本接收用户输入并生成格式化的输出。此练习巩固了 Python 的基本概念,包括用户输入处理和字符串格式化。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/type_conversion("Type Conversion") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/variables_data_types -.-> lab-61{{"打印 Hello Python"}} python/strings -.-> lab-61{{"打印 Hello Python"}} python/type_conversion -.-> lab-61{{"打印 Hello Python"}} python/build_in_functions -.-> lab-61{{"打印 Hello Python"}} end

交互式 Python 脚本

屏幕左侧的代码编辑器会显示模板文件 hello_python.py。你可以点击该文件打开它,并在看到 TODO 注释的地方编写代码。

任务

  • 通过替换 TODO 注释为有效代码来完成 Python 脚本
  • 在终端中运行脚本以测试你的代码

要求

  • 使用模板文件 /home/labex/project/hello_python.py
  • 替换第一个 TODO 注释为以下代码:
    • 使用 input() 函数
    • 显示提示文本 Enter your name:
    • 将结果存储在名为 name 的变量中
  • 替换第二个 TODO 注释为以下代码:
    • 使用 print() 函数
    • 输出消息 Hello Python, I am <name>!
    • <name> 替换为存储的输入值
    • 在末尾包含感叹号

使用编辑器

  1. 点击左侧文件资源管理器中的文件 hello_python.py 以打开它
  2. 编辑器提供以下功能:
    • Python 代码的语法高亮
    • 自动缩进
    • 行号以便于参考
  3. 编辑完成后:
    • 使用 Ctrl+S(Mac 上为 Cmd+S)保存更改
    • 在终端中使用 python hello_python.py 运行脚本
Python 代码编辑器界面

示例

运行完成的脚本时:

$ python hello_python.py
Enter your name: Alice
Hello Python, I am Alice!
✨ 查看解决方案并练习

总结

在本挑战中,你使用了一个 Python 脚本模板来创建一个交互式程序。此练习向你介绍了基本的编程概念,包括使用代码编辑器、使用 input() 处理用户输入以及使用 print() 创建输出。你还学习了如何从终端运行 Python 脚本,并了解了模板文件如何帮助构建代码结构。