Skip to content

Python 编程第一步

欢迎来到 Python 编程的世界!本章节将引导你编写你的第一个 Python 程序,并介绍一些基本的编程概念。

第一个 Python 程序

让我们从经典的 "Hello, World!" 程序开始。这个程序非常简单,只是在屏幕上打印出 "Hello, World!" 这句话。

使用 Python 解释器

  1. 打开终端:在 Windows 上,可以打开命令提示符或 PowerShell;在 macOS 或 Linux 上,可以打开终端。
  2. 启动 Python 解释器:在终端中输入 pythonpython3,然后按 Enter 键。
  3. 输入代码:在 Python 解释器中,输入以下代码,然后按 Enter 键:
python
print("Hello, World!")
  1. 查看输出:你应该会看到屏幕上显示 "Hello, World!"。
  2. 退出解释器:输入 exit() 或按 Ctrl+Z 然后按 Enter 键(Windows),或按 Ctrl+D(macOS/Linux)。

使用文本编辑器

除了使用 Python 解释器直接运行代码外,你还可以使用文本编辑器创建一个 Python 文件,然后运行它。

  1. 创建文件:使用文本编辑器(如 VS Code、Sublime Text、Notepad++ 等)创建一个名为 hello.py 的文件。
  2. 编写代码:在文件中输入以下代码:
python
print("Hello, World!")
  1. 保存文件:保存文件。
  2. 运行文件:在终端中,导航到文件所在的目录,然后输入 python hello.pypython3 hello.py,按 Enter 键。
  3. 查看输出:你应该会看到屏幕上显示 "Hello, World!"。

基本编程概念

变量

变量是用于存储数据的容器。在 Python 中,你可以通过赋值语句来创建变量。

示例:

python
# 变量示例
name = "Alice"
age = 30
height = 1.65
is_student = False

print(name)
print(age)
print(height)
print(is_student)

输出:

Alice
30
1.65
False

数据类型

Python 有多种数据类型,包括整数、浮点数、字符串、布尔值等。

示例:

python
# 数据类型示例
# 整数
x = 10
print(f"x = {x}, 类型:{type(x)}")

# 浮点数
y = 3.14
print(f"y = {y}, 类型:{type(y)}")

# 字符串
z = "Hello"
print(f"z = {z}, 类型:{type(z)}")

# 布尔值
a = True
print(f"a = {a}, 类型:{type(a)}")

b = False
print(f"b = {b}, 类型:{type(b)}")

输出:

x = 10, 类型:<class 'int'>
y = 3.14, 类型:<class 'float'>
z = Hello, 类型:<class 'str'>
a = True, 类型:<class 'bool'>
b = False, 类型:<class 'bool'>

输入和输出

输出

使用 print() 函数可以在屏幕上显示输出。

示例:

python
# 输出示例
print("Hello, World!")  # 打印字符串
print(123)  # 打印整数
print(3.14)  # 打印浮点数
print(True)  # 打印布尔值

# 打印多个值
print("Hello", "World!")  # 打印多个字符串
print("The answer is", 42)  # 打印字符串和整数

# 使用格式化字符串
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")  # f-string(Python 3.6+)
print("My name is {} and I am {} years old.".format(name, age))  # format 方法
print("My name is %s and I am %d years old." % (name, age))  # % 格式化

输出:

Hello, World!
123
3.14
True
Hello World!
The answer is 42
My name is Alice and I am 30 years old.
My name is Alice and I am 30 years old.
My name is Alice and I am 30 years old.

输入

使用 input() 函数可以从用户那里获取输入。

示例:

python
# 输入示例
name = input("What is your name? ")
print(f"Hello, {name}!")

# 输入数字
age = input("How old are you? ")
print(f"You are {age} years old.")

# 注意:input() 函数返回的是字符串,需要转换为数字才能进行数学运算
age = int(input("How old are you? "))
next_year_age = age + 1
print(f"Next year, you will be {next_year_age} years old.")

输出:

What is your name? Alice
Hello, Alice!
How old are you? 30
You are 30 years old.
How old are you? 30
Next year, you will be 31 years old.

注释

注释是代码中不执行的部分,用于解释代码的功能。在 Python 中,单行注释以 # 开头,多行注释可以使用三引号 '''"""

示例:

python
# 这是一个单行注释
print("Hello, World!")  # 这也是一个单行注释

'''这是一个多行注释
可以跨越多行
'''print("Hello, Python!")

"""
这也是一个多行注释
可以跨越多行
"""
print("Hello, Programming!")

输出:

Hello, World!
Hello, Python!
Hello, Programming!

基本数学运算

Python 可以执行基本的数学运算,如加法、减法、乘法、除法等。

示例:

python
# 基本数学运算
x = 10
y = 3

print(f"x + y = {x + y}")  # 加法
print(f"x - y = {x - y}")  # 减法
print(f"x * y = {x * y}")  # 乘法
print(f"x / y = {x / y}")  # 除法(返回浮点数)
print(f"x % y = {x % y}")  # 取模(返回余数)
print(f"x ** y = {x ** y}")  # 幂(返回 x 的 y 次幂)
print(f"x // y = {x // y}")  # 整除(返回商的整数部分)

输出:

