python语法简略教程

Python 是一种高层次、解释型、通用编程语言,具有易读的语法和强大的功能。以下是一个简略的 Python 语法教程:

基本语法

1. 注释

注释是代码中不执行的部分,用于解释代码。

python

复制代码

# 这是单行注释

"""

这是多行注释

也可以用于文档字符串

"""

2. 变量和数据类型

Python 是动态类型语言,不需要显式声明变量类型。

python

复制代码

# 整数

x = 10

# 浮点数

y = 3.14

# 字符串

name = "Python"

# 布尔值

is_valid = True

3. 数据结构

列表(List)

列表是有序的可变集合。

python

复制代码

fruits = ["apple", "banana", "cherry"]

fruits.append("orange") # 添加元素

print(fruits[1]) # 访问元素

元组(Tuple)

元组是有序的不可变集合。

python

复制代码

colors = ("red", "green", "blue")

print(colors[0])

集合(Set)

集合是无序的无重复元素的集合。

python

复制代码

unique_numbers = {1, 2, 3, 2, 1}

print(unique_numbers)

字典(Dictionary)

字典是键值对集合。

python

复制代码

person = {"name": "Alice", "age": 25}

print(person["name"])

4. 条件语句

条件语句用于执行不同的代码块。

python

复制代码

if x > 5:

    print("x is greater than 5")

elif x == 5: 

    print("x is 5")

else: 

    print("x is less than 5")

5. 循环

循环用于重复执行代码块。

for 循环

python

复制代码

for fruit in fruits:

    print(fruit)

while 循环

python

复制代码

count = 0

while count < 5:

    print(count)

    count += 1

6. 函数

函数是可重用的代码块。

python

复制代码

def greet(name):

    return f"Hello, {name}!"

print(greet("Alice"))

7. 类

类是创建对象的蓝图。

python

复制代码

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age def

    greet(self): 

        return f"Hello, my name is {self.name} and I am {self.age} years old." person = Person("Alice", 30)

print(person.greet())

8. 文件操作

Python 提供了简单的文件读写操作。

python

复制代码

# 写文件

with open("example.txt", "w") as file:

    file.write("Hello, world!")

# 读文件

with open("example.txt", "r") as file:

    content = file.read() print(content)

9. 异常处理

异常处理用于捕获和处理运行时错误。

python

复制代码

try:

    result = 10 / 0

except ZeroDivisionError:

    print("Cannot divide by zero!")

finally:

    print("This block is always executed.")

10. 模块和包

模块和包用于组织代码。

python

复制代码

# 导入内置模块

import math

print(math.sqrt(16))

# 导入自定义模块

# 假设有一个文件 mymodule.py,包含一个函数 say_hello

# from mymodule import say_hello

# say_hello()

这是一个简略的 Python 语法介绍,希望能帮助你快速入门 Python 编程。

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值