程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

掌握 Python:基本语法(python基本语法总结)

hfteth 2025-04-30 16:58:39 技术文章 11 ℃

变量和数据类型

几乎每个编程任务的核心都是变量和数据类型。变量就像内存中存储位置的标签,可以在其中保存程序可以操作的数据。Python 是动态类型的,这意味着不必显式声明变量的类型。下面快速浏览了如何使用变量和基本数据类型:

# Variables and simple data types
name = "Ada Lovelace"
age = 28
is_programmer = True

在 Python 中,基本数据类型包括整数 ( int )、浮点数 ( float )、字符串 ( str ) 和布尔值 ( bool )。

列表和词典

当需要在单个变量中存储多个项目时,列表和字典可以派上用场。列表是有序的项目集合,而字典则包含键值对。

# List example
colors = ["red", "green", "blue"]
print(colors[0])  # Prints: red

# Dictionary example
person = {"name": "Ada Lovelace", "profession": "Programmer"}
print(person["name"])  # Prints: Ada Lovelace

循环

循环让我们多次重复一个代码块。Python 为此提供了 for 循环和 while 循环。

For 循环

# For loop with a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

此循环打印 fruits 列表中的每个项目。

While 循环

# While loop example
count = 0
while count < 3:
    print("Programming is fun!")
    count += 1

此循环将继续打印“编程很有趣!”,直到 count 等于 3。

函数

函数是使用 Python def 中的关键字定义的。它们允许我们封装一组指令,这些指令可以在整个程序中重复使用。

# Function example
def greet(name):
    return f"Hello, {name}!"

print(greet("Ada"))

此函数 greet ,采用名称并返回个性化问候语。

条件语句

Python 使用 ifelifelse 基于不同条件的代码有条件地执行。

# if-elif-else example
age = 20
if age < 18:
    print("You're a minor.")
elif age < 65:
    print("You're an adult.")
else:
    print("You're a senior.")

本示例将打印“You're an adult.”,因为年龄为 20 岁。

缩进事项

Python 最显着的特性之一是它使用缩进来定义代码块。与其他使用大括号 {} 表示块的语言不同,Python 使用缩进级别。这使得 Python 代码非常可读,但这也意味着您必须小心间距。

注释和文档字符串

注释(用 # )和 文档字符串(三引号字符串)对于使其他人和未来的自己能够理解您的代码至关重要。它们不是由 Python 执行的。

# This is a single-line comment

"""
This is a docstring
used to describe what a complex piece of code does
"""
最近发表
标签列表