x + y = 13
x - y = 7
x * y = 30
x / y = 3.3333333333333335
x % y = 1
x ** y = 1000
x // y = 3

实践项目

现在,让我们创建一个简单的实践项目,来巩固我们所学的知识。

项目:计算器

创建一个简单的计算器,它可以执行基本的数学运算。

步骤:

  1. 创建文件:创建一个名为 calculator.py 的文件。
  2. 编写代码:在文件中输入以下代码:
python
# 简单计算器

print("简单计算器")
print("可用的操作:")
print("1. 加法")
print("2. 减法")
print("3. 乘法")
print("4. 除法")

# 获取用户选择
choice = input("请选择操作(1-4):")

# 获取两个数字
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))

# 执行操作
if choice == "1":
    result = num1 + num2
    print(f"{num1} + {num2} = {result}")
elif choice == "2":
    result = num1 - num2
    print(f"{num1} - {num2} = {result}")
elif choice == "3":
    result = num1 * num2
    print(f"{num1} * {num2} = {result}")
elif choice == "4":
    if num2 == 0:
        print("错误:除数不能为零!")
    else:
        result = num1 / num2
        print(f"{num1} / {num2} = {result}")
else:
    print("错误:无效的选择!")
  1. 保存文件:保存文件。
  2. 运行文件:在终端中,导航到文件所在的目录,然后输入 python calculator.pypython3 calculator.py,按 Enter 键。
  3. 测试计算器:按照提示输入操作和数字,测试计算器的功能。

项目:猜数字游戏

创建一个猜数字游戏,计算机随机生成一个数字,然后用户尝试猜测它。

步骤:

  1. 创建文件:创建一个名为 guess_number.py 的文件。
  2. 编写代码:在文件中输入以下代码:
python
# 猜数字游戏
import random

# 生成随机数字(1-100)
secret_number = random.randint(1, 100)
print("猜数字游戏")
print("我已经想好了一个 1 到 100 之间的数字。")
print("你有 10 次机会来猜测它。")

# 猜测次数
guesses_taken = 0

# 游戏循环
while guesses_taken < 10:
    # 获取用户猜测
    guess = int(input("请输入你的猜测:"))
    guesses_taken += 1
    
    # 检查猜测
    if guess < secret_number:
        print("你的猜测太小了!")
    elif guess > secret_number:
        print("你的猜测太大了!")
    else:
        print(f"恭喜你!你在 {guesses_taken} 次尝试后猜对了!")
        break

# 如果猜测次数用完
if guesses_taken == 10:
    print(f"很遗憾,你没有在 10 次机会内猜对。")
    print(f"秘密数字是:{secret_number}")
  1. 保存文件:保存文件。
  2. 运行文件:在终端中,导航到文件所在的目录,然后输入 python guess_number.pypython3 guess_number.py,按 Enter 键。
  3. 玩游戏:按照提示输入你的猜测,看看你是否能在 10 次机会内猜对数字。

常见错误和解决方案

在编写 Python 代码时,你可能会遇到一些常见的错误。以下是一些常见错误及其解决方案:

语法错误(SyntaxError)

错误示例:

python
print("Hello, World!)  # 缺少右引号

错误信息:

  File "hello.py", line 1
    print("Hello, World!)  # 缺少右引号
                        ^
SyntaxError: EOL while scanning string literal

解决方案: 检查代码的语法,确保所有的括号、引号等都是成对出现的。

名称错误(NameError)

错误示例:

python
print(hello)  # hello 未定义

错误信息:

  File "hello.py", line 1, in <module>
    print(hello)
NameError: name 'hello' is not defined

解决方案: 确保所有的变量和函数名都已经定义。

类型错误(TypeError)

错误示例:

python
print("The answer is " + 42)  # 尝试连接字符串和整数

错误信息:

  File "hello.py", line 1, in <module>
    print("The answer is " + 42)
TypeError: can only concatenate str (not "int") to str

解决方案: 确保操作的类型是兼容的,例如,使用 str() 函数将整数转换为字符串,或使用 f-string。

索引错误(IndexError)

错误示例:

python
fruits = ["apple", "banana", "cherry"]
print(fruits[3])  # 索引超出范围

错误信息:

  File "hello.py", line 2, in <module>
    print(fruits[3])
IndexError: list index out of range

解决方案: 确保索引在合法的范围内,列表的索引从 0 开始。

键错误(KeyError)

错误示例:

python
person = {"name": "Alice", "age": 30}
print(person["city"])  # 键不存在

错误信息:

  File "hello.py", line 2, in <module>
    print(person["city"])
KeyError: 'city'

解决方案: 确保键存在于字典中,或使用 get() 方法。

总结

本章节介绍了 Python 编程的基础知识,包括:

  1. 编写和运行第一个 Python 程序
  2. 使用变量存储数据
  3. 基本数据类型
  4. 输入和输出
  5. 注释
  6. 基本数学运算
  7. 两个实践项目:计算器和猜数字游戏
  8. 常见错误和解决方案

这些基础知识是 Python 编程的起点,掌握它们后,你可以开始学习更复杂的概念,如条件语句、循环、函数、数据结构等。

祝你在 Python 编程的道路上一切顺利